fix: trigger lifespan events when using mount_http() (closes #256)#311
Open
Emeralden wants to merge 1 commit into
Open
fix: trigger lifespan events when using mount_http() (closes #256)#311Emeralden wants to merge 1 commit into
Emeralden 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.
Comment on lines
+370
to
+385
| _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 |
Comment on lines
+371
to
+385
| _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 |
Comment on lines
+51
to
+58
| 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 |
Comment on lines
+58
to
+62
| await receive_q.put({"type": "lifespan.shutdown"}) | ||
| try: | ||
| await asyncio.wait_for(send_q.get(), timeout=3.0) | ||
| except asyncio.TimeoutError: | ||
| pass |
Comment on lines
+370
to
+371
| _main_router = self.fastapi.router | ||
| _original_lifespan = _main_router.lifespan_context |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.