Skip to main content

fastmcp.server.lifespan

Composable lifespans for FastMCP servers. This module provides a @lifespan decorator for creating composable server lifespans that can be combined using the | operator. Example:
To compose with existing @asynccontextmanager lifespans, wrap them explicitly:

Functions

lifespan

Decorator to create a composable lifespan. Use this decorator on an async generator function to make it composable with other lifespans using the | operator. Args:
  • fn: An async generator function that takes a FastMCP server and yields a dict for the lifespan context.
Returns:
  • A composable Lifespan wrapper.

Classes

Lifespan

Composable lifespan wrapper. Wraps an async generator function and enables composition via the | operator. The wrapped function should yield a dict that becomes part of the lifespan context.

ContextManagerLifespan

Lifespan wrapper for already-wrapped context manager functions. Use this for functions already decorated with @asynccontextmanager.

ComposedLifespan

Two lifespans composed together. Enters the left lifespan first, then the right. Exits in reverse order. Results are shallow-merged into a single dict.