@@ -197,6 +197,7 @@ from contextlib import asynccontextmanager
197197from dataclasses import dataclass
198198
199199from mcp.server.fastmcp import Context, FastMCP
200+ from mcp.server.session import ServerSession
200201
201202
202203# Mock database class for example
@@ -242,7 +243,7 @@ mcp = FastMCP("My App", lifespan=app_lifespan)
242243
243244# Access type-safe lifespan context in tools
244245@mcp.tool ()
245- def query_db (ctx : Context) -> str :
246+ def query_db (ctx : Context[ServerSession, AppContext] ) -> str :
246247 """ Tool that uses initialized resources."""
247248 db = ctx.request_context.lifespan_context.db
248249 return db.query()
@@ -314,12 +315,13 @@ Tools can optionally receive a Context object by including a parameter with the
314315<!-- snippet-source examples/snippets/servers/tool_progress.py -->
315316``` python
316317from mcp.server.fastmcp import Context, FastMCP
318+ from mcp.server.session import ServerSession
317319
318320mcp = FastMCP(name = " Progress Example" )
319321
320322
321323@mcp.tool ()
322- async def long_running_task (task_name : str , ctx : Context, steps : int = 5 ) -> str :
324+ async def long_running_task (task_name : str , ctx : Context[ServerSession, None ] , steps : int = 5 ) -> str :
323325 """ Execute a task with progress updates."""
324326 await ctx.info(f " Starting: { task_name} " )
325327
@@ -445,7 +447,7 @@ def get_user(user_id: str) -> UserProfile:
445447
446448# Classes WITHOUT type hints cannot be used for structured output
447449class UntypedConfig :
448- def __init__ (self , setting1 , setting2 ):
450+ def __init__ (self , setting1 , setting2 ): # type: ignore [ reportMissingParameterType ]
449451 self .setting1 = setting1
450452 self .setting2 = setting2
451453
@@ -571,12 +573,13 @@ The Context object provides the following capabilities:
571573<!-- snippet-source examples/snippets/servers/tool_progress.py -->
572574``` python
573575from mcp.server.fastmcp import Context, FastMCP
576+ from mcp.server.session import ServerSession
574577
575578mcp = FastMCP(name = " Progress Example" )
576579
577580
578581@mcp.tool ()
579- async def long_running_task (task_name : str , ctx : Context, steps : int = 5 ) -> str :
582+ async def long_running_task (task_name : str , ctx : Context[ServerSession, None ] , steps : int = 5 ) -> str :
580583 """ Execute a task with progress updates."""
581584 await ctx.info(f " Starting: { task_name} " )
582585
@@ -694,6 +697,7 @@ Request additional information from users. This example shows an Elicitation dur
694697from pydantic import BaseModel, Field
695698
696699from mcp.server.fastmcp import Context, FastMCP
700+ from mcp.server.session import ServerSession
697701
698702mcp = FastMCP(name = " Elicitation Example" )
699703
@@ -709,12 +713,7 @@ class BookingPreferences(BaseModel):
709713
710714
711715@mcp.tool ()
712- async def book_table (
713- date : str ,
714- time : str ,
715- party_size : int ,
716- ctx : Context,
717- ) -> str :
716+ async def book_table (date : str , time : str , party_size : int , ctx : Context[ServerSession, None ]) -> str :
718717 """ Book a table with date availability check."""
719718 # Check if date is available
720719 if date == " 2024-12-25" :
@@ -750,13 +749,14 @@ Tools can interact with LLMs through sampling (generating text):
750749<!-- snippet-source examples/snippets/servers/sampling.py -->
751750``` python
752751from mcp.server.fastmcp import Context, FastMCP
752+ from mcp.server.session import ServerSession
753753from mcp.types import SamplingMessage, TextContent
754754
755755mcp = FastMCP(name = " Sampling Example" )
756756
757757
758758@mcp.tool ()
759- async def generate_poem (topic : str , ctx : Context) -> str :
759+ async def generate_poem (topic : str , ctx : Context[ServerSession, None ] ) -> str :
760760 """ Generate a poem using LLM sampling."""
761761 prompt = f " Write a short poem about { topic} "
762762
@@ -785,12 +785,13 @@ Tools can send logs and notifications through the context:
785785<!-- snippet-source examples/snippets/servers/notifications.py -->
786786``` python
787787from mcp.server.fastmcp import Context, FastMCP
788+ from mcp.server.session import ServerSession
788789
789790mcp = FastMCP(name = " Notifications Example" )
790791
791792
792793@mcp.tool ()
793- async def process_data (data : str , ctx : Context) -> str :
794+ async def process_data (data : str , ctx : Context[ServerSession, None ] ) -> str :
794795 """ Process data with logging."""
795796 # Different log levels
796797 await ctx.debug(f " Debug: Processing ' { data} ' " )
@@ -1244,6 +1245,7 @@ Run from the repository root:
12441245
12451246from collections.abc import AsyncIterator
12461247from contextlib import asynccontextmanager
1248+ from typing import Any
12471249
12481250import mcp.server.stdio
12491251import mcp.types as types
@@ -1272,7 +1274,7 @@ class Database:
12721274
12731275
12741276@asynccontextmanager
1275- async def server_lifespan (_server : Server) -> AsyncIterator[dict ]:
1277+ async def server_lifespan (_server : Server) -> AsyncIterator[dict[ str , Any] ]:
12761278 """ Manage server startup and shutdown lifecycle."""
12771279 # Initialize resources on startup
12781280 db = await Database.connect()
@@ -1304,7 +1306,7 @@ async def handle_list_tools() -> list[types.Tool]:
13041306
13051307
13061308@server.call_tool ()
1307- async def query_db (name : str , arguments : dict ) -> list[types.TextContent]:
1309+ async def query_db (name : str , arguments : dict[ str , Any] ) -> list[types.TextContent]:
13081310 """ Handle database query tool call."""
13091311 if name != " query_db" :
13101312 raise ValueError (f " Unknown tool: { name} " )
@@ -1558,7 +1560,7 @@ server_params = StdioServerParameters(
15581560
15591561# Optional: create a sampling callback
15601562async def handle_sampling_message (
1561- context : RequestContext, params : types.CreateMessageRequestParams
1563+ context : RequestContext[ClientSession, None ] , params : types.CreateMessageRequestParams
15621564) -> types.CreateMessageResult:
15631565 print (f " Sampling request: { params.messages} " )
15641566 return types.CreateMessageResult(
0 commit comments