MCP · Lesson 71 of 120
Lifespan
Open once, share everywhere.
Some things should be opened once, when the server starts. A database connection, or an HTTP client. The lifespan opens them at startup, shares them with every tool, and closes them at shutdown.

- Open at startup
- Share with tools
- Close at shutdown
A lifespan
The lifespan opens our pretend database, and yields it. Code after yield runs at shutdown. The tool reads it from the request context. Run it. The database opens once, the tool uses it, and it closes at the end.
lifespan.pypython
import asyncio
from contextlib import asynccontextmanager
from mcp import Client
from mcp.server.mcpserver import MCPServer, Context
@asynccontextmanager
async def lifespan(server):
print("open database"); yield {"db": {1042: "shipped", 1043: "packing"}}; print("close database")
mcp = MCPServer("northwind", lifespan=lifespan)
@mcp.tool()
def order_status(order_id: int, ctx: Context) -> str:
"""Look up an order."""
return ctx.request_context.lifespan_context["db"].get(order_id, "not found")
async def main():
async with Client(mcp) as client:
print((await client.call_tool("order_status", {"order_id": 1043})).content[0].text)
asyncio.run(main())Output
open database packing close database
Summary
Use the lifespan to open shared things once, and read them from the request context. Next, configuration.
Key takeaways- lifespan
- yield
- lifespan_context
Next up: Configuration — environment variables