Skip to content
Closed
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
43 changes: 43 additions & 0 deletions tests/server/mcpserver/test_tool_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down