modelcontextprotocol / modelcontextprotocol/python-sdk

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

Open
#1,974 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug P3 v2
Dominant language
Python
Stars
24.3k
Forks
4k
Avg merge
1d 1h
Merged PRs (30d)
31

Description

Initial Checks
Description

When registering a callable class instance as an MCP tool via FastMCP.add_tool(), the ctx: Context parameter is incorrectly exposed as an externally visible tool parameter instead of being injected by the framework. This is because find_context_parameter() uses typing.get_type_hints() which doesn't introspect the call method of callable class instances.

Suggested Fix
Update find_context_parameter() to handle callable class instances:

def find_context_parameter(fn: Callable[..., Any]) -> str | None:
    from mcp.server.fastmcp.server import Context

    # Handle callable class instances by using __call__ method
    target = fn
    if not (inspect.isfunction(fn) or inspect.ismethod(fn)):
        if callable(fn) and hasattr(fn, "__call__"):
            target = fn.__call__

    try:
        hints = typing.get_type_hints(target)
    except Exception:
        return None

    # ... rest of function unchanged
Example Code
from typing import Annotated, Any
from mcp.server.fastmcp import Context, FastMCP
from mcp.server.session import ServerSession
from starlette.requests import Request
import pydantic

class MyTool:
    def __init__(self, name: str):
        self.__name__ = name

    async def __call__(
        self,
        query: Annotated[str, pydantic.Field(description="Search query")],
        ctx: Context[ServerSession, Any, Request],
    ) -> str:
        """Performs a search."""
        return f"Results for: {query}"

mcp = FastMCP(name="Test Server")
mcp.add_tool(MyTool(name="my_search"), name="my_search", description="Search tool")

# When listing tools, 'ctx' appears as a required parameter in the schema
Python & MCP Python SDK
1.26.0

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at find_context_parameter(), which is used while registering tools through FastMCP.add_tool(). Compare its handling of regular functions with callable class instances and verify the example no longer exposes ctx as a tool parameter when the callable instance is registered.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
api, backend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.