Skip to content

System Architecture & Interactive Diagrams

litestar-mcp unifies Model Context Protocol (MCP) servers, durable background task and DAG workflow execution, multi-agent orchestration, and Agent-to-Agent (A2A 1.0) interoperability inside a single Litestar ASGI lifecycle.

This page collects all six interactive architectural diagrams and links each subsystem to its implementation guide and API reference.


Request & Transport Dispatch Pipeline

MCPController mounts POST /mcp, GET /mcp (with Accept: text/event-stream, gated by MCPConfig.enable_get_sse and MCPConfig.allowed_origins), and DELETE /mcp at MCPConfig.base_path (default /mcp), delegating JSON-RPC framing and negotiation across SUPPORTED_PROTOCOL_VERSIONS = ("2026-07-28", "2025-11-25", "2025-06-18", "2025-03-26") to MCPHandlerService. Stateless 2026-07-28 requests (server/discover, SEP-2575 routing headers, and POST subscriptions/listen) remain headerless with respect to session state, while session-aware 2025-11-25, 2025-06-18, and 2025-03-26 clients receive an owner-bound Mcp-Session-Id (MCPSessionStore) on initialize, listen on GET /mcp SSE streams, manage resources/subscribe and resources/unsubscribe (honoring MCPConfig.subscription_authorizer), adjust RFC 5424 server log verbosity via logging/setLevel (await MCPRequestContext.log(...) emitting notifications/message), call ping, and close sessions via DELETE /mcp. Terminal tools (litestar mcp stdio, bridge, export-tool-spec, list-tools, list-resources, list-skills, and run) reuse the same compiled registry and ASGI lifecycle.

When a client calls tools/call or prompts/get, MCPHandlerService dispatches an in-memory ASGI request through the host Litestar router rather than opening a loopback TCP socket or bypassing the framework. Your authentication middleware, route guards, Provide factories, Dishka FromDishka[T] providers, DTO validators, lifecycle hooks, and OpenTelemetry spans execute on every invocation.

Streamable HTTP Sessions, SSE, and Internal ASGI Dispatch Pipeline JSON-RPC requests and GET /mcp SSE streams (Accept: text/event-stream) arrive at MCPController (/mcp), negotiate stateless 2026-07-28 (server/discover, POST subscriptions/listen) or stateful 2025-11-25, 2025-06-18, and 2025-03-26 (initialize, Mcp-Session-Id via MCPSessionStore, resources/subscribe, RFC 5424 logging/setLevel, DELETE /mcp), and execute handlers through internal ASGI dispatch with MCPRequestContext.log() and SubscriptionManager. MCP Client POST • GET /mcp • DELETE /mcp 2026-07-28: server/discover POST subscriptions/listen SSE 2025-*: initialize + Mcp-Session-Id GET /mcp (Accept: text/event-stream) resources/subscribe • logging/setLevel logLevel _meta & SEP-2575 headers MCPController MCPHandlerService Router Guards, auth & Origin check MCPSessionStore (Mcp-Session-Id TTL) RFC 5424 logging/setLevel state GET /mcp SSE stream & 405 toggle 202 Accepted • 204 DELETE /mcp 2026-07-28 • 2025-11-25 • 2025-06-18 Internal ASGI Dispatch execute_tool / prompt / res Forwards Auth & Trace Headers Preserves request.user & auth Binds session_id & log_level threshold MCPRequestContext.log() & progress subscription_authorizer enforcement Zero TCP Loopback Hop Litestar Handler @get / @post / @mcp_tool Middleware & Route Guards Provide & FromDishka[T] msgspec DTOs & outputSchema SEP-1865 ui:// HTML resources ctx.log() -> notifications/message before/after_request hooks Session State, Subscription Fan-Out & Observability Layer MCPSessionStore (TTL) | SubscriptionManager (owner_id • session_id • subscription_authorizer) Registry (Tools • Resources • Prompts • Skills) | SpanManager OpenTelemetry (mcp.request • mcp.tool.call)
In-Process Stdio and Stateful/Stateless HTTP Bridge Pipeline Desktop MCP clients exchange newline-delimited JSON on stdin/stdout using in-process Litestar.lifespan() execution with MCPStdioContext or the remote HTTP bridge supporting both stateless 2026-07-28 and stateful 2025-11-25 Mcp-Session-Id sessions, GET /mcp SSE notification forwarding, and DELETE /mcp teardown. Desktop Host stdin / stdout NDJSON IDE & Desktop MCP Clients litestar mcp stdio (in-process) litestar mcp bridge (--endpoint) 2026-07-28 or 2025-11-25 frames Receives notifications/* on stdout mcp.run(transport="stdio") Stdio Lifecycle Adapter run_stdio_async() Enters Litestar.lifespan() Injects MCPStdioContext user • auth • session_id • state Streams progress & RFC 5424 logs Resource & skill list_changed push Bounded shutdown_timeout=5.0s ASGI Scope or HTTP Bridge stdio.py / bridge.py Stateless 2026-07-28 POST relay 2025-11-25 Mcp-Session-Id capture Background GET /mcp SSE listener Forwards SSE notifications to NDJSON Clean DELETE /mcp session teardown Owner ID: user:<subject> Application DI Full Litestar Pipeline DB Pools & Stores Active Dishka Scope.REQUEST Route Guards Enforced SkillCatalog & Registry live Identical Tool & UI Semantics MCPSessionStore + Tasks active Two CLI Modes: Local In-Process ASGI vs Stateful/Stateless Remote HTTP Bridge litestar --app app:app mcp stdio | litestar mcp bridge --endpoint https://api.example.com/mcp Bridge 2025-11-25 lifecycle: initialize -> Mcp-Session-Id -> GET /mcp SSE forwarder -> DELETE /mcp on EOF

Primitives & Discovery Compilation

At application startup (on_app_init), LitestarMCP inspects every registered Litestar route handler, PromptController, SkillController, and MCPSkillsConfig source to populate the central Registry and SkillCatalog:

  • Tools: Compiles route signatures, msgspec.Struct, Pydantic, @dataclass, and TypedDict models, and Provide dependencies into JSON Schema 2020-12 via generate_schema_for_handler while stripping internal DI parameters (Request, State, ToolContext, and Dishka-resolved types). Synthesizes opt-in outputSchema (MCPConfig.auto_output_schema, output_schema=, mcp_output_schema, hoisting root msgspec.Struct $ref schemas to "type": "object") with automatic structuredContent population, infers mcp_annotations (readOnlyHint, destructiveHint, idempotentHint) from HTTP verbs, and attaches SEP-1865 presentation and UI metadata (UI_EXTENSION = "io.modelcontextprotocol/ui", _meta.ui, title, icons).
  • Resources & Templates: Separates static custom-scheme URIs (uri="ui://...", docs://..., app://... in resources/list) from parameterized {var} RFC 6570 Level 1 templates (resources/templates/list), preserves raw non-charset MIME parameters such as UI_MIME_TYPE = "text/html;profile=mcp-app" along with contents[0]._meta, and manages owner-scoped resources/subscribe and POST subscriptions/listen notifications gated by MCPConfig.subscription_authorizer.
  • Prompts: Extracts PromptArgument and _meta (meta) descriptors from route handlers or PromptController methods, normalizes return values into MCP message sequences, and optionally projects visible skills into prompts/list and prompts/get when MCPSkillsConfig(expose_as_prompts=True) is set.
  • Agent Skills (SEP-2640): Exports SkillCatalog at litestar_mcp.SkillCatalog with request-optional DI (skill_catalog), composing static SKILL.md directories (FilesystemSkillSource), dynamic request-aware SkillSource providers, and SkillController endpoints under io.modelcontextprotocol/skills (skills/list with tag/query filtering, skills/get, notifications/skills/list_changed when list_changed=True), skill://<name>/... resources, and litestar mcp list-skills.
MCP Tools, Structured Output, and SEP-1865 UI Compilation Pipeline Litestar routes marked with mcp_tool or @mcp_tool compile signature types, outputSchema (output_schema=True and auto_output_schema), title, icons, and SEP-1865 _meta.ui links into tools/list and execute via tools/call with automatic structuredContent, MCPRequestContext.log(), and report_progress(). Route Declaration @mcp_tool(...) / mcp_tool=True output_schema=True | {...} title, icons & meta={"ui": ...} SEP-1865 _meta.ui.resourceUri annotations={...} & HTTP verb hints task=True | "required" | "optional" MCPConfig(auto_output_schema=True) Registry Schema Builder Registry.register_tool() Compiles inputSchema & outputSchema msgspec / Pydantic / dataclass / TypedDict Strips Dishka & internal DI params Emits title, icons & _meta.ui fields Precedence: description > summary > doc litestar mcp export-tool-spec JSON-RPC Execution tools/list & tools/call Dispatches via internal ASGI scope Automatic structuredContent payloads MCPRequestContext.log() (RFC 5424) MCPRequestContext.report_progress() Promotes params.task background runs isError: true on 4xx/5xx tool errors
MCP Resources, RFC 6570 URI Templates, and SEP-1865 UI Pipeline Static resources (uri=) and RFC 6570 {var} templates separate cleanly via classify_resource_uri, advertise SEP-1865 io.modelcontextprotocol/ui and text/html;profile=mcp-app with contents[0]._meta, and deliver live updates via resources/subscribe, unsubscribe, notify_resources_list_changed(), and GET /mcp SSE. Resource & UI Opts @mcp_resource(uri="ui://...") mcp_resource_uri="ui://reports/view" mcp_resource_template="notes://{id}" classify_resource_uri (uri= vs {var}) text/html;profile=mcp-app raw HTML title, icons & contents[0]._meta io.modelcontextprotocol/ui URI Matcher & Subscriptions Registry & SubscriptionManager Static resources vs RFC 6570 templates Preserves non-charset MIME profiles resources/subscribe & unsubscribe notify_resource_updated(uri) + Channels notify_resources_list_changed() GET /mcp SSE & subscriptions/listen Resource JSON-RPC Surface resources/read & list resources/list (static URIs + _meta) resources/templates/list (RFC 6570) Returns unquoted HTML, text, or blob Injects contents[0]._meta on read notifications/resources/list_changed notifications/resources/updated
MCP Prompts, Metadata, and Skill Prompt Projection Pipeline Prompts declared via @mcp_prompt(meta=...), @prompt(meta=...), PromptController, route markers, or MCPSkillsConfig(expose_as_prompts=True) emit _meta on prompts/list and resolve Litestar and Dishka DI during prompts/get. Prompt Authoring PromptController / @mcp_prompt @mcp_prompt(meta=...) / @prompt(meta=...) Route opt: mcp_prompt & mcp_prompt_meta expose_as_prompts=True projection Universal DI: Provide / FromDishka[T] Dependency() & Parameter() markers Controller-level guards & _meta Argument Schema & Metadata PromptArgument & _meta Excludes DI & Request parameters Derives required/optional arguments Parses Google docstring Args table Advertises title, icons & _meta Projects visible SkillCatalog entries completion/complete handler Prompt Message Normalization prompts/list & prompts/get Executes within ASGI request scope Normalizes str, dict, or list[dict] Renders SKILL.md instructions on get Produces role + TextContent blocks Enforces controller & route guards messages: [{role, content}]
Agent Skills SEP-2640 and SkillCatalog Pipeline MCPSkillsConfig combines paths, SkillSource plugins, SkillController, expose_as_prompts=True, and list_changed=True into request-optional SkillCatalog (app_config.dependencies["skill_catalog"] with internal blank Request fallback), tags and query filtering, skillsListChanged notifications, and litestar mcp list-skills. Skill Sources (SEP-2640) MCPSkillsConfig paths=[Path("skills")] & sources=[...] expose_as_prompts=True & list_changed=True SkillController class discovery Skill.from_content() + title/icons/tags/_meta SkillFile.from_content() + SHA-256 litestar mcp list-skills Request-Optional Catalog SkillCatalog app_config.dependencies["skill_catalog"] Request + DI or internal blank Request filter_skills() tags & query matching Path traversal & symlink containment notify_list_changed() event fan-out io.modelcontextprotocol/skills Discovery & Change Events skills/* • prompts/* • skill://* skills/list (cursor, tags, query) skills/get (SKILL.md + file manifest) resources/read skill://{name}/{path} prompts/list & get (expose_as_prompts) skillsListChanged capability enabled notifications/skills/list_changed

MCP Tasks & Distributed Queue Execution

The io.modelcontextprotocol/tasks capability lets clients request asynchronous execution on any tool by supplying params.task. MCPTaskStore persists TaskRecord state (status, status_message) alongside private ToolTaskCall dispatch metadata (progress_token, bound session_id, and RFC 5424 log_level) in the litestar_mcp_tasks store namespace so promoted tasks forward notifications/progress and MCPRequestContext.log() (notifications/message) events across in-process and distributed executors:

  • QueueTaskExecutor (litestar-mcp[queues]): Auto-attaches when QueuePlugin from litestar-queues is present on the Litestar app (or when passed explicitly to MCPTaskConfig(executor=...)). Captures a PrincipalSnapshot (request.user, request.auth, litestar-security SecurityContext scopes/roles, and Dishka Scope.REQUEST context) alongside task progress and logging metadata so background worker replicas rehydrate the exact caller identity, stream progress updates, and honor cooperative tasks/cancel polling plus multi-round MCPInputRequiredResult / tasks/update human-in-the-loop resume across distinct replicas.
  • Built-in In-Process Task Execution (executor="in_process"): Default zero-dependency task runner in MCPTaskStore / MCPHandlerService using an in-process AnyIO task group for local development, stdio servers, and single-worker deployments while forwarding progress_token and session log streams identically.
Distributed QueueTaskExecutor and Task Progress/Log Forwarding on litestar-queues tools/call with params.task persists TaskRecord and ToolTaskCall (progress_token, session_id, log_level, PrincipalSnapshot) in MCPTaskStore, runs on litestar-queues workers calling ctx.report_progress() and ctx.log() to update MCPTaskStore.update_status_message() and fan out notifications/progress onto strictly matched 2025-* GET /mcp session SSE streams (while 2026-07-28 POST subscriptions/listen carries notifications/tasks and opted-in logLevel notifications/message while excluding notifications/progress), and refreshes log_level from MCPSessionStore on tasks/update. Task Promotion tools/call (params.task) Captures PrincipalSnapshot & owner_id ToolTaskCall.progress_token Persists session_id & log_level request.user & SecurityContext Persists TaskRecord before return Returns CreateTaskResult Durable Store & Broker MCPTaskStore + QueuePlugin Store: litestar_mcp_tasks (TTL) MCPTaskStore.update_status_message() QueueTaskExecutor.submit() / resume() MCPSessionStore log_level refresh on tasks/update • queue="..." Postgres / Redis / SQLSpec Worker Rehydration Replica Worker Execution Rehydrates user, auth & Dishka Restores progress_token & log_level ctx.report_progress() -> statusMessage ctx.log() RFC 5424 severity filter ChannelsPlugin cross-replica fan-out Cooperative CancelScope SSE & Task Control tasks/get • update • cancel 2025-11-25 GET /mcp SSE push: notifications/progress notifications/message MCPInputRequiredResult pause tasks/update refreshes log_level Cross-Replica Safe Cross-Replica Progress, Logging & Transport Isolation Worker ctx.report_progress() & ctx.log() -> update_status_message() + ChannelsPlugin -> 2025-11-25 GET /mcp SSE 2026-07-28 subscriptions/listen: notifications/tasks + opted-in logLevel (excludes progress) | tasks/get statusMessage
Built-In MCPTaskStore, Promoted Progress/Logging, and Elicitation Lifecycle Built-in MCPTaskStore persists strictly owner-scoped TaskRecord and ToolTaskCall metadata (progress_token, session_id, log_level), updates TaskRecord.statusMessage via MCPTaskStore.update_status_message(), and forwards notifications/progress and notifications/message onto 2025-* GET /mcp session SSE streams while 2026-07-28 subscriptions/listen carries taskIds and opted-in logLevel events (excluding progress). Promoted Context tools/call (params.task) Validates task="optional" | "required" Captures ToolTaskCall(progress_token, session_id, log_level, owner_id) Single-writer Store keys with TTL Detaches runner after HTTP return Immediate taskId handle MCPTaskStore State Machine litestar_mcp_tasks Store working -> input_required -> completed Executes tool via internal ASGI dispatch MCPTaskStore.update_status_message() Updates TaskRecord.statusMessage live Filters ctx.log() by session log_level Zero external broker required Session SSE, Poll & Resume GET /mcp SSE • tasks/get • update Forwards notifications/progress & message onto 2025-11-25 GET /mcp session SSE subscriptions/listen: tasks + logLevel only tasks/get returns statusMessage & result tasks/update resumes & refreshes log_level Owner-isolated lookup & tasks/cancel Post-Promotion Progress, RFC 5424 Logging & Transport Rules ToolTaskCall(progress_token, session_id, log_level) -> MCPTaskStore.update_status_message() -> TaskRecord.statusMessage 2025-* GET /mcp: notifications/progress + notifications/message | 2026-07-28 subscriptions/listen: excludes progress

Durable DAG Workflows (DurableWorkflowEngine)

DynamicWorkflow defines a Directed Acyclic Graph (DAG) of WorkflowNode steps (wrapping either an Agent or an async Python callable) with topological wave dependencies and conditional WorkflowNode(condition=...) branching.

The same DynamicWorkflow definition runs in-process via WorkflowEngine or across distributed worker replicas via DurableWorkflowEngine on litestar-queues:

  • Conflict-Free Persistence (WorkflowStore): Persists a write-once NodeRecord per completed node ({prefix}:{run_id}:node:{node_name}) and a monotonic WorkflowRun document in litestar_mcp_workflows, preventing sibling fan-in write races.
  • Forever-Unique Node Scheduling: Schedules ready nodes with unique_key="wf-node:{run_id}:{node}" and unique_until="forever". If a node fails transiently and retries via litestar-queues, DurableWorkflowEngine releases the reservation with service.reset_task_identity() before re-raising.
  • Self-Rearming Per-Run Watchdog: Schedules wf-watchdog:{run_id}:{tick} tasks that inspect ready_nodes() and heal stalled runs if a worker process crashes mid-wave.
Distributed DurableWorkflowEngine on litestar-queues DynamicWorkflow DAG waves execute across worker replicas via DurableWorkflowEngine, persisting write-once NodeRecord and monotonic WorkflowRun documents in WorkflowStore (litestar_mcp_workflows), using forever-unique wf-node:{run_id}:{node} reservations (Calls reset_task_identity() before each wave enqueue) and per-run wf-watchdog:{run_id}:{tick} recovery. DynamicWorkflow DAG engine.start(name, ...) Topological wave validation Agent nodes & Python step nodes Conditional & dynamic DAG edges Persists initial_state in WorkflowStore Returns run_id immediately WorkflowStore litestar_mcp_workflows Write-once NodeRecord per node Eliminates sibling fan-in races Monotonic WorkflowRun status Completed outputs never lost engine.snapshot(run_id) Forever-Unique Queue wf-node:{run_id}:{node} Deduplicates concurrent fan-in Rehydrates Dishka Scope.REQUEST Calls reset_task_identity() before each wave enqueue Enqueues ready downstream wave Watchdog wf-watchdog:{id}:{t} Per-run self-rearming Checks get_ready_nodes() Heals crashed workers Stops on terminal state Zero orphan DAG runs Parallel Wave Fan-Out & Conflict-Free Fan-In Wave 0: [extract] -> Wave 1: [enrich_a, enrich_b] (parallel workers) -> Wave 2: [aggregate] (forever-unique gate)
In-Process WorkflowEngine Execution In-process WorkflowEngine executes DynamicWorkflow topological waves concurrently using AnyIO task groups within a single request or background coroutine. Workflow Definition DynamicWorkflow(name="...") WorkflowNode(name, handler=... | agent=...) depends_on=["upstream_a", ...] Validates acyclic dependency graph Conditional edge predicates workflow.add_node(...) & add_edge(...) AnyIO Wave Scheduler WorkflowEngine.run(workflow, initial_state) Computes ready nodes per wave Runs sibling wave nodes in TaskGroup Passes WorkflowContext(run_id, state) Records ctx.node_outputs[node] Propagates failed StepResult.error Dynamic Branching & Output StepResult & WorkflowContext StepResult(node_name, output, status, error) Prunes unselected conditional branches Returns completed WorkflowContext Same DynamicWorkflow runs on both WorkflowEngine & DurableWorkflowEngine Portable DAG Definition Across In-Process and Distributed Engines Author DynamicWorkflow once -> test with WorkflowEngine in unit tests -> deploy on DurableWorkflowEngine

Multi-Agent Runtime, Handoffs & Protocol Bridges

AgentRuntime manages Agent and AgentGroup execution inside your Litestar application:

  • TurnBudget & GoogleGenAIClient: Enforces per-turn ceilings (max_turns, max_tool_calls, timeout_seconds) while driving ModelClient implementations. GoogleGenAIClient defaults to gemini-3.8-flash and preserves Gemini 3/2.5 thought_signature bytes across multi-turn tool calls.
  • AgentGroup Handoffs: Coordinates a primary agent and specialist sub-agents by injecting a synthetic Literal-typed transfer_to_agent tool without mutating the underlying Agent.tools lists.
  • Owner-Scoped Sessions & SSE Streaming: SessionStore (MemorySessionStore or LitestarStoreSessionStore) isolates conversation history by authenticated owner_id. AgentChatController and QueuedAgentChatController expose ready-to-mount REST and Server-Sent Events (SSE) endpoints.
  • Bidirectional Protocol Bridges: agent_to_mcp, mcp_to_tools(..., include_app_only=False), discover_mcp_tools(..., include_app_only=False), and agent_to_a2a connect Litestar routes, remote MCP servers, local agents, and A2A 1.0 endpoints via in-process execute_tool ASGI DI dispatch while honoring MCPConfig operation/tag filters and SEP-1865 _meta.ui.visibility rules.
AgentGroup, AgentRuntime, TurnBudget, and Owner-Scoped Sessions AgentChatController and QueuedAgentChatController stream SSE turns through AgentRuntime, enforcing TurnBudget limits, calling GoogleGenAIClient (gemini-3.8-flash), executing non-mutating AgentGroup handoffs via transfer_to_agent, and persisting history in owner-scoped SessionStore. Chat & Queue Controllers AgentChatController QueuedAgentChatController POST /agent/chat (stream=True) Owner-Scoped SessionStore Memory / LitestarStore Streams AgentStreamFrame SSE AgentRuntime Plugin TurnBudget Enforcement max_turns • max_tool_calls max_input/output_tokens • wall_time Parallel tool call fan-out Dishka & Litestar DI resolution SpanManager (TelemetryConfig) Spans AgentGroup Handoffs Coordinator & Specialists Synthetic transfer_to_agent tool Non-mutating member toolsets TurnBudget handoff cycle guard Preserves conversation history Tracks active_agent in session ModelClient GoogleGenAIClient Default: gemini-3.8-flash Preserves thought_signature stream_turn(messages, tools, ...) Structured response_schema Custom ModelClient protocol Bidirectional Protocol Bridges agent_to_mcp(agent) • mcp_to_tools(mcp_plugin, app) • discover_mcp_tools(client) • agent_to_a2a(agent_or_group)
Bidirectional Protocol Bridges Between Agent, MCP, and A2A 1.0 Four zero-boilerplate bridges connect Agent and AgentGroup instances to MCP tools/call, remote MCP Client discovery, and A2A 1.0 LitestarA2A executors. MCP Primitives & Clients LitestarMCP / MCPStreamableHTTPClient Local marked routes (@get/@post) Remote Streamable HTTP servers Exposed as callable MCP tools tools/list & tools/call mcp_to_tools agent_to_mcp Agent / AgentGroup litestar_mcp.agent Unified Tool(name, schema, fn) discover_mcp_tools(mcp_client) Forward headers & ToolContext AgentRuntime.run_turn() & stream() agent_to_a2a A2A 1.0 Interoperability LitestarA2A(A2AConfig) Auto-generates AgentCard & Skills Wraps Agent in AgentExecutor Bridges SessionStore by context_id JSON-RPC 2.0 + HTTP+JSON REST Compose Any Direction Without Duplicate Tool Definitions Litestar Routes -> mcp_to_tools(mcp_plugin, app) -> AgentRuntime -> agent_to_a2a(agent) & agent_to_mcp(agent)

A2A 1.0 Interoperability & Multi-Tenancy (LitestarA2A)

LitestarA2A (litestar-mcp[a2a]) integrates the official a2a-sdk 1.0 runtime (AgentCard, AgentSkill, AgentExecutor, DefaultRequestHandler, TaskStore, ServerCallContext) directly into Litestar:

  • Dual Transport Bindings: Serves JSON-RPC 2.0 at POST /a2a and, when enable_http_json=True, mounts native A2A 1.0 HTTP+JSON REST routes (POST /a2a/message:send, POST /a2a/message:stream, GET /a2a/tasks, GET /a2a/tasks/{id}, POST /a2a/tasks/{id}:cancel, POST /a2a/tasks/{id}:subscribe, and push notification config endpoints) while advertising both interfaces in /.well-known/agent-card.json.
  • Split Route Security: Applies A2AConfig.route_opt to execution routes while keeping discovery public (or separately scoped) via A2AConfig.agent_card_route_opt.
  • Multi-Tenant Context Resolution: Extracts tenant identity with precedence request payload > /{tenant:str} URL path > X-A2A-Tenant header and populates ServerCallContext.tenant via A2AConfig.context_builder.
LitestarA2A Dual Transport Bindings and AgentExecutor Pipeline LitestarA2A serves /.well-known/agent-card.json, JSON-RPC 2.0 at /a2a, and A2A 1.0 HTTP+JSON REST routes (:cancel, :subscribe, /message:send, /message:stream) backed by DefaultRequestHandler and AgentExecutor. Discovery & Clients /.well-known/agent-card.json agent_card_route_opt (public) Advertises JSONRPC & HTTP+JSON Lists AgentSkill capabilities A2A-Version: 1.0 header enable_http_json=True Dual Transport Routes POST /a2a (JSON-RPC 2.0) POST /a2a/message:send POST /a2a/message:stream (SSE) GET /a2a/tasks & /tasks/{id} POST /a2a/tasks/{id}:cancel POST /a2a/tasks/{id}:subscribe Request Handler DefaultRequestHandler Builds ServerCallContext context_builder hook InMemoryTaskStore / custom PushNotificationConfigStore ProtoJSON Event Serializer Executor AgentExecutor execute(ctx, queue) cancel(ctx, queue) Or agent_to_a2a() Emits TaskStatus & ArtifactUpdate Official a2a-sdk 1.0 Wire Compliance Single A2AConfig mounts JSON-RPC 2.0, HTTP+JSON REST (:send, :stream, :cancel, :subscribe), and Push Notifications
Multi-Tenant Resolution and Split Route Security Multi-tenant resolution extracts tenant identity from JSON-RPC/HTTP payloads, /{tenant:str}/a2a path parameters, or X-Tenant-ID / X-A2A-Tenant headers, passes it through context_builder into ServerCallContext.tenant, and separates public agent_card_route_opt from protected route_opt. Tenant Extraction Sources Payload + Path + Header path="/a2a" or "/{tenant:str}/a2a" Header: X-Tenant-ID / X-A2A-Tenant Precedence: payload > path > header Applies to JSON-RPC & HTTP+JSON Tenant-scoped URLs in AgentCard Context Builder & Auth ServerCallContext.tenant Default builder populates .tenant Custom A2AConfig.context_builder Forwards request.user & request.auth Enforces Litestar router guards context.state["litestar_state"] Split Route Opt Security route_opt vs agent_card_route_opt route_opt={"auth": required(...)} Protects RPC & REST execution routes agent_card_route_opt={"auth": public()} Keeps /.well-known/agent-card.json open First-party litestar-security ready Zero-Leakage Tenant Isolation Payload tenant | /{tenant}/a2a | X-Tenant-ID: acme -> ServerCallContext(tenant="acme")

Runnable Reference Examples & PEP 723 Single-File Apps

Every subsystem above is accompanied by runnable, pytest-verified reference applications and single-file PEP 723 scripts:

  • Reference Examples & Notes Matrix: Full comparison of the advanced_alchemy and sqlspec Notes reference application families across 10 database/auth variants (no_auth, jwt_auth, cloud_run_jwt, google_iap).
  • Single-File uvx & PEP 723 Guide: Zero-setup execution of standalone litestar-mcp scripts using inline PEP 723 dependency metadata, uv run, and litestar mcp bridge.