Skip to content

Tool.from_function fails to detect parameterized Context subclasses #537

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
triplewhopper opened this issue Apr 18, 2025 · 1 comment
Closed

Comments

@triplewhopper
Copy link

triplewhopper commented Apr 18, 2025

Describe the bug
In Tool.from_function, the detection of Context parameters only matches the bare Context type. Functions annotated with parameterized generics such as Context[ServerSession, MyContext] are not recognized, causing tool.context_kwarg to remain None.

To Reproduce

  1. Install MCP Python SDK v1.6.0.
  2. In a Python script or REPL:
    from mcp.server.fastmcp import Context
    from mcp.server.fastmcp.tools.base import Tool
    from mcp.server.session import ServerSession
    
    class MyContext:
        def __init__(self, x: int):
            self.x = x
    
    def example_tool(ctx: Context[ServerSession, MyContext], y: int) -> int:
        return 42
    
    def example_tool2(ctx: Context, y: int) -> int:
        return 42
    
    tool = Tool.from_function(example_tool)
    print(tool.context_kwarg)  # outputs None
    
    tool2 = Tool.from_function(example_tool2)
    print(tool2.context_kwarg) # outputs 'ctx'

Screenshots
Image

Environment:

  • OS: macOS 15.3.2
  • Python version: 3.12.9
  • MCP Python SDK version: 1.6.0

Additional context
Suggest one-line fix at mcp/server/fastmcp/tools/base.py:56:

-    if param.annotation is Context:
+    if isinstance(param.annotation, type) and issubclass(param.annotation, Context):

and a unit test to verify:

def test_generic_context_recognition():
    from mcp.server.fastmcp import Context
    from mcp.server.fastmcp.tools.base import Tool
    from mcp.server.session import ServerSession

    class MyContext:
        pass

    def fn(ctx: Context[ServerSession, MyContext]):
        ...

    tool = Tool.from_function(fn)
    assert tool.context_kwarg == "ctx"
@triplewhopper
Copy link
Author

Fixed by PR #358 on main. Closing as completed.

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

No branches or pull requests

1 participant