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 + streams registry.

Pick a backing once at app startup via one of the registry's three use_* configurators, then obtain stream instances anywhere in your process via await streams.get_or_create(id) and program against the <xref:EventStream> Protocol.

See docs/streaming-guide.md for the developer guide (registry API, backings, per-turn id convention, exception/wire mapping, third-party-impl peer-registry pattern).

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:

  • Two decorators — @task (one-shot, single run, ephemeral) and @multi_turn_task (chain — every return X is one turn; chain stays alive in suspended between turns).
  • Lifecycle automation — .run() and .start() automatically start, resume, or recover tasks based on their current state.
  • Entry mode — ctx.entry_mode tells the handler whether it was entered fresh, resumed from suspension, or recovered from a crash.
  • RetryPolicy — configurable retry with exponential, fixed, or linear backoff (see <xref:RetryPolicy> presets).
  • Streaming lives in streaming; handlers call stream = await streams.get_or_create(invocation_id) to obtain a stream handle; TaskRun itself is NOT iterable.

Public API::

from azure.ai.agentserver.core.tasks import (
    task,
    multi_turn_task,
    Task,
    MultiTurnTask,
    RetryPolicy,
    TaskContext,
    TaskRun,
    TaskFailed,
    TaskCancelled,
    TaskDeferred,
    TaskConflictError,
    LastInputIdPreconditionFailed,
    SteeringQueueFull,
    InputTooLarge,
    JSONValue,
    TaskErrorDict,
    TaskExhaustedRetriesErrorDict,
    EntryMode,
)

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. azure-ai-agentserver-responses and azure-ai-agentserver-invocations), which compose on top of this core package; this module is the supported public surface for those constants.

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 app.config:


   app = InvocationAgentServerHost()
   print(app.config.agent_name)
   print(app.config.project_endpoint)
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:

  • Health probe (GET /readiness)

  • Memory snapshot lifecycle hooks

  • Graceful shutdown handling (SIGTERM, configurable timeout)

  • OpenTelemetry tracing with Azure Monitor and OTLP exporters

  • Hypercorn-based ASGI server with HTTP/1.1

Protocol packages subclass this host to add their own routes:


   from azure.ai.agentserver.invocations import InvocationAgentServerHost

   app = InvocationAgentServerHost()

   @app.invoke_handler
   async def handle(request):
       return JSONResponse({"ok": True})

   app.run()

For multi-protocol agents, compose via cooperative inheritance:


   class MyHost(InvocationAgentServerHost, ResponsesAgentServerHost):
       pass

   app = MyHost()
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 None when the corresponding header was absent (e.g. local development, or call_id under protocol version 1.0.0).

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 BaseHTTPMiddleware, this passes the receive callable through to the inner application untouched, preserving request.is_disconnected() behaviour.

Wired automatically by AgentServerHost so that all protocol hosts (responses, invocations, etc.) get consistent inbound logging.

RequestIdMiddleware

Pure-ASGI middleware that sets x-request-id on every HTTP response.

The resolved request ID is stored in scope["state"] under <xref:REQUEST_ID_STATE_KEY> so that protocol-specific code (e.g. the Responses package) can read it for error body enrichment.

Unlike BaseHTTPMiddleware, this passes the receive callable through to the inner application untouched, preserving request.is_disconnected() behaviour.

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
str

The SDK identifier (e.g., "azure-ai-agentserver-responses").

version
Required
str

The package version string (e.g., "1.0.0b1").

Returns

Type Description
str

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
str or None

Application Insights connection string.

Default value: None
log_level
str or None

Log level name (e.g. "INFO", "DEBUG").

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
dict[str, dict[str, Any]] or None

Per-library OpenTelemetry instrumentation options. Azure SDK, HTTPX, Requests, urllib, and urllib3 instrumentation are disabled by default; set a library's enabled option to True to enable it.

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
str

Machine-readable error code (e.g. "internal_error").

message
Required
str

Human-readable error message.

Keyword-Only Parameters

Name Description
status_code
int

HTTP status code for the response.

error_type

Optional error type classification string. When provided, included as "type" in the error body.

Default value: None
details

Child error objects, each with at least code and message keys.

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
Any

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
any

The OTel span to end, or None.

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
type[<xref:T>] | Callable[<xref:P>, <xref:T>]

Class or callable to mark as experimental.

Returns

Type Description
type[<xref:T>] | Callable[<xref:P>, <xref:T>]

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
int

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
int

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 state dict).

Returns

Type Description
str | None

The resolved x-request-id value, or None.

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
any

The OTel span, or None.

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
str

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
int

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
Any

The OTel span to make current, or None.

Returns

Type Description
Any

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
any

The OTel span to end on completion, or None.

Returns

Type Description
AsyncIterator[<xref:azure.ai.agentserver.core.StreamContent>]

An async iterator yielding chunks unchanged.