diff --git a/src/mcp/server/mcpserver/utilities/context_injection.py b/src/mcp/server/mcpserver/utilities/context_injection.py index 9cba83e86..cbfdfa4a4 100644 --- a/src/mcp/server/mcpserver/utilities/context_injection.py +++ b/src/mcp/server/mcpserver/utilities/context_injection.py @@ -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 diff --git a/tests/server/mcpserver/test_tool_manager.py b/tests/server/mcpserver/test_tool_manager.py index 550bba50a..716f0fa34 100644 --- a/tests/server/mcpserver/test_tool_manager.py +++ b/tests/server/mcpserver/test_tool_manager.py @@ -413,6 +413,49 @@ def tool_with_context(x: int, ctx: Context[ServerSessionT, None]) -> str: with pytest.raises(ToolError, match="Error executing tool tool_with_context"): await manager.call_tool("tool_with_context", {"x": 42}, context=ctx) + def test_context_detection_callable_class(self): + """Test that context parameters are detected in callable class instances.""" + + class MyTool: + def __init__(self, name: str): + self.__name__ = name + + async def __call__(self, query: str, ctx: Context[ServerSessionT, None]) -> str: # pragma: no cover + return f"Result: {query}" + + manager = ToolManager() + tool = manager.add_tool(MyTool(name="my_tool"), name="my_tool", description="A tool") + assert tool.context_kwarg == "ctx" + # ctx should not appear in the JSON schema + assert "ctx" not in json.dumps(tool.parameters) + + @pytest.mark.anyio + async def test_context_injection_callable_class(self): + """Test that context is injected into callable class instances.""" + + class MyTool: + def __init__(self, name: str): + self.__name__ = name + + 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="my_tool"), name="my_tool", description="A tool") + + mcp = MCPServer() + ctx = mcp.get_context() + result = await manager.call_tool("my_tool", {"x": 42}, context=ctx) + assert result == "42" + + def test_find_context_parameter_non_callable(self): + """Test find_context_parameter returns None for non-callable objects.""" + from mcp.server.mcpserver.utilities.context_injection import find_context_parameter + + result = find_context_parameter(42) # type: ignore[arg-type] + assert result is None + class TestToolAnnotations: def test_tool_annotations(self):