Skip to main content
New in version 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:
The dict you yield becomes the lifespan context, accessible from tools.
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 via ctx.lifespan_context:

Composing Lifespans

Compose multiple lifespans with the | operator:
Composed lifespans:
  • 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:
To compose an @asynccontextmanager function with @lifespan functions, wrap it with ContextManagerLifespan:

With FastAPI

When mounting FastMCP into FastAPI, use combine_lifespans to run both your app’s lifespan and the MCP server’s lifespan:
See the FastAPI integration guide for full details.