Initial Checks
Description
With stdio protocol, the lifespan runs on server start up as expected. However, with streamable-http the lifespan does not execute on server start up.
Example Code
fromcollections.abcimportAsyncIteratorfromcontextlibimportasynccontextmanagerfromdataclassesimportdataclassfrommcp.server.fastmcpimportContext, FastMCPfrommcp.server.sessionimportServerSession# Mock database class for exampleclassDatabase:
"""Mock database class for example."""@classmethodasyncdefconnect(cls) ->"Database":
"""Connect to database."""returncls()
asyncdefdisconnect(self) ->None:
"""Disconnect from database."""passdefquery(self) ->str:
"""Execute a query."""return"Query result"@dataclassclassAppContext:
"""Application context with typed dependencies."""db: Database@asynccontextmanagerasyncdefapp_lifespan(server: FastMCP) ->AsyncIterator[AppContext]:
"""Manage application lifecycle with type-safe context."""# Initialize on startupprint("Enter lifespan")
db=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[ServerSession, AppContext]) ->str:
"""Tool that uses initialized resources."""db=ctx.request_context.lifespan_context.dbreturndb.query()
mcp.run(transport="streamable-http") # on server startup, the lifespan does not runPython & MCP Python SDK
Initial Checks
Description
With
stdioprotocol, the lifespan runs on server start up as expected. However, withstreamable-httpthe lifespan does not execute on server start up.Example Code
Python & MCP Python SDK