Skip to content

Commit 37a3979

Browse files
committed
Fix context detection by checking for subclass relationship
Previously, the code only checked for exact matches with `Context`. This update ensures that subclasses of `Context` are also correctly identified, improving flexibility and reliability.
1 parent 568cbd1 commit 37a3979

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

src/mcp/server/fastmcp/tools/base.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import inspect
44
from collections.abc import Callable
5-
from typing import TYPE_CHECKING, Any
5+
from typing import TYPE_CHECKING, Any, get_origin
66

77
from pydantic import BaseModel, Field
88

@@ -53,7 +53,9 @@ def from_function(
5353
if context_kwarg is None:
5454
sig = inspect.signature(fn)
5555
for param_name, param in sig.parameters.items():
56-
if param.annotation is Context:
56+
if get_origin(param.annotation) is not None:
57+
continue
58+
if issubclass(param.annotation, Context):
5759
context_kwarg = param_name
5860
break
5961

tests/server/fastmcp/test_tool_manager.py

+11
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,7 @@ def test_context_parameter_detection(self):
242242
"""Test that context parameters are properly detected in
243243
Tool.from_function()."""
244244
from mcp.server.fastmcp import Context
245+
from mcp.server.session import ServerSessionT
245246

246247
def tool_with_context(x: int, ctx: Context) -> str:
247248
return str(x)
@@ -256,6 +257,16 @@ def tool_without_context(x: int) -> str:
256257
tool = manager.add_tool(tool_without_context)
257258
assert tool.context_kwarg is None
258259

260+
class LifespanParam: ...
261+
262+
def tool_with_specialized_context(
263+
x: int, ctx: Context[ServerSessionT, LifespanParam]
264+
) -> str:
265+
return str(x)
266+
267+
tool = manager.add_tool(tool_with_specialized_context)
268+
assert tool.context_kwarg == "ctx"
269+
259270
@pytest.mark.anyio
260271
async def test_context_injection(self):
261272
"""Test that context is properly injected during tool execution."""

0 commit comments

Comments
 (0)