Skip to content

fix: detect Context parameter in callable class instances#2167

Closed
giulio-leone wants to merge 2 commits intomodelcontextprotocol:mainfrom
giulio-leone:fix/callable-class-context-parameter
Closed

fix: detect Context parameter in callable class instances#2167
giulio-leone wants to merge 2 commits intomodelcontextprotocol:mainfrom
giulio-leone:fix/callable-class-context-parameter

Conversation

@giulio-leone
Copy link

Summary

Fix find_context_parameter() to correctly detect the Context parameter in callable class instances (objects with __call__ method).

Problem

When registering a callable class instance as an MCP tool via add_tool(), the ctx: Context parameter is incorrectly exposed as a visible tool parameter in the JSON schema instead of being injected by the framework.

This happens because typing.get_type_hints() raises TypeError on callable class instances ('<MyTool object>' is not a module, class, method, or function). The exception is caught, find_context_parameter() returns None, and the context parameter is not excluded from the schema.

Solution

Before calling get_type_hints(), detect callable class instances and inspect their __call__ method instead:

target = fn
if not (inspect.isfunction(fn) or inspect.ismethod(fn)):
    if callable(fn) and hasattr(fn, '__call__'):
        target = fn.__call__

This is consistent with how _is_async_callable() (in tools/base.py) already handles callable classes.

Test

Added test_context_injection_callable_class that registers a callable class with a Context parameter and verifies it is properly injected (not exposed in schema).

Fixes #1974

g97iulio1609 added 2 commits February 28, 2026 15:41
find_context_parameter() uses typing.get_type_hints() which raises
TypeError on callable class instances.  Fall back to inspecting the
__call__ method so that the Context parameter is properly detected
and excluded from the tool's JSON schema.

Fixes modelcontextprotocol#1974
@giulio-leone
Copy link
Author

Closing as duplicate of #2178, which has passing CI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

find_context_parameter() fails to detect Context parameter in callable class instances

1 participant