Skip to content

Commit 95ae275

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 c2ca8e0 commit 95ae275

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

Diff for: 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

Diff for: tests/server/fastmcp/test_tool_manager.py

+10
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,8 @@ 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
246+
from mcp.shared.context import LifespanContextT
245247

246248
def tool_with_context(x: int, ctx: Context) -> str:
247249
return str(x)
@@ -256,6 +258,14 @@ def tool_without_context(x: int) -> str:
256258
tool = manager.add_tool(tool_without_context)
257259
assert tool.context_kwarg is None
258260

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

0 commit comments

Comments
 (0)