Skip to content

Is lifespan ready for the MCP (high-level) server? #392

@KokoiRuby

Description

@KokoiRuby

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

Image

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions