3.0.0
Lifespans let you run code once when the server starts and clean up when it stops. Unlike per-session handlers, lifespans run exactly once regardless of how many clients connect.
Basic Usage
Use the@lifespan decorator to define a lifespan:
Always use
try/finally for cleanup code to ensure it runs even if the server is cancelled.Accessing Lifespan Context
Access the lifespan context in tools viactx.lifespan_context:
Composing Lifespans
Compose multiple lifespans with the| operator:
- Enter in order (left to right)
- Exit in reverse order (right to left)
- Merge their context dicts (later values overwrite earlier on conflict)
Backwards Compatibility
Existing@asynccontextmanager lifespans still work when passed directly to FastMCP:
@asynccontextmanager function with @lifespan functions, wrap it with ContextManagerLifespan:
With FastAPI
When mounting FastMCP into FastAPI, usecombine_lifespans to run both your app’s lifespan and the MCP server’s lifespan:

