fix: trigger lifespan events when using mount_http() (closes #256) - #311
fix: trigger lifespan events when using mount_http() (closes #256)#311Emeralden wants to merge 1 commit into
Conversation
…rg#256) When FastAPI(lifespan=...) is used, Starlette replaces the router's lifespan_context with the user's function and completely bypasses any on_startup / on_shutdown handlers registered via add_event_handler(). This caused the ASGI lifespan protocol to appear unsupported to uvicorn, silently skipping DB connections, caches, and background task setup. Fix: wrap self.fastapi.router.lifespan_context instead of using add_event_handler(). The wrapper runs the user's startup first (so their resources are available to MCP tools), then starts the StreamableHTTP session manager, and shuts them down in reverse order. Also add explicit startup() / shutdown() methods to FastApiHttpSessionManager so callers can integrate the session manager into their own lifecycle management if needed. Tests: 6 new tests in tests/test_lifespan.py covering - lifespan startup/shutdown fires with mount_http() - correct startup-before-shutdown ordering - user resources available during HTTP requests - MCP /mcp endpoint reachable post-startup - apps without lifespan continue working - session manager starts after user startup
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Adds robust lifespan integration for mount_http() so the MCP HTTP session manager starts/stops alongside the FastAPI app lifespan (regression coverage for issue #256).
Changes:
- Wrap FastAPI’s router lifespan context to start/stop the MCP HTTP session manager in
mount_http(). - Expose explicit
startup()/shutdown()APIs on the HTTP transport (with lazy fallback retained). - Add async tests that manually drive ASGI lifespan to validate startup/shutdown ordering and endpoint availability.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 5 comments.
| File | Description |
|---|---|
| tests/test_lifespan.py | New regression tests for ASGI lifespan behavior when using mount_http(). |
| fastapi_mcp/transport/http.py | Adds explicit startup()/shutdown() methods and clarifies lazy-start behavior. |
| fastapi_mcp/server.py | Wraps FastAPI router lifespan context so MCP session manager follows app lifecycle. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| _main_router = self.fastapi.router | ||
| _original_lifespan = _main_router.lifespan_context | ||
| _transport = http_transport # capture for closure | ||
|
|
||
| @asynccontextmanager | ||
| async def _mcp_lifespan(app: Any): | ||
| # Run user startup first so their resources (DB, cache …) are | ||
| # available when the MCP session manager begins accepting clients. | ||
| async with _original_lifespan(app) as state: | ||
| await _transport.startup() | ||
| try: | ||
| yield state | ||
| finally: | ||
| await _transport.shutdown() | ||
|
|
||
| _main_router.lifespan_context = _mcp_lifespan |
| _original_lifespan = _main_router.lifespan_context | ||
| _transport = http_transport # capture for closure | ||
|
|
||
| @asynccontextmanager | ||
| async def _mcp_lifespan(app: Any): | ||
| # Run user startup first so their resources (DB, cache …) are | ||
| # available when the MCP session manager begins accepting clients. | ||
| async with _original_lifespan(app) as state: | ||
| await _transport.startup() | ||
| try: | ||
| yield state | ||
| finally: | ||
| await _transport.shutdown() | ||
|
|
||
| _main_router.lifespan_context = _mcp_lifespan |
| if self._manager_task and not self._manager_task.done(): | ||
| self._manager_task.cancel() | ||
| try: | ||
| await self._manager_task | ||
| except asyncio.CancelledError: | ||
| pass | ||
| self._manager_started = False | ||
| self._session_manager = None |
| await receive_q.put({"type": "lifespan.shutdown"}) | ||
| try: | ||
| await asyncio.wait_for(send_q.get(), timeout=3.0) | ||
| except asyncio.TimeoutError: | ||
| pass |
| _main_router = self.fastapi.router | ||
| _original_lifespan = _main_router.lifespan_context |
|
@Emeralden — I adopted your patch from this PR and opened #339 with it (rebased onto current main, plus your 6 lifespan tests — the ordering test fails on main today since the session manager starts lazily outside the lifespan). Full suite 75/75. Credited in the commit and PR — thanks, hopefully this helps it land. |
When FastAPI(lifespan=...) is used, Starlette replaces the router's lifespan_context with the user's function and completely bypasses any on_startup / on_shutdown handlers registered via add_event_handler(). This caused the ASGI lifespan protocol to appear unsupported to uvicorn, silently skipping DB connections, caches, and background task setup.
Fix: wrap self.fastapi.router.lifespan_context instead of using add_event_handler(). The wrapper runs the user's startup first (so their resources are available to MCP tools), then starts the StreamableHTTP session manager, and shuts them down in reverse order.
Also add explicit startup() / shutdown() methods to FastApiHttpSessionManager so callers can integrate the session manager into their own lifecycle management if needed.
Tests: 6 new tests in tests/test_lifespan.py covering
Describe your changes
When FastAPI(lifespan=...) is used, Starlette replaces the router's lifespan_context with the user's function and completely bypasses any on_startup / on_shutdown handlers registered via add_event_handler(). This caused the ASGI lifespan protocol to appear unsupported to uvicorn, silently skipping DB connections, caches, and background task setup.
Fix: wrap self.fastapi.router.lifespan_context instead of using add_event_handler(). The wrapper runs the user's startup first (so their resources are available to MCP tools), then starts the StreamableHTTP session manager, and shuts them down in reverse order.
Also add explicit startup() / shutdown() methods to FastApiHttpSessionManager so callers can integrate the session manager into their own lifecycle management if needed.
Issue ticket number and link
Closes #256
Screenshots
(No UI change. Bug fix only)
Checklist
tests/test_lifespan.py)Need help on this PR? Tag
@codesmithwith what you need. Autofix is disabled.