modelcontextprotocol / modelcontextprotocol/python-sdk
find_context_parameter() fails to detect Context parameter in callable class instances
未关闭
还没有人认领这个 Issue。
bug
P3
v2
- 主要语言
- Python
- 星标
- 24.3k
- 派生
- 4k
- 平均合并
- 1 天 1 小时
- 30 天内合并 PR
- 31
描述
Initial Checks
- I confirm that I'm using the latest version of MCP Python SDK
- I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue
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
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 find_context_parameter() 开始,它在通过 FastMCP.add_tool() 注册工具时使用。比较它对普通函数和可调用类实例的处理,并验证在注册可调用实例时,示例不再将 ctx 暴露为工具参数。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- api, backend
- Issue 类型
- 缺陷
- 难度
- 2/5
- 预计耗时
- 1-3 小时
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 55/100