Server Lifespan
70%
Defining a Lifespan
The lifespan is an async generator function decorated with @lifespan. It yields once, and whatever you yield becomes available to all tools via ctx.lifespan_context. The try/finally block ensures cleanup code runs even if the server is cancelled or an exception occurs:
from fastmcp import FastMCP, Context
from fastmcp.server.lifespan import lifespan
@lifespan
async def app_lifespan(server):
# This runs once when the server starts
db = await connect_to_database()
try:
yield {"db": db} # make db available to all tools
finally:
# This runs once when the server stops
await db.close()
mcpPractical MCP with FastMCP & LangChain
Engineering the Agentic ExperienceEnroll now to unlock current content and receive all future updates for free. Your purchase supports the author and fuels the creation of more exciting content. Act fast, as the price will rise as the course nears completion!
