core Package
Azure AI AgentServerHost core framework: base <xref:AgentServerHost> and shared utilities for Hosted Agents.
Packages
| storage |
Durable state-store client for AgentServer. |
| streaming |
Unified streaming primitive — <xref:EventStream> Protocol +
Pick a backing once at app startup via one of the registry's three
See |
| tasks |
Task subsystem for crash-resilient long-running agents. Provides the <xref:task> and <xref:multi_turn_task> decorators plus supporting types for building Azure AI Hosted Agents that survive container crashes, OOM kills, and redeployments. Key features:
Public API::
|
Modules
| platform_headers |
Public platform HTTP header / wire-contract constants. These constants form the wire contract between the Foundry platform, agent
containers, and downstream storage services. They are shared across the
AgentServer protocol packages (e.g. See the module-level documentation of each constant for its wire semantics. |
Classes
| AgentConfig |
Resolved configuration for an agent server host. All values are populated from environment variables at creation time.
Access via
|
| AgentServerHost |
Agent server host framework for Azure AI Hosted Agent containers. A <xref:starlette.applications.Starlette> subclass providing the protocol-agnostic infrastructure required by all hosted agent containers:
Protocol packages subclass this host to add their own routes:
For multi-protocol agents, compose via cooperative inheritance:
|
| AgentSessionContext |
Note This is an experimental class, and may change at any time. Session context supplied after a process is restored from a snapshot. |
| FoundryAgentRequestContext |
Platform-supplied, request-scoped identity context. Populated by the protocol endpoint from inbound platform headers on every
request. All fields are |
| FoundryOriginalSubject |
Note This is an experimental class, and may change at any time. Invocation-local original-subject assertions, separate from model authentication. These values are not proof of identity. The receiving model service must establish provenance and invocation binding before using them. This draft does not change model authorization or enable budget enforcement. |
| InboundRequestLoggingMiddleware |
Pure-ASGI middleware that logs inbound HTTP requests. Unlike Wired automatically by AgentServerHost so that all protocol hosts (responses, invocations, etc.) get consistent inbound logging. |
| RequestIdMiddleware |
Pure-ASGI middleware that sets The resolved request ID is stored in Unlike |
Functions
build_server_version
Build a standard version segment for the x-platform-server header.
Format: {sdk_name}/{version} (python/{major}.{minor})
Protocol packages call this during host initialisation and pass the result to register_server_version.
build_server_version(sdk_name: str, version: str) -> str
Parameters
| Name | Description |
|---|---|
|
sdk_name
Required
|
The SDK identifier
(e.g., |
|
version
Required
|
The package version string (e.g., |
Returns
| Type | Description |
|---|---|
|
A formatted version string. |
Exceptions
| Type | Description |
|---|---|
|
If sdk_name or version is empty. |
configure_observability
Default observability setup: console logging + tracing/OTel export.
Attaches a formatted StreamHandler to the root logger so that
both SDK and user logging.info() calls are visible on the console.
Then configures OpenTelemetry tracing and log export (Azure Monitor
and/or OTLP) when a connection string or OTLP endpoint is available.
Pass this function (or a custom replacement) as the
configure_observability parameter of AgentServerHost.
Pass None to disable all SDK-managed observability setup.
configure_observability(*, connection_string: str | None = None, log_level: str | None = None, enable_sensitive_data: bool = False, instrumentation_options: dict[str, dict[str, Any]] | None = None) -> None
Keyword-Only Parameters
| Name | Description |
|---|---|
|
connection_string
|
Application Insights connection string. Default value: None
|
|
log_level
|
Log level name (e.g. Default value: None
|
|
enable_sensitive_data
|
Enable sensitive data recording (prompts, tool arguments, results) for Agent Framework SDK instrumentation. Defaults to False. Default value: False
|
|
instrumentation_options
|
Per-library OpenTelemetry instrumentation
options. Azure SDK, HTTPX, Requests, urllib, and urllib3 instrumentation
are disabled by default; set a library's Default value: None
|
create_error_response
Build a JSONResponse with the standard error envelope.
create_error_response(code: str, message: str, *, status_code: int, error_type: str | None = None, details: list[dict[str, Any]] | None = None, headers: dict[str, str] | None = None) -> JSONResponse
Parameters
| Name | Description |
|---|---|
|
code
Required
|
Machine-readable error code (e.g. |
|
message
Required
|
Human-readable error message. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
status_code
|
HTTP status code for the response. |
|
error_type
|
Optional error type classification string. When
provided, included as Default value: None
|
|
details
|
Child error objects, each with at least Default value: None
|
|
headers
|
Extra HTTP headers to include on the response. Default value: None
|
Returns
| Type | Description |
|---|---|
|
<xref:JSONResponse>
|
A ready-to-send JSON error response. |
detach_context
Detach a context previously attached by set_current_span.
Best-effort no-op when token is None or when the token is no
longer the current OpenTelemetry context.
detach_context(token: Any) -> None
Parameters
| Name | Description |
|---|---|
|
token
Required
|
The token returned by set_current_span. |
end_span
End a span, optionally recording an error first.
No-op when span is None.
end_span(span: Any, exc: BaseException | None = None) -> None
Parameters
| Name | Description |
|---|---|
|
span
Required
|
The OTel span to end, or |
|
exc
|
Optional exception to record before ending. Default value: None
|
experimental
Add an experimental note and runtime warning to a class or function.
experimental(wrapped: type[T] | Callable[[P], T]) -> type[T] | Callable[[P], T]
Parameters
| Name | Description |
|---|---|
|
wrapped
Required
|
Class or callable to mark as experimental. |
Returns
| Type | Description |
|---|---|
|
The wrapped class or callable. |
flush_spans
Flush all pending spans from the TracerProvider.
The BatchSpanProcessor buffers spans and exports them on a timer
(default 5 seconds). In hosted sandbox environments the platform may
suspend the process immediately after an HTTP response is sent, before
the batch timer fires. Calling this function after ending the request
span ensures that all child spans — including short-lived ones created
by third-party tracers (e.g. LangChain/LangGraph per-node spans) — are
exported before the sandbox is frozen.
No-op when the OTel SDK is not installed or the provider does not
support force_flush.
flush_spans(timeout_millis: int = 5000) -> None
Parameters
| Name | Description |
|---|---|
|
timeout_millis
|
Maximum time to wait for the flush, in milliseconds. Defaults to 5000 (5 seconds). Default value: 5000
|
flush_spans_async
Note
This is an experimental method, and may change at any time.
Non-blocking variant of flush_spans.
TracerProvider.force_flush blocks the calling thread until the exporter
drains its queue. On the request hot path – which runs inside an async
handler – that blocks the asyncio event loop, serialising every concurrent
request behind a single export (head-of-line blocking). Offload the
blocking call to the default thread pool so the event loop stays free to
send the response and service other requests concurrently.
Cancellation is deferred until the flush completes, including when the worker is still queued. Exporter failures are handled by flush_spans.
No-op when the OTel SDK is not installed or the provider does not support
force_flush.
async flush_spans_async(timeout_millis: int = 5000) -> None
Parameters
| Name | Description |
|---|---|
|
timeout_millis
|
Maximum time to wait for the flush, in milliseconds. Defaults to 5000 (5 seconds). Default value: 5000
|
get_request_context
Return the platform context for the current request.
Safe to call from anywhere during request processing. When no context has
been established (e.g. outside a request, or local development), an empty
FoundryAgentRequestContext with all-None fields is returned.
get_request_context() -> FoundryAgentRequestContext
Returns
| Type | Description |
|---|---|
|
The current request-scoped platform context. |
read_request_id
Return the request ID resolved by RequestIdMiddleware.
Reads the value the middleware stored in the ASGI scope["state"] so
protocol packages can correlate a request without depending on the internal
state-key name. Returns None when the middleware is not installed or the
value is absent.
read_request_id(scope: Mapping[str, Any]) -> str | None
Parameters
| Name | Description |
|---|---|
|
scope
Required
|
The ASGI scope (or any mapping carrying a |
Returns
| Type | Description |
|---|---|
|
The resolved |
record_error
Record an exception and ERROR status on a span.
Sets error.type and otel.status.description per OTel
semantic conventions.
record_error(span: Any, exc: BaseException) -> None
Parameters
| Name | Description |
|---|---|
|
span
Required
|
The OTel span, or |
|
exc
Required
|
The exception to record. |
reset_request_context
Restore the request context to its previous value (internal).
reset_request_context(token: Token[FoundryAgentRequestContext]) -> None
Parameters
| Name | Description |
|---|---|
|
token
Required
|
The token returned by set_request_context. |
resolve_state_subdir
Resolve an on-disk state subdirectory under the agentserver state root.
The root is AGENTSERVER_STATE_ROOT (the single operator knob), or
~/.agentserver when unset. Each subsystem owns and passes its own
subdirectory name (e.g. "tasks"); the core layer does not enumerate
or reserve names. The path is not created on disk — callers mkdir lazily
on first write.
resolve_state_subdir(name: str) -> Path
Parameters
| Name | Description |
|---|---|
|
name
Required
|
The subdirectory name owned by the calling subsystem. |
Returns
| Type | Description |
|---|---|
|
<xref:Path>
|
The resolved subdirectory path under the state root. |
schedule_flush_spans
Note
This is an experimental method, and may change at any time.
Schedule a coalesced background span flush and return immediately.
Unlike flush_spans / flush_spans_async, this does not delay the caller (i.e. the HTTP response) by the export duration. At most one background flush task runs at a time: calls made while a flush is in flight are coalesced into a single follow-up flush rather than spawning a task per request, so neither the retained task reference nor the executor queue grows with the request rate. Falls back to a synchronous flush when no event loop is running.
Note
Only safe when the hosting platform guarantees a brief drain window
before it suspends/freezes the process after sending a response;
otherwise the final request's spans may be lost.
schedule_flush_spans(timeout_millis: int = 5000) -> None
Parameters
| Name | Description |
|---|---|
|
timeout_millis
|
Maximum time to wait for the flush, in milliseconds. Defaults to 5000 (5 seconds). Default value: 5000
|
set_current_span
Set a span as the current span in the OTel context.
This makes span the active parent for any child spans created by downstream code (e.g. framework handlers). Without this, spans created inside the handler would become siblings rather than children of span.
Returns a context token that must be passed to
detach_context when the scope ends. No-op when span
is None.
set_current_span(span: Any) -> Any
Parameters
| Name | Description |
|---|---|
|
span
Required
|
The OTel span to make current, or None. |
Returns
| Type | Description |
|---|---|
|
A context token, or None. |
set_request_context
Bind context as the current request context (internal).
Called by protocol endpoints at the start of request handling. The returned token should be passed to reset_request_context when the request completes to avoid leaking context across requests on the same task.
set_request_context(context: FoundryAgentRequestContext) -> Token[FoundryAgentRequestContext]
Parameters
| Name | Description |
|---|---|
|
context
Required
|
The request context to bind. |
Returns
| Type | Description |
|---|---|
|
A reset token for restoring the previous value. |
trace_stream
Wrap a streaming body so the span covers the full transmission.
Yields chunks unchanged. Ends the span when the iterator is exhausted or raises an exception.
async trace_stream(iterator: AsyncIterable[str | bytes | memoryview], span: Any) -> AsyncIterator[str | bytes | memoryview]
Parameters
| Name | Description |
|---|---|
|
iterator
Required
|
AsyncIterable[<xref:azure.ai.agentserver.core.StreamContent>]
The async iterable to wrap. |
|
span
Required
|
The OTel span to end on completion, or |
Returns
| Type | Description |
|---|---|
|
AsyncIterator[<xref:azure.ai.agentserver.core.StreamContent>]
|
An async iterator yielding chunks unchanged. |