Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type error when using Lifespan context #355

Closed
jkawamoto opened this issue Mar 24, 2025 · 0 comments
Closed

Type error when using Lifespan context #355

jkawamoto opened this issue Mar 24, 2025 · 0 comments

Comments

@jkawamoto
Copy link
Contributor

Describe the bug
I attempted to use AppContext in my project by utilizing the sample code provided in the README.md. However, it raised the following type error:

error: Cannot access attribute "db" for class "None"

To Reproduce
Below is the sample code taken from the README.md.

from contextlib import asynccontextmanager
from collections.abc import AsyncIterator
from dataclasses import dataclass

from mcp.server.fastmcp import Context, FastMCP


class Database:   # Replace with your actual DB type
    @classmethod
    async def connect(cls):
        return cls()

    async def disconnect(self):
        pass

    def query(self):
        return "Hello, World!"


# Create a named server
mcp = FastMCP("My App")


@dataclass
class AppContext:
    db: Database


@asynccontextmanager
async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]:
    """Manage application lifecycle with type-safe context"""
    # Initialize on startup
    db = await Database.connect()
    try:
        yield AppContext(db=db)
    finally:
        # Cleanup on shutdown
        await db.disconnect()


# 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.query()

Store the code above in a file named readme.py and run the following command:

uv run pyright readme.py

Expected behavior
The type check should pass without any errors.

Desktop (please complete the following information):

  • OS: macOS 15.3.2
  • Browser N/A
  • Version N/A
@jkawamoto jkawamoto changed the title Type Errors in Sample Code Type error when using Lifespan context Mar 25, 2025
dsp-ant added a commit that referenced this issue Mar 25, 2025
The TypeVar LifespanContextT was incorrectly defined with a default=None, which caused type errors when using strongly typed custom context objects. This change properly propagates the type information from custom lifespans to request contexts.
jkawamoto added a commit to jkawamoto/mcp-bear that referenced this issue Mar 25, 2025
Until modelcontextprotocol/python-sdk#355 is solved, we should ignore type errors around AppContext.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant