Skip to content

fix: trigger lifespan events when using mount_http() (closes #256)#311

Open
Emeralden wants to merge 1 commit into
tadata-org:mainfrom
Emeralden:fix/lifespan-not-triggered-mount-http
Open

fix: trigger lifespan events when using mount_http() (closes #256)#311
Emeralden wants to merge 1 commit into
tadata-org:mainfrom
Emeralden:fix/lifespan-not-triggered-mount-http

Conversation

@Emeralden

@Emeralden Emeralden commented Jun 2, 2026

Copy link
Copy Markdown

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

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

  • Added relevant tests (6 tests in tests/test_lifespan.py)
  • Run ruff & mypy and there are no issues
  • All tests pass (89/89)

View with Codesmith Autofix with Codesmith
Need help on this PR? Tag @codesmith with what you need. Autofix is disabled.

…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
Copilot AI review requested due to automatic review settings June 2, 2026 03:13

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 thread fastapi_mcp/server.py
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 thread fastapi_mcp/server.py
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 thread tests/test_lifespan.py
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 thread fastapi_mcp/server.py
Comment on lines +370 to +371
_main_router = self.fastapi.router
_original_lifespan = _main_router.lifespan_context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] lifespan context manager not triggered when using mount_http() in fastapi-mcp 0.4.0

2 participants