Context managers in MCP servers
MCP allows you to control the lifecycle management of your resources. Let’s have a look at some code:
async def load_settings() -> dict:
"""Load settings from a configuration file."""
# Simulate loading settings
return {"setting1": "value1", "setting2": "value2"}
@asynccontextmanager
async def server_lifespan(server: Server) -> AsyncIterator[dict]:
"""Manage server startup and shutdown lifecycle."""
# Initialize resources on startup
db = await Database.connect()
settings = await load_settings()
try:
yield {"db": db, "settings": settings}
finally:
# Clean up on shutdown
await db.disconnect()
Here, we’ve done several things:
- Defined an asynchronous context manager,
server_lifespan, that manages the lifecycle of the server - Initialized...