AgentServerHost Class

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()

Constructor

AgentServerHost(*, applicationinsights_connection_string: str | None = None, graceful_shutdown_timeout: int | None = None, log_level: str | None = None, access_log: ~logging.Logger | None = <object object>, access_log_format: str | None = None, configure_observability: ~collections.abc.Callable[[...], None] | None = <function configure_observability>, routes: list[starlette.routing.Route] | None = None, **kwargs: ~typing.Any)

Parameters

Name Description
applicationinsights_connection_string
Required

Application Insights connection string for exporting traces and logs to Azure Monitor. When None (default) the APPLICATIONINSIGHTS_CONNECTION_STRING env var is consulted. Tracing is automatically enabled when a connection string is available.

graceful_shutdown_timeout
Required

Seconds to wait for in-flight requests to complete after receiving SIGTERM / shutdown signal. When None (default) the default is 30 seconds. Set to 0 to disable the drain period.

log_level
Required

Library log level (e.g. "DEBUG", "INFO"). When None (default) the default is "INFO".

access_log
Required

Logger for HTTP access logs, or None to disable. Defaults to the library logger (azure.ai.agentserver).

access_log_format
Required

Hypercorn access-log format string. Supports %(h)s (remote addr), %(r)s (request line), %(s)s (status), %(b)s (body size), %(D)s (duration μs), %({header}i)s (request header), %({header}o)s (response header). Defaults to %(h)s "%(r)s" %(s)s %(b)s %(D)sμs.

configure_observability
Required

Callable that sets up console logging, tracing, and OTel export. Defaults to <xref:_tracing.configure_observability> which attaches a console handler to the root logger and configures Azure Monitor / OTLP export. Pass a custom callable to override the setup, or None to skip all SDK-managed observability configuration.

Keyword-Only Parameters

Name Description
applicationinsights_connection_string
Default value: None
graceful_shutdown_timeout
Default value: None
log_level
Default value: None
access_log
Default value: <object object at 0x0000029848A22280>
access_log_format
Default value: None
configure_observability
Default value: <function configure_observability at 0x000002984AD3FCE0>
routes
Default value: None

Methods

add_exception_handler
add_middleware

Add middleware to the host.

This exposes Starlette's middleware extension point without leaking Starlette's private type aliases in this package's public API.

add_route
after_restore_handler

Register a function to rebuild process state after snapshot restore.

Environment overrides are applied before the function is called.

before_snapshot_handler

Register a function to release process state before a memory snapshot.

The hook is serialized and runs at most once for each snapshot cycle.

build_middleware_stack
host
mount
readiness_handler

Register a function to handle readiness probe requests.

The registered function replaces the default healthy response for GET /readiness.

register_pre_shutdown_callback

Register a synchronous callback to run on SIGTERM signal receipt.

Callbacks run from inside the SIGTERM signal handler, BEFORE Hypercorn begins its graceful drain. Use this to set asyncio events that long-running request handlers observe via their cancellation-polling loops, so they can return before Hypercorn waits the full graceful_shutdown_timeout for the request to complete.

Callbacks MUST be non-blocking and signal-safe — they execute synchronously on the main thread inside the signal handler. The typical pattern is:


   shutdown_event = asyncio.Event()
   app.register_pre_shutdown_callback(shutdown_event.set)

Note: asyncio.Event.set() is safe to call from a signal handler when the event loop is running on the same thread.

register_server_version

Register a version segment for the x-platform-server header.

Protocol packages (e.g. responses, invocations) call this in their __init__ to add their own portion. Handler developers can also call it to append a custom version string. Duplicates are ignored.

Use build_server_version to build a standard segment:


   from azure.ai.agentserver.core import build_server_version

   app.register_server_version(
       build_server_version("my-library", "2.0.0")
   )
run

Start the server synchronously.

run_async

Start the server asynchronously (awaitable).

shutdown_handler

Register a function as the shutdown handler.

url_path_for

add_exception_handler

add_exception_handler(exc_class_or_status_code: int | type[Exception], handler: ExceptionHandler) -> None

Parameters

Name Description
exc_class_or_status_code
Required
handler
Required

add_middleware

Add middleware to the host.

This exposes Starlette's middleware extension point without leaking Starlette's private type aliases in this package's public API.

add_middleware(middleware_class: ~collections.abc.Callable[[~typing.Concatenate[~collections.abc.Callable[[~collections.abc.MutableMapping[str, ~typing.Any], ~collections.abc.Callable[[], ~collections.abc.Awaitable[~collections.abc.MutableMapping[str, ~typing.Any]]], ~collections.abc.Callable[[~collections.abc.MutableMapping[str, ~typing.Any]], ~collections.abc.Awaitable[None]]], ~collections.abc.Awaitable[None]], ~P]], ~collections.abc.Callable[[~collections.abc.MutableMapping[str, ~typing.Any], ~collections.abc.Callable[[], ~collections.abc.Awaitable[~collections.abc.MutableMapping[str, ~typing.Any]]], ~collections.abc.Callable[[~collections.abc.MutableMapping[str, ~typing.Any]], ~collections.abc.Awaitable[None]]], ~collections.abc.Awaitable[None]]], *args: ~typing.~P, **kwargs: ~typing.~P) -> None

Parameters

Name Description
middleware_class
Required
<xref:MiddlewareFactory>

Middleware class or factory to add.

args
Required
Any

Positional arguments forwarded to the middleware.

add_route

add_route(path: str, route: Callable[[Request], Awaitable[Response] | Response], methods: list[str] | None = None, name: str | None = None, include_in_schema: bool = True) -> None

Parameters

Name Description
path
Required
route
Required
methods
Default value: None
name
Default value: None
include_in_schema
Default value: True

after_restore_handler

Register a function to rebuild process state after snapshot restore.

Environment overrides are applied before the function is called.

after_restore_handler(fn: Callable[[AgentSessionContext], Awaitable[None]]) -> Callable[[AgentSessionContext], Awaitable[None]]

Parameters

Name Description
fn
Required

Async function called with the restored session context.

Returns

Type Description

The original function (unmodified).

before_snapshot_handler

Register a function to release process state before a memory snapshot.

The hook is serialized and runs at most once for each snapshot cycle.

before_snapshot_handler(fn: Callable[[], Awaitable[None]]) -> Callable[[], Awaitable[None]]

Parameters

Name Description
fn
Required

Async function called before the platform captures the process.

Returns

Type Description

The original function (unmodified).

build_middleware_stack

build_middleware_stack() -> Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]]

host

host(host: str, app: Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]], name: str | None = None) -> None

Parameters

Name Description
host
Required
app
Required
name
Default value: None

mount

mount(path: str, app: Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]], name: str | None = None) -> None

Parameters

Name Description
path
Required
app
Required
name
Default value: None

readiness_handler

Register a function to handle readiness probe requests.

The registered function replaces the default healthy response for GET /readiness.

readiness_handler(fn: Callable[[Request], Awaitable[Response]]) -> Callable[[Request], Awaitable[Response]]

Parameters

Name Description
fn
Required
Callable[[<xref:Request>], Awaitable[<xref:Response>]]

Async function accepting the incoming request and returning the readiness response.

Returns

Type Description
Callable[[<xref:Request>], Awaitable[<xref:Response>]]

The original function (unmodified).

register_pre_shutdown_callback

Register a synchronous callback to run on SIGTERM signal receipt.

Callbacks run from inside the SIGTERM signal handler, BEFORE Hypercorn begins its graceful drain. Use this to set asyncio events that long-running request handlers observe via their cancellation-polling loops, so they can return before Hypercorn waits the full graceful_shutdown_timeout for the request to complete.

Callbacks MUST be non-blocking and signal-safe — they execute synchronously on the main thread inside the signal handler. The typical pattern is:


   shutdown_event = asyncio.Event()
   app.register_pre_shutdown_callback(shutdown_event.set)

Note: asyncio.Event.set() is safe to call from a signal handler when the event loop is running on the same thread.

register_pre_shutdown_callback(fn: Callable[[], None]) -> None

Parameters

Name Description
fn
Required
Callable[[], None]

A synchronous, non-blocking callable.

register_server_version

Register a version segment for the x-platform-server header.

Protocol packages (e.g. responses, invocations) call this in their __init__ to add their own portion. Handler developers can also call it to append a custom version string. Duplicates are ignored.

Use build_server_version to build a standard segment:


   from azure.ai.agentserver.core import build_server_version

   app.register_server_version(
       build_server_version("my-library", "2.0.0")
   )
register_server_version(version_segment: str) -> None

Parameters

Name Description
version_segment
Required
str

The version string to register.

Exceptions

Type Description

If version_segment is empty or whitespace-only.

run

Start the server synchronously.

run(host: str = '0.0.0.0', port: int | None = None) -> None

Parameters

Name Description
host
str

Network interface to bind. Defaults to "0.0.0.0".

Default value: 0.0.0.0
port

Port to bind. Defaults to PORT env var or 8088.

Default value: None

run_async

Start the server asynchronously (awaitable).

async run_async(host: str = '0.0.0.0', port: int | None = None) -> None

Parameters

Name Description
host
str

Network interface to bind. Defaults to "0.0.0.0".

Default value: 0.0.0.0
port

Port to bind. Defaults to PORT env var or 8088.

Default value: None

shutdown_handler

Register a function as the shutdown handler.

shutdown_handler(fn: Callable[[], Awaitable[None]]) -> Callable[[], Awaitable[None]]

Parameters

Name Description
fn
Required

Async function called during graceful shutdown.

Returns

Type Description

The original function (unmodified).

url_path_for

url_path_for(name: str, /, **path_params: Any) -> URLPath

Positional-Only Parameters

Name Description
name
Required

Attributes

routes