You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
fromcontextlibimportasynccontextmanagerfromcollections.abcimportAsyncIteratorfromdataclassesimportdataclassfrommcp.server.fastmcpimportContext, FastMCPclassDatabase: # Replace with your actual DB type@classmethodasyncdefconnect(cls):
returncls()
asyncdefdisconnect(self):
passdefquery(self):
return"Hello, World!"# Create a named servermcp=FastMCP("My App")
@dataclassclassAppContext:
db: Database@asynccontextmanagerasyncdefapp_lifespan(server: FastMCP) ->AsyncIterator[AppContext]:
"""Manage application lifecycle with type-safe context"""# Initialize on startupdb=awaitDatabase.connect()
try:
yieldAppContext(db=db)
finally:
# Cleanup on shutdownawaitdb.disconnect()
# Pass lifespan to servermcp=FastMCP("My App", lifespan=app_lifespan)
# Access type-safe lifespan context in tools@mcp.tool()defquery_db(ctx: Context) ->str:
"""Tool that uses initialized resources"""db=ctx.request_context.lifespan_context.dbreturndb.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
The text was updated successfully, but these errors were encountered:
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
Describe the bug
I attempted to use
AppContext
in my project by utilizing the sample code provided in theREADME.md
. However, it raised the following type error:To Reproduce
Below is the sample code taken from the
README.md
.Store the code above in a file named
readme.py
and run the following command:Expected behavior
The type check should pass without any errors.
Desktop (please complete the following information):
The text was updated successfully, but these errors were encountered: