What are hosted agents?

When you build agentic applications by using open-source frameworks, you typically manage many cross-cutting concerns: containerization, web server setup, security, memory persistence, scaling, instrumentation, and version rollbacks. These tasks become even more challenging in heterogeneous cloud environments.

Hosted agents in Foundry Agent Service solve these challenges for Microsoft Foundry users. Hosted agents call models from the Foundry model catalog to perform reasoning while your custom code handles orchestration. By using this managed platform, you can deploy and operate AI agents securely and at scale. You can use your custom agent code or a preferred agent framework with streamlined deployment and management.

If you're exploring hosted agents with an AI coding agent, the Microsoft Foundry Skill can help connect these concepts to implementation, deployment, and operations tasks.

When to use hosted agents

Choose Hosted agents over prompt-based agents when you need to:

  • Bring your own code - use any framework (Agent Framework, LangGraph, Semantic Kernel, or custom code) rather than prompt-only definitions.
  • Use custom protocols - accept webhooks or non-OpenAI payloads via the Invocations protocol.
  • Control compute resources - specify CPU and memory for your agent's sandbox.
  • Run stateful workloads - persist files and state across turns via $HOME and the /files endpoint.
  • Run long-lived work resiliently - preserve in-progress agent work across process interruptions and replay streamed results to reconnecting clients.

How it works

You package your agent as a container image and push it to Azure Container Registry. When you deploy, Agent Service pulls the image, assigns a dedicated Microsoft Entra ID (agent identity), and exposes a dedicated endpoint for the agent.

At runtime, Agent Service provisions compute for the session and routes requests to your container. Your agent code handles those requests and can call Foundry models, Toolbox tools, and downstream Azure services using its agent identity. The platform handles scaling, session state persistence, observability, and lifecycle management.

The following diagram shows how responsibility is divided. You own the code that runs inside the sandbox. The platform owns the endpoint, identity, scaling, and session state around it.

Diagram that shows the architecture of a hosted agent. Clients call a dedicated agent endpoint over the Responses, Invocations, Invocations (WebSocket), or Activity protocol, authenticated with Microsoft Entra ID. Agent Service holds the container image, agent versions, agent identity, and conversations, and starts a per-session VM-isolated sandbox that moves between active, idle, and resumed states. The sandbox calls models, a Toolbox MCP endpoint, and your own Azure services.

Important

When you use Hosted Agents with other Microsoft products and services, you must read all relevant documentation for such products and services and understand related risks and compliance considerations.

If you use Hosted Agent with any third-party servers, agents, code, or non-Azure Direct models ("Third-Party Systems"), you do so at your own risk. Third-Party Systems are Non-Microsoft Products under the Microsoft Product Terms and are governed by their own third-party license terms. You're responsible for any usage and associated costs.

We recommend reviewing all data being shared with and received from Third-Party Systems and being cognizant of third-party practices for handling, sharing, retention, and location of data. Similarly, if you connect to or integrate with non-Foundry Microsoft services and features, it is important to review their data practices. It is your responsibility to manage whether your data will flow outside of your organization's compliance and geographic boundaries and any related implications, and that appropriate permissions, boundaries, and approvals are provisioned.

You're responsible for carefully reviewing and testing applications you build in the context of your specific use cases and making all appropriate decisions and customizations. This includes implementing your own responsible AI mitigations, such as metaprompts, content filters, or other safety systems, and ensuring your applications meet appropriate quality, reliability, security, and trustworthiness standards. See the Foundry Agent Service transparency note.

Key concepts

Hosted agents

Hosted agents are containerized agentic AI applications that run on Agent Service. Unlike prompt-based agents—which are defined entirely through prompts and tool configuration in the Foundry portal—Hosted agents are your own code packaged as a container image. You choose the framework, control the runtime behavior, and deploy the image to Microsoft-managed infrastructure.

The platform automatically manages the container lifecycle based on activity, provisioning resources when you create a version and deprovisioning when the idle timeout is reached.

Framework hosting integrations

Use the hosting integration for your framework to connect your agent to Foundry:

These integrations provide the protocol handlers for your agent. Follow the linked guide for setup and deployment steps.

Isolation model

Hosted agents run in per-session VM-isolated sandboxes. Ordinary volume-backed sessions have a persistent filesystem ($HOME and /files), enabling scale-to-zero with stateful resume. Sessions are isolated from each other. Memory-snapshot sessions have different persistence behavior.

Protocols: Responses, Invocations, and Invocations (WebSocket)

Hosted agent containers can expose Responses, Invocations, Invocations (WebSocket), or native Activity. Each protocol is provided by a lightweight library that handles the HTTP or WebSocket server, health checks, and OpenTelemetry integration. The Responses, Invocations, and Invocations (WebSocket) protocols are available in all regions that support Hosted agents.

Which protocol should I use?

Scenario Protocol Why
Conversational chatbot or assistant Responses The platform manages conversation history, streaming events, and session lifecycle—use any OpenAI-compatible SDK as the client.
Multi-turn Q&A with RAG or tools Responses Built-in conversation ID threading and tool result handling.
Background / async processing Responses background: true with platform-managed polling and cancellation. Opt in separately when the handler must recover after a process interruption.
Responses-based agent published to Teams or Microsoft 365 Responses with an Activity channel endpoint The platform translates channel activities to Responses requests and converts the output for channel delivery.
Native channel message, event, or card-action handlers Activity Your container hosts Microsoft 365 Agents SDK handlers directly. See Native Activity protocol for supported interaction patterns and setup considerations.
Webhook receiver (GitHub, Stripe, Jira, etc.) Invocations The external system sends its own payload format—you can't change it to match /responses.
Non-conversational processing (classification, extraction, batch) Invocations The input is structured data, not a chat message. Arbitrary JSON in, arbitrary JSON out.
Custom streaming protocol (AG-UI, etc.) Invocations AG-UI and other agent-UI protocols aren't OpenAI-compatible—you need raw SSE control.
Protocol bridge (GitHub Copilot, proprietary systems) Invocations The caller has its own protocol that doesn't map to /responses.
Real-time voice agent (microphone in, speech out) Invocations (WebSocket) Bidirectional streaming over a single persistent connection. Pair with Pipecat, LiveKit, or Voice Live in your container. See Build a voice agent.

Tip

Not sure? Start with Responses. You can always add an Invocations endpoint later—a Hosted agent can support both protocols simultaneously.

The protocol you choose determines the payload your container receives, and how much of the session, streaming, and background lifecycle the platform manages for you. A single agent can support more than one protocol, so this choice isn't permanent. Use the following decision tree to pick a starting point.

Diagram that shows Activity for channel events, Invocations WebSocket for real-time voice, Responses for chat, and Invocations for other workloads.

Protocol comparison

Aspect Responses Invocations Activity
Best for Most agents—the platform manages conversation history, streaming lifecycle, and background execution Agents that need full HTTP control, custom payloads, or long-running async workflows Native channel messages, events, and invoke handlers
Payload OpenAI-compatible /responses contract Arbitrary JSON via /invocations—you define the schema Activity Protocol activities via /activity/messages
Client SDK Any OpenAI-compatible SDK (Python, JS, C#) works out of the box Custom client—you define the contract Microsoft 365 Agents SDK and an Activity-compatible channel or test client
Session history Platform-managed via conversation ID You manage sessions (in-memory, Cosmos DB, etc.) Application-managed model history; turn-state defaults differ by SDK language
Streaming Platform-managed ResponseEventStream with lifecycle events Raw SSE—you format and write events directly Channel-specific reply mechanism; support depends on the channel and publishing experience
Background / long-running Built-in background mode and polling; optional resilient recovery for stored background responses Resilient tasks in the AgentServer SDK; you define polling or streaming endpoints Your application implements recovery for interrupted work

Background mode and resilient execution solve different problems. Background mode lets work continue after the initiating request returns. Resilient execution preserves work after the hosting process stops. For the recovery model and application responsibilities, see Resilience for long-running hosted agents.

Additional protocols

Hosted agents support two Activity integration paths. A Responses-based container uses the platform's channel translation. A native Activity container uses the Activity adapter and Microsoft 365 Agents SDK handlers directly. Enabling a public Activity endpoint alone doesn't select the native implementation. See Native Activity protocol.

The A2A protocol supports agent-to-agent delegation. Supported protocols can be combined in a single agent.

For hosted agents, the A2A endpoint supports only A2A v1.0. A request that doesn't specify a version gets v0.3, so set the A2A-Version: 1.0 header or the a2a-version=1.0 query string on each request. Send each request as a single-turn SendMessage call: don't set contextId or taskId on the message, and don't set configuration.returnImmediately to true. GetTask isn't supported. Requests that use another version, set those fields, or call GetTask return an error with reason HOSTED_AGENT_NOT_SUPPORTED.

Agent identity and endpoint

Each hosted agent deployed to a Foundry project gets its own dedicated Microsoft Entra ID (agent identity) and dedicated endpoint—both created automatically at deploy time. You don't need to configure managed identities or routing manually.

The endpoint is available immediately after deployment—publishing isn't required for programmatic access:

  • Responses: {project_endpoint}/agents/{name}/endpoint/protocols/openai/responses
  • Invocations: {project_endpoint}/agents/{name}/endpoint/protocols/invocations
  • Invocations (WebSocket): wss://{account}.services.ai.azure.com/api/projects/{project}/agents/{name}/endpoint/protocols/invocations_ws?api-version=v1
  • A2A v1.0 (GA): {project_endpoint}/agents/{name}/endpoint/protocols/a2a
  • Activity: Use the public channel messaging endpoint configured by the publishing workflow. It isn't the container route /activity/messages.

Which endpoints are active depends on the protocols declared in the agent version definition. Set this definition in the azure.ai.agent service in azure.yaml when using azd, or via protocol_versions when using the SDK.

Two identities are involved:

Identity Scope Purpose
Microsoft Entra ID (agent identity, per-agent) Created automatically at deploy time The identity the agent container authenticates with at runtime. Used for model invocation, tool access, and downstream Azure services.
Project managed identity (project-wide) System-assigned on the Foundry project Used by the platform for infrastructure operations (for example, Container Registry Repository Reader on the container registry). Not the agent's runtime identity.

The agent identity can access model inferencing through the project endpoint and session storage by default. For external resources (for example, your own Azure Storage), assign RBAC roles manually to the agent's Microsoft Entra ID. For more information, see Agent access beyond defaults.

When integrated via Microsoft 365 channels (for example, Teams), hosted agents can operate in two identity modes depending on how they're invoked:

  • User-invoked scenarios (interactive): If a user token is present, the platform supports OAuth 2.0 On-Behalf-Of (OBO) flows. In this case, the agent can call downstream services on behalf of the user using the user's delegated permissions, subject to Microsoft Entra ID tenant policies.

  • Autonomous or background scenarios: If no user token is available, the agent authenticates using its own Microsoft Entra ID (agent identity), typically via managed identity, to access downstream services.

In both cases, the agent retains its dedicated Microsoft Entra ID for authentication, authorization, and auditability.

For user delegation with MCP and other tools, connect those tools through a Foundry toolbox. Use the integration for your agent framework to connect to the toolbox. See Toolbox in Foundry.

For more information, see Agent applications and Agent identity concepts.

Sessions, conversations, and the state store

Hosted agents use sessions, conversations, and the state store to manage state. How they work depends on the protocol.

Sessions

A session ID identifies a logical session with persisted state, including $HOME and files uploaded via the /files endpoint. The platform provisions compute on demand and restores persisted state onto it.

The filesystem persistence described here applies to ordinary volume-backed sessions. Memory snapshots restore a version's startup baseline rather than an ongoing session's local files or process memory. See Enable memory snapshots for hosted agents.

  • State persistence: $HOME and /files content are persisted across turns and across idle periods. When compute goes idle and is brought back (on new or existing infrastructure), the session's state is automatically restored.
  • Isolation: Each session is isolated from other sessions.
  • Automatic lifecycle: Sessions are created on first use. The platform provisions and deprovisions compute automatically.
  • Session lifetime: You can configure the idle timeout per agent version from 2 through 240 minutes (4 hours), with a 15-minute default. If no request arrives within that window, the platform deprovisions the compute and persists the session state. A background response that's still running keeps the session active, even if it produces no output for longer than the idle timeout. The platform permanently deletes a session after 30 days of inactivity.
  • Session management APIs: List sessions, terminate sessions, and upload or download files per session.

Session compute

Each session owns a compute resource named default. The session is the logical workload and isolation boundary; the compute is its runtime handle. The compute ID stays stable even when the backing sandbox changes.

The agent version defines the image, resources, baseline policies, and optional compute primitives. The preview session compute APIs expose runtime operations: discovery, explicit start, exec, container log stream, ports, lifecycle-policy changes, and read-only egress summaries.

Capabilities describe operation support, not caller permission or instantaneous readiness. Exec runs a process inside the runtime; it doesn't submit an agent-protocol invocation or create conversation history. For these operations and their authorization requirements, see Manage hosted agent session compute.

Conversations

A conversation ID is a durable record of conversation history (messages, tool calls, and responses) stored in Foundry.

  • Persistence: Conversation history is stored in Foundry and persists independently of compute state.
  • Cross-channel access: Users can access the same conversation from the playground, API, Teams, or other published channels.

State store

The state store is a durable, server-backed key-value store for application state that the platform doesn't manage for you. A store holds keyed JSON items and is addressed by a caller-chosen store name.

  • Persistence: Foundry stores items and persists them independently of compute state, so they survive container crashes, restarts, and idle eviction.
  • Isolation: Each store name is an independent partition. A store can also partition its items per end user, so one store name is safe to share across the users of a multitenant agent.
  • Item lifetime: A store-level idle window ages out items, with a default of 30 days. Writes renew the window, and you can configure a store to never expire its items.
  • Any framework: Because the store is a general-purpose key-value API, an agent can use it to hold framework checkpoints for a bring-your-own framework such as LangGraph or Microsoft Agent Framework, alongside its own application state.

For more information, see Durable state store for hosted agents.

How sessions and conversations work with each protocol

Responses protocol: conversation ID is the primary concept. The platform manages conversation history automatically and associates a session ID with each conversation. The platform returns the session ID to the client, which can use it to upload files via the /files endpoint, making those files available to the conversation's compute.

Invocations protocol: session ID is the primary concept. The client manages the session ID directly to maintain state across interactions. The client can upload content via the /files endpoint using the session ID to make it available for the session. There's no platform-managed conversation history—you manage state in your own code.

Native Activity protocol: Your application manages model conversation history separately from the state saved by the Activity SDK. Python defaults to Foundry storage when hosted; .NET defaults to in-memory storage. See Conversation state and history.

Session compute lifecycle

State What happens
Active Compute is running. Requests are routed to it. $HOME and /files content are available.
Idle No requests for the configured idle timeout. The platform deprovisions compute and persists session state ($HOME, /files).
Resumed Same session ID is referenced again. Platform provisions new compute and restores persisted state.

Compute follows the session, not the individual request. The platform provisions a sandbox when a session starts and releases it when the configured idle timeout elapses after the most recent request. When the session resumes, the platform restores $HOME and /files, so your code finds the files it wrote earlier. The following diagram shows how a request moves through these states.

Sequence diagram of a hosted agent request. The client sends a request with a conversation or session ID, Agent Service authenticates it with Microsoft Entra ID and provisions compute, and the sandbox restores $HOME and /files. Your code loops over model calls and Toolbox tool calls over MCP, then returns a response. After the configured idle timeout elapses without a request, the platform deprovisions compute and persists session state, and the next request restores it onto new compute.

Security and data handling

Treat a Hosted agent like production application code.

Important

Use third-party systems at your own risk, and always implement appropriate responsible AI mitigations. You're responsible for managing all data that might flow outside of your organization's compliance and geographic boundaries. Learn more.

  • Don't put secrets in container images or environment variables. Use managed identities and connections, and store secrets in a managed secret store. For guidance, see Set up a Key Vault connection.
  • Be careful with non-Microsoft tools and servers. If your agent calls tools backed by non-Microsoft services, some data might flow to those services. Review data sharing, retention, and location policies for any non-Microsoft service you connect.
  • Separate uploads from trusted application files. Uploads use the session's $HOME. If upload callers aren't trusted to change agent behavior, don't automatically load code, configuration, or trusted instructions from upload-writable paths. Keep session data separate from application files. See Python and C# configuration examples, including the Python PYTHONNOUSERSITE setting and limitations for skill and harness agents.

Platform details

Versioning

Each call to create a version produces an immutable agent version. The version is a snapshot of the container image, resource allocation, environment variables, and protocol configuration. To update your agent, create and deploy a new version.

An agent endpoint serves one version at a time and routes 100% of its traffic to that version. Traffic splitting between versions isn't supported.

Environment variables are the primary mechanism for passing configuration to your container at runtime (for example, the project endpoint, model deployment name, and custom settings). They're set per version and are immutable once the version is created.

Observability

Hosted agents provide built-in observability. The platform automatically injects an Application Insights connection string into your agent container via environment variables. Agents that use the protocol libraries emit OpenTelemetry traces by default, which appear in the linked Application Insights resource under Investigate > Transaction search or Performance.

For configuration and analysis guidance, see Enable tracing in your project.

Toolbox in Foundry

Hosted agents have full access to Foundry-managed tools, including Code Interpreter, Web Search (with Grounding with Bing Custom Search), Foundry IQ (Azure AI Search), OpenAPI, MCP, A2A, Skills, and more. You connect these tools through a Toolbox MCP endpoint provisioned in your Foundry project rather than by adding them directly to the agent definition. The toolbox gives you consolidated authentication across OAuth identity passthrough, agent identity, key-based auth, and more.

Use the Toolbox integration provided by your agent framework. For frameworks without a Toolbox integration, connect through a compatible MCP client. For framework examples, see Integrate the toolbox into your agent. For hosted-agent setup with Microsoft Agent Framework or LangGraph, see Use a toolbox with a hosted agent.

Language support

Hosted agents support Python and C#. Use a framework hosting integration when available, or use the framework-agnostic protocol libraries for custom agent code. For code examples, see the Python samples and C# samples in the foundry-samples repository.

Sandbox sizes

Hosted agent sandboxes support the following CPU and memory combinations:

CPU Memory
0.25 vCPU 0.5 GiB
0.5 vCPU 1 GiB
1 vCPU 2 GiB
2 vCPU 4 GiB
4 vCPU 8 GiB
8 vCPU 16 GiB
16 vCPU 32 GiB

Session storage

Each session has persistent storage under $HOME. Files saved there remain available when the session resumes after an idle period. Files uploaded through the session's /files endpoint share this storage.

Maximum persistent storage

CPU Maximum $HOME storage
0.25 vCPU Up to 3 GiB
0.5 vCPU Up to 6.4 GiB
1 vCPU Up to 12.8 GiB
2 vCPU Up to 28 GiB
4 vCPU Up to 60 GiB
8 vCPU Up to 100 GiB
16 vCPU Up to 100 GiB

These values are upper limits before accounting for your container image, not guaranteed allocations. The platform determines the actual storage allocation using your CPU tier and image size after conversion. A larger image can leave less space for persistent files.

How image size affects persistent storage

The following table shows the $HOME allocation for a new session when its image is the maximum supported size for the selected CPU tier:

CPU Maximum image size after conversion $HOME storage with an image of that size
0.25 vCPU 2 GiB 1 GiB
0.5 vCPU 3 GiB 4 GiB
1 vCPU 5 GiB 8.8 GiB
2 vCPU 20 GiB 12 GiB
4 vCPU 40 GiB 28 GiB
8 vCPU 40 GiB 92 GiB
16 vCPU 40 GiB 100 GiB

For example, an 8-vCPU session with a 40-GiB converted image receives 92 GiB of persistent storage. With a smaller image, it can receive up to 100 GiB.

The container image is stored separately from $HOME; it doesn't occupy the persistent-storage allocation shown above. Changing CPU allocation doesn't resize an existing session's persistent storage. For image-size limits, see Hosted-agent image and storage limits.

Scaling and right-sizing

Hosted agents scale per session, not per replica. The platform creates a new VM-isolated sandbox for each session on demand and keeps its compute active while requests continue. Each request resets the idle timer. When the configured idle timeout elapses after the most recent request, the platform deprovisions the sandbox compute and persists the session state.

The idle timeout can be 2 through 240 minutes (4 hours) and defaults to 15 minutes. The platform permanently deletes a session after 30 days of inactivity. There's no replica count to configure and no warm pool to size.

Because every session runs in its own sandbox, the CPU and memory values you set on an agent version describe a single session, not the aggregate footprint of the agent. Billing is based on the CPU and memory allocated to each active session, not what your code uses, so oversizing multiplies cost by your concurrency. For details, see Pricing.

To right-size, run a representative workload and inspect resource usage in the linked Application Insights resource:

  1. Open the App Insights resource in the Azure portal and select Investigate > Performance.
  2. Review CPU, available memory, request rate, and average request duration over the time range you tested.

Compare the observed peaks against the CPU and memory you allocated. If sustained peaks exceed roughly 70% of allocation, raise the next agent version's allocation; if peaks stay well below, lower it to reduce cost. Always retest after a change, because each new version is immutable.

Private networking

Hosted agents support deployment within network-isolated Foundry resources and can use a customer-provided Azure Virtual Network for outbound traffic. This enables agents in network-isolated Foundry deployments to reach private resources such as databases or internal APIs. For more information, see Configure virtual networks.

Planned hosted-session capacity depends on the delegated subnet size. Each session runs in its own VM-isolated sandbox. The platform optimizes VNet injection to limit IP allocation, network attachment, and communication overhead.

Subnet capacity must also cover project-level networking components and upgrade headroom, and regional session quotas apply. For capacity planning, see Planned hosted-session capacities by subnet size.

Note

Foundry projects created after June 25, 2026 support a private (network-secured) Azure Container Registry for your agent image. Projects created before that date require the registry to remain reachable over its public endpoint. Existing projects aren't affected. For more information, see Limitations.

Limits, pricing, and availability

Pricing

Managed hosting runtime billing is based on the CPU and memory allocated to each session's sandbox for the time its compute runs. Model and tool usage is billed separately. For current rates, see the Foundry pricing page.

How session billing works:

  • Each session is billed separately. Every session runs in its own sandbox, so cost grows with the number of sessions running at the same time. There's no replica or instance count.
  • Allocation, not utilization, is billed. Billing uses the CPU and memory allocated from the values you set on the agent version, not the CPU and memory your code actually uses.
  • Idle time before suspension is billed. Idle compute remains billable until the platform suspends the sandbox, normally after the configured idle timeout. While the session is suspended, compute usage isn't billed until it resumes.
  • Stopping a session ends billing. When you stop a session, billing ends when its compute stops. Final billing records can arrive later. Deleting a running session terminates its compute. Additional compute usage can accrue while termination is in progress.

To reduce cost:

  • Stop each session when its work is done instead of waiting for the idle timeout.
  • Use a shorter idle timeout for agents that don't need to keep compute running between requests. A shorter timeout means more cold starts when sessions resume.
  • Right-size CPU and memory as described in Scaling and right-sizing.

Region availability

Hosted agents are currently available in the following regions:

  • Australia East
  • Brazil South
  • Canada Central
  • Canada East
  • Central US
  • East US
  • East US 2
  • France Central
  • Germany West Central
  • Italy North
  • Japan East
  • Japan West
  • Korea Central
  • North Central US
  • Norway East
  • Poland Central
  • South Africa North
  • South Central US
  • South India
  • Southeast Asia
  • Spain Central
  • Sweden Central
  • Switzerland North
  • Switzerland West
  • UAE North
  • UK South
  • UK West
  • West Central US
  • West Europe
  • West US
  • West US 3

Note

This list will be updated as additional regions become available.

Next steps

Task Link
Build and deploy your first Hosted agent Quickstart: Deploy your first Hosted agent
Deploy using the Foundry SDK Deploy a Hosted agent by using the Foundry SDK
Update, delete, invoke, or stream logs Manage Hosted agents
Set up tracing and monitoring Enable tracing in your project
Optimize agent instructions automatically Agent optimizer overview
Evaluate agent performance Agent evaluators
Publish to Teams, Microsoft 365, or custom apps Agent applications
Browse code samples Python samples and C# samples