Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/mcp/server/mcpserver/utilities/context_injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,15 @@ def find_context_parameter(fn: Callable[..., Any]) -> str | None:
"""
from mcp.server.mcpserver.server import Context

# Handle callable class instances by inspecting __call__ method
target = fn
if not (inspect.isfunction(fn) or inspect.ismethod(fn)):
if callable(fn) and hasattr(fn, "__call__"):
target = fn.__call__

# Get type hints to properly resolve string annotations
try:
hints = typing.get_type_hints(fn)
hints = typing.get_type_hints(target)
except Exception: # pragma: lax no cover
# If we can't resolve type hints, we can't find the context parameter
return None
Expand Down
17 changes: 17 additions & 0 deletions tests/server/mcpserver/test_tool_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,23 @@ async def async_tool(x: int, ctx: Context[ServerSessionT, None]) -> str:
result = await manager.call_tool("async_tool", {"x": 42}, context=ctx)
assert result == "42"

@pytest.mark.anyio
async def test_context_injection_callable_class(self):
"""Test that context is properly injected for callable class instances."""

class MyTool:
async def __call__(self, x: int, ctx: Context[ServerSessionT, None]) -> str:
assert isinstance(ctx, Context)
return str(x)

manager = ToolManager()
manager.add_tool(MyTool(), name="callable_tool")

mcp = MCPServer()
ctx = mcp.get_context()
result = await manager.call_tool("callable_tool", {"x": 42}, context=ctx)
assert result == "42"

@pytest.mark.anyio
async def test_context_optional(self):
"""Test that context is optional when calling tools."""
Expand Down