Closed
Description
Describe the bug
In Tool.from_function
, the detection of Context
parameters only matches the bare Context
type. Functions annotated with parameterized generics such as Context[ServerSession, MyContext]
are not recognized, causing tool.context_kwarg
to remain None
.
To Reproduce
- Install MCP Python SDK v1.6.0.
- In a Python script or REPL:
from mcp.server.fastmcp import Context from mcp.server.fastmcp.tools.base import Tool from mcp.server.session import ServerSession class MyContext: def __init__(self, x: int): self.x = x def example_tool(ctx: Context[ServerSession, MyContext], y: int) -> int: return 42 def example_tool2(ctx: Context, y: int) -> int: return 42 tool = Tool.from_function(example_tool) print(tool.context_kwarg) # outputs None tool2 = Tool.from_function(example_tool2) print(tool2.context_kwarg) # outputs 'ctx'
Environment:
- OS: macOS 15.3.2
- Python version: 3.12.9
- MCP Python SDK version: 1.6.0
Additional context
Suggest one-line fix at mcp/server/fastmcp/tools/base.py:56
:
- if param.annotation is Context:
+ if isinstance(param.annotation, type) and issubclass(param.annotation, Context):
and a unit test to verify:
def test_generic_context_recognition():
from mcp.server.fastmcp import Context
from mcp.server.fastmcp.tools.base import Tool
from mcp.server.session import ServerSession
class MyContext:
pass
def fn(ctx: Context[ServerSession, MyContext]):
...
tool = Tool.from_function(fn)
assert tool.context_kwarg == "ctx"
Metadata
Metadata
Assignees
Labels
No labels