-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Closed
Description
Hello,
I'm new to the MCP. I followed this section in README.md. However, I'm not able to extract anything from the context.
I simply remove the depdency of fake_database, and made db just a string.
# Add lifespan support for startup/shutdown with strong typing
from contextlib import asynccontextmanager
from collections.abc import AsyncIterator
from dataclasses import dataclass
from mcp.server.fastmcp import Context, FastMCP
# Create a named server
mcp = FastMCP("My App")
@dataclass
class AppContext:
db: str
@asynccontextmanager
async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]:
"""Manage application lifecycle with type-safe context"""
# Initialize on startup
db = "test str"
try:
yield AppContext(db=db)
finally:
# Cleanup on shutdown
...
# Pass lifespan to server
mcp = FastMCP("My App", lifespan=app_lifespan)
# Access type-safe lifespan context in tools
@mcp.tool()
def query_db(ctx: Context) -> str:
"""Tool that uses initialized resources"""
db = ctx.request_context.lifespan_context["db"]
return db
Metadata
Metadata
Assignees
Labels
No labels