Skip to main content

FastAPI Mounting Guide

You can mount an MCPServer (or FastMCP) instance within an existing FastAPI application. This allows you to serve your MCP tools alongside your existing API endpoints.

Basic Integration

When mounting MCPServer, 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

  1. Lifespan Management: The critical part is wrapping the application lifespan with an anyio.create_task_group() and assigning it to mcp.session_manager._task_group. This works around FastMCP’s assumption that it controls the main loop.
  2. Transport: Mounting implies using the Streamable HTTP transport pattern.
  3. Paths: The MCPServer has internal routes like /mcp (for SSE/POST) and /docs. When mounted at /agent, these become /agent/mcp and /agent/docs.

Example with Shared State

If you want your MCP tools to access the main application’s state (like a database connection), you can pass that context into the tool or use a closure.