Skip to content

With FastMCP.from_fastapi, how to pass lifespan to FastAPI app since it is already created? #559

Closed Answered by asaintsever
asaintsever asked this question in Q&A
Discussion options

You must be logged in to vote

Yes I managed to have something working properly:

@asynccontextmanager
async def lifespan(app: FastAPI):
    async with create_mcp_server(app):
       # ...
       yield
      # ...

With create_mcp_server defined as:

def create_mcp_server(app: FastAPI):
    # Create an MCP server from the FastAPI app
    mcp = FastMCP.from_fastapi(app=app)

    # For Streamable HTTP transport, on "/mcp" path (default)
    mcp_app = mcp.http_app()

    # The MCP endpoint will be available at /mcp-server/mcp of the resulting FastAPI app.
    app.mount("/mcp-server", mcp_app)
    return mcp_app.lifespan(mcp_app)

By doing so my app is both a regular FastAPI app exposing REST endpoints and a FastMCP app expo…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@asaintsever
Comment options

Answer selected by asaintsever
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants