FastAPI Mounting Guide
You can mount anMCPServer (or FastMCP) instance within an existing FastAPI application. This allows you to serve your MCP tools alongside your existing API endpoints.
Basic Integration
When mountingMCPServer, we need to ensure its internal task group (used for managing SSE streams) is properly initialized. We do this using FastAPI’s lifespan events.
Important Considerations
- Lifespan Management: The critical part is wrapping the application lifespan with an
anyio.create_task_group()and assigning it tomcp.session_manager._task_group. This works aroundFastMCP’s assumption that it controls the main loop. - Transport: Mounting implies using the Streamable HTTP transport pattern.
- Paths: The
MCPServerhas internal routes like/mcp(for SSE/POST) and/docs. When mounted at/agent, these become/agent/mcpand/agent/docs.