fix: detect Context parameter in callable class instances#2167
Open
giulio-leone wants to merge 1 commit intomodelcontextprotocol:mainfrom
Open
fix: detect Context parameter in callable class instances#2167giulio-leone wants to merge 1 commit intomodelcontextprotocol:mainfrom
giulio-leone wants to merge 1 commit intomodelcontextprotocol:mainfrom
Conversation
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 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fix
find_context_parameter()to correctly detect theContextparameter in callable class instances (objects with__call__method).Problem
When registering a callable class instance as an MCP tool via
add_tool(), thectx: Contextparameter 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()raisesTypeErroron callable class instances ('<MyTool object>' is not a module, class, method, or function). The exception is caught,find_context_parameter()returnsNone, 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:This is consistent with how
_is_async_callable()(intools/base.py) already handles callable classes.Test
Added
test_context_injection_callable_classthat registers a callable class with aContextparameter and verifies it is properly injected (not exposed in schema).Fixes #1974