-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Description
Describe the bug
The code does not work because the type annotation for the ctx argument is not simply Context; it includes type variables ServerSessionT and AppContext.
@mcp.tool()
def query_db(ctx: Context[ServerSessionT, AppContext]) -> str:
"""Tool that uses initialized resources"""
db = ctx.request_context.lifespan_context.db
return db.query()The MCP server assumes that ctx will be passed by clients, as its implementation only checks whether the annotation is exactly Context.
You can see this limitation in the following code:
python-sdk/src/mcp/server/fastmcp/tools/base.py
Lines 53 to 58 in 9ae4df8
| if context_kwarg is None: | |
| sig = inspect.signature(fn) | |
| for param_name, param in sig.parameters.items(): | |
| if param.annotation is Context: | |
| context_kwarg = param_name | |
| break |
The necessity of adding type variables to Context is explained in issue #xxx.
To Reproduce
- Apply the following patch:
diff --git a/examples/fastmcp/simple_echo.py b/examples/fastmcp/simple_echo.py
index c261526..3069b7e 100644
--- a/examples/fastmcp/simple_echo.py
+++ b/examples/fastmcp/simple_echo.py
@@ -1,14 +1,15 @@
"""
FastMCP Echo Server
"""
+from typing import Any
-from mcp.server.fastmcp import FastMCP
+from mcp.server.fastmcp import FastMCP, Context
# Create server
mcp = FastMCP("Echo Server")
@mcp.tool()
-def echo(text: str) -> str:
+def echo(ctx:Context[Any, Any], text: str) -> str:
"""Echo the input text"""
return text - Run the following command:
uv run pytest tests/test_examples.py
- The test will fail with the following error:
Error executing tool echo: 1 validation error for echoArguments
ctx
Field required [type=missing, input_value={'text': 'hello'}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.10/v/missing
Expected behavior
Type variables should be allowed in tool definitions. The MCP server should correctly handle Context annotations that include type variables.
Desktop (please complete the following information):
- OS: macOS 15.3.2
- Browser N/A
- Version N/A