Skip to content

Conversation

@hashwnath
Copy link

Summary

Fix find_context_parameter() to correctly detect Context parameters in callable class instances registered via FastMCP.add_tool().

Motivation and Context

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

Root cause: typing.get_type_hints(fn) is called on the class instance rather than its __call__ method, so the Context type hint is not resolved.

Fix: Detect non-function/non-method callables and target their __call__ method for type hint resolution. This mirrors the existing pattern in _is_async_callable().

Resolves #1974

What Has Been Changed?

  • src/mcp/server/mcpserver/utilities/context_injection.py: Added callable class instance handling before get_type_hints() call
  • tests/server/mcpserver/test_tool_manager.py: Added 3 tests:
    • test_context_parameter_detection_callable_class — sync callable class
    • test_context_parameter_detection_async_callable_class — async callable class
    • test_context_injection_callable_class — full injection + schema exclusion

How Has This Been Tested?

  • All 54 tests in test_tool_manager.py pass (including 3 new tests)
  • Ruff linting passes
  • New tests verify:
    • context_kwarg is correctly set to "ctx"
    • ctx is excluded from tool parameters JSON schema
    • Context is properly injected during tool execution

Breaking Changes

No breaking changes.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

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

Root cause: typing.get_type_hints() was called on the class instance
rather than its __call__ method, so Context type hints were not resolved.

Fix: detect non-function/non-method callables and target their __call__
method, mirroring the existing pattern in _is_async_callable().

Fixes modelcontextprotocol#1974
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