modelcontextprotocol / modelcontextprotocol/python-sdk
find_context_parameter() fails to detect Context parameter in callable class instances
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Python
- Star
- 24.3k
- Fork
- 4k
- Merge trung bình
- 1 ngày 1 giờ
- Pull request đã merge (30 ngày)
- 31
Mô tả
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
Hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Hướng nghiên cứu
Bắt đầu từ find_context_parameter(), được sử dụng khi đăng ký các tool thông qua FastMCP.add_tool(). So sánh cách hàm này xử lý các hàm thông thường với các thể hiện lớp có thể gọi, đồng thời xác minh rằng ví dụ không còn hiển thị ctx dưới dạng tham số của tool khi thể hiện có thể gọi được đăng ký.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Đánh giá
- Công nghệ
- python
- Lĩnh vực
- api, backend
- Loại issue
- Lỗi
- Độ khó
- 2/5
- Thời gian dự kiến
- 1-3 giờ
- Mức độ hoạt động
- Đình trệ
- Độ rõ ràng
- Đặc tả rõ ràng
- Mức phù hợp với người mới
- 55/100