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
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()defquery_db(ctx: Context[ServerSessionT, AppContext]) ->str:
"""Tool that uses initialized resources"""db=ctx.request_context.lifespan_context.dbreturndb.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:
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
The text was updated successfully, but these errors were encountered:
Describe the bug
The code does not work because the type annotation for the
ctx
argument is not simplyContext
; it includes type variablesServerSessionT
andAppContext
.The MCP server assumes that
ctx
will be passed by clients, as its implementation only checks whether the annotation is exactlyContext
.You can see this limitation in the following code:
python-sdk/src/mcp/server/fastmcp/tools/base.py
Lines 53 to 58 in 9ae4df8
The necessity of adding type variables to
Context
is explained in issue #xxx.To Reproduce
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):
The text was updated successfully, but these errors were encountered: