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.
1. Request & Transport Dispatch Pipeline¶
MCPController mounts at MCPConfig.base_path (default /mcp) and delegates JSON-RPC framing and version negotiation to MCPHandlerService. Both 2026-07-28 stateless discovery (server/discover + SEP-2575 headers) and 2025-06-18 initialization (initialize, ping, notifications/initialized, DELETE /mcp) share the same registry and internal ASGI execution path.
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.
- Deep-Dive Guides: Core Architectural Concepts · Streamable HTTP & Discovery · Stdio & HTTP Bridge
- API Reference:
LitestarMCP&MCPConfig
2. 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:
- Tools: Compiles route signatures,
msgspec.Struct/ Pydantic /@dataclassmodels, andProvidedependencies into JSON Schema while stripping internal DI parameters (Request,State,ToolContext, and Dishka-resolved types). InfersToolAnnotations(readOnlyHint,destructiveHint,idempotentHint) from the HTTP verb unless overridden. - Resources & Templates: Separates static URIs (
resources/list) from parameterized RFC 6570 Level 1 templates (resources/templates/list) and managesresources/subscribechange notifications. - Prompts: Extracts
PromptArgumentmetadata from route handlers orPromptControllermethods and normalizes return values into MCP message sequences. - Agent Skills (
SEP-2640): Combines staticSKILL.mddirectories (FilesystemSkillSource), dynamic request-awareSkillSourceproviders, andSkillControllerendpoints underio.modelcontextprotocol/skills(skills/list,skills/load,skills/read_file) andskills://fallback resources.
- Deep-Dive Guides: Marking Routes & Decorators · Tools & Annotations · Resources & Templates · Prompts & PromptController · Agent Skills (SEP-2640)
- API Reference: Primitives & Skills API
3. 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 metadata in the litestar_mcp_tasks store namespace and delegates execution to a pluggable MCPTaskExecutor:
QueueTaskExecutor(litestar-mcp[queues]): Auto-attaches whenQueuePluginfromlitestar-queuesis present on the Litestar app (or when passed explicitly toMCPTaskConfig(executor=...)). Captures aPrincipalSnapshot(request.user,request.auth,litestar-securitySecurityContextscopes/roles, and DishkaScope.REQUESTcontext) so background worker replicas rehydrate the exact caller identity. Supports cooperativetasks/cancelpolling and multi-roundMCPInputRequiredResult/tasks/updatehuman-in-the-loop resume across distinct replicas.InProcessTaskExecutor: Default zero-dependency executor using an in-process AnyIOTaskGroupfor local development, stdio servers, and single-worker deployments.
- Deep-Dive Guides: MCP Tasks & Human-in-the-Loop · Distributed Task Queues (
QueueTaskExecutor) · Multi-Replica Deployment - API Reference: Tasks, Queues & Workflows API
4. 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-onceNodeRecordper completed node ({prefix}:{run_id}:node:{node_name}) and a monotonicWorkflowRundocument inlitestar_mcp_workflows, preventing sibling fan-in write races. - Forever-Unique Node Scheduling: Schedules ready nodes with
unique_key="wf-node:{run_id}:{node}"andunique_until="forever". If a node fails transiently and retries vialitestar-queues,DurableWorkflowEnginereleases the reservation withservice.reset_task_identity()before re-raising. - Self-Rearming Per-Run Watchdog: Schedules
wf-watchdog:{run_id}:{tick}tasks that inspectready_nodes()and heal stalled runs if a worker process crashes mid-wave.
- Deep-Dive Guides: Durable DAG Workflows · Tasks, Queues & Workflows Overview
- API Reference:
DurableWorkflowEngine&WorkflowStore·DynamicWorkflow&WorkflowEngine
5. 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 drivingModelClientimplementations.GoogleGenAIClientdefaults togemini-3.8-flashand preserves Gemini 3/2.5thought_signaturebytes across multi-turn tool calls.AgentGroupHandoffs: Coordinates a primary agent and specialist sub-agents by injecting a syntheticLiteral-typedtransfer_to_agenttool without mutating the underlyingAgent.toolslists.- Owner-Scoped Sessions & SSE Streaming:
SessionStore(MemorySessionStoreorLitestarStoreSessionStore) isolates conversation history by authenticatedowner_id.AgentChatControllerandQueuedAgentChatControllerexpose ready-to-mount REST and Server-Sent Events (SSE) endpoints. - Bidirectional Protocol Bridges:
agent_to_mcp,mcp_to_tools,discover_mcp_tools, andagent_to_a2aconnect Litestar routes, remote MCP servers, local agents, and A2A 1.0 endpoints without duplicate glue code.
- Deep-Dive Guides: Agent Runtime & Turn Budgets · Agent Groups & Handoffs · Sessions & SSE Streaming · Queued Agent Turns · Protocol Bridges
- API Reference: Agents & In-Process Workflows API · A2A 1.0 & Protocol Bridges API
6. 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 /a2aand, whenenable_http_json=True, mounts native A2A 1.0HTTP+JSONREST 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_optto execution routes while keeping discovery public (or separately scoped) viaA2AConfig.agent_card_route_opt. - Multi-Tenant Context Resolution: Extracts tenant identity from
/{tenant:str}path parameters or theX-A2A-Tenantrequest header (with path parameters taking precedence) and populatesServerCallContext.tenantviaA2AConfig.context_builder.
- Deep-Dive Guides: A2A 1.0 Protocol & HTTP+JSON Binding · Multi-Tenant A2A Routing · First-Party
litestar-securityIntegration - API Reference:
LitestarA2A&A2AConfig
7. 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_alchemyandsqlspecNotes reference application families across 10 database/auth variants (no_auth,jwt_auth,cloud_run,google_iap). - Single-File
uvx& PEP 723 Guide: Zero-setup execution of standalonelitestar-mcpscripts using inline PEP 723 dependency metadata,uv run, andlitestar mcp bridge.