How to work with lifespan? #1763
Unanswered
MicaelJarniac
asked this question in
Q&A
Replies: 1 comment
-
|
mcp.http_app() returns a StarletteWithLifespan that already has a lifespan managing its StreamableHTTPSessionManager. so we append to it: from contextlib import asynccontextmanager
import asyncio
def wrap_lifespan_with_background_task(original_lifespan):
"""
Wraps FastMCP's existing lifespan to add custom background tasks.
Preserves the session manager lifespan while adding custom logic.
"""
@asynccontextmanager
async def combined_lifespan(app):
# Run FastMCP's original lifespan (manages session manager)
async with original_lifespan(app):
# Startup: Start your background task
app.state.my_background_task = asyncio.create_task(
my_background_function()
)
logger.info("Background task started")
yield # App runs here
# Shutdown: Stop background task gracefully
if bg_task := getattr(app.state, "my_background_task", None):
bg_task.cancel()
try:
await asyncio.wait_for(bg_task, timeout=5.0)
except asyncio.CancelledError:
pass # Expected
except asyncio.TimeoutError:
logger.warning("Task cancellation timed out")
except Exception as exc:
logger.exception("Error cancelling task: %s", exc)
logger.info("Background task stopped")
return combined_lifespan
def main():
# Create FastMCP app
app = mcp.http_app(path="/mcp")
# Wrap the existing lifespan
original_lifespan = app.router.lifespan_context
if original_lifespan:
app.router.lifespan_context = wrap_lifespan_with_background_task(
original_lifespan
)
else:
logger.warning("No FastMCP lifespan found!")
uvicorn.run(app, host="0.0.0.0", port=8000) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
The FastMCP 1.0 implementation in
modelcontextprotocol/python-sdkhas the following:I wanted to know how to do the same on this FastMCP 2.0.
Especially, how to get it correctly type-hinted and everything like that.
I couldn't find it in the docs, and from testing locally, the type-hints aren't working.
Is there a better approach for initializing a resource, like in the example above?
Beta Was this translation helpful? Give feedback.
All reactions