diff --git a/docs/deployment/asgi.mdx b/docs/deployment/asgi.mdx index 6fc5624fb..ace7ee136 100644 --- a/docs/deployment/asgi.mdx +++ b/docs/deployment/asgi.mdx @@ -45,6 +45,9 @@ sse_app = mcp.http_app(transport="sse") Both approaches return a Starlette application that can be integrated with other ASGI-compatible web frameworks. +The returned app stores the `FastMCP` instance on `app.state.fastmcp_server`, so you +can access it from custom middleware or routes via `request.app.state.fastmcp_server`. + The MCP server's endpoint is mounted at the root path `/mcp` for Streamable HTTP transport, and `/sse` for SSE transport, though you can change these paths by passing a `path` argument to the `http_app()` method: ```python diff --git a/src/fastmcp/server/http.py b/src/fastmcp/server/http.py index 2437e85f8..d718d610a 100644 --- a/src/fastmcp/server/http.py +++ b/src/fastmcp/server/http.py @@ -247,11 +247,15 @@ def create_sse_app( server_middleware.extend(middleware) # Create and return the app - return create_base_app( + app = create_base_app( routes=server_routes, middleware=server_middleware, debug=debug, ) + # Store the FastMCP server instance on the Starlette app state + app.state.fastmcp_server = server + + return app def create_streamable_http_app( @@ -344,9 +348,13 @@ def create_streamable_http_app( yield # Create and return the app with lifespan - return create_base_app( + app = create_base_app( routes=server_routes, middleware=server_middleware, debug=debug, lifespan=lifespan, ) + # Store the FastMCP server instance on the Starlette app state + app.state.fastmcp_server = server + + return app diff --git a/tests/server/test_app_state.py b/tests/server/test_app_state.py new file mode 100644 index 000000000..609089400 --- /dev/null +++ b/tests/server/test_app_state.py @@ -0,0 +1,26 @@ +from fastmcp.server import FastMCP +from fastmcp.server.http import create_sse_app, create_streamable_http_app + + +def test_http_app_sets_mcp_server_state(): + server = FastMCP(name="StateTest") + app = server.http_app() + assert app.state.fastmcp_server is server + + +def test_http_app_sse_sets_mcp_server_state(): + server = FastMCP(name="StateTest") + app = server.http_app(transport="sse") + assert app.state.fastmcp_server is server + + +def test_create_streamable_http_app_sets_state(): + server = FastMCP(name="StateTest") + app = create_streamable_http_app(server, "/mcp") + assert app.state.fastmcp_server is server + + +def test_create_sse_app_sets_state(): + server = FastMCP(name="StateTest") + app = create_sse_app(server, message_path="/message", sse_path="/sse") + assert app.state.fastmcp_server is server