π The fast, Pythonic way to build MCP servers and clients.
fix(tools): take partial tool names and docstrings from the wrapped function (#5269)
εεΊη±³949fea4954a9
diff --git a/fastmcp_slim/fastmcp/tools/function_parsing.py b/fastmcp_slim/fastmcp/tools/function_parsing.pyindex 760dd3b08..d267047f2 100644--- a/fastmcp_slim/fastmcp/tools/function_parsing.py+++ b/fastmcp_slim/fastmcp/tools/function_parsing.py@@ -299,9 +299,23 @@ class ParsedFunction:"Functions with **kwargs are not supported as tools")- # collect name and description before we potentially modify the function- fn_name = getattr(fn, "__name__", None) or fn.__class__.__name__- outer_docstring = parse_docstring(fn)+ # Keep the partial's bound signature, and fall back to the wrapped+ # callable only for metadata the partial hasn't explicitly overridden.+ target = fn+ partial_name = None+ partial_docstring = ParsedDocstring()+ has_partial_docstring = False+ while isinstance(target, functools.partial):+ partial_name = partial_name or getattr(target, "__name__", None)+ if not has_partial_docstring and "__doc__" in target.__dict__:+ partial_docstring = parse_docstring(target)+ has_partial_docstring = True+ target = target.func+ fn_name = partial_name or getattr(target, "__name__", None)+ fn_name = fn_name or target.__class__.__name__+ outer_docstring = (+ partial_docstring if has_partial_docstring else parse_docstring(target)+ )# if the fn is a callable class, we need to get the __call__ method from here outif not inspect.isroutine(fn) and not isinstance(fn, functools.partial):@@ -316,11 +330,25 @@ class ParsedFunction:# describes __init__, so falling back to it would risk injecting# constructor docs into __call__'s schema on overlapping names.# The description, however, comes from the class docstring (which- # describes what the tool IS) when present.- inner_docstring = parse_docstring(fn)+ # describes what the tool IS) when present. A partial likewise keeps+ # its own partially-bound signature but declares its parameters in+ # the wrapped function's docstring.+ if isinstance(fn, functools.partial):+ doc_fn = target if inspect.isroutine(target) else target.__call__+ else:+ doc_fn = fn+ inner_docstring = parse_docstring(doc_fn)parsed_docstring = ParsedDocstring(- description=outer_docstring.description or inner_docstring.description,- parameters=inner_docstring.parameters,+ description=(+ outer_docstring.description+ if has_partial_docstring+ else outer_docstring.description or inner_docstring.description+ ),+ parameters=(+ partial_docstring.parameters+ if has_partial_docstring+ else inner_docstring.parameters+ ),)# Transform Context type annotations to Depends() for unified DIdiff --git a/tests/tools/tool/test_tool.py b/tests/tools/tool/test_tool.pyindex 0aad4445c..9c2fe4c5a 100644--- a/tests/tools/tool/test_tool.py+++ b/tests/tools/tool/test_tool.py@@ -1,3 +1,4 @@+import functoolsfrom datetime import timedeltafrom typing import Annotated@@ -11,6 +12,7 @@ from mcp_types import ()from pydantic import BaseModel, Field+from fastmcp import Client, FastMCPfrom fastmcp.tools.base import Tool, ToolResultfrom fastmcp.utilities.types import Audio, File, Image@@ -322,6 +324,93 @@ class TestToolFromFunction:):Tool.from_function(lambda x: x)+ async def test_partial_function(self):+ """A partial takes its name and docstring from the wrapped function,+ not from functools.partial's class."""++ def multiply(x: int, y: int) -> int:+ """Multiply two numbers.++ Args:+ x: The first number.+ y: The second number.+ """+ return x * y++ tool = Tool.from_function(functools.partial(multiply, y=2))++ assert tool.name == "multiply"+ assert tool.description == "Multiply two numbers."+ assert tool.parameters["properties"] == {+ "x": {"type": "integer", "description": "The first number."},+ "y": {"default": 2, "type": "integer", "description": "The second number."},+ }++ result = await tool.run({"x": 3})+ assert result.structured_content == {"result": 6}++ async def test_partial_functions_do_not_collide(self):+ """Partials over different functions must not share the name 'partial',+ which makes the second registration replace the first."""++ def multiply(x: int, y: int) -> int:+ """Multiply two numbers."""+ return x * y++ def greet(name: str, greeting: str) -> str:+ """Greet a person."""+ return f"{greeting}, {name}!"++ mcp = FastMCP()+ mcp.add_tool(functools.partial(multiply, y=2))+ mcp.add_tool(functools.partial(greet, greeting="Hello"))++ async with Client(mcp) as client:+ tools = await client.list_tools()++ assert {tool.name: tool.description for tool in tools} == {+ "multiply": "Multiply two numbers.",+ "greet": "Greet a person.",+ }++ @pytest.mark.parametrize("docstring", ["Double the input.", "", None])+ async def test_partial_explicit_metadata_is_preserved(+ self, docstring: str | None+ ) -> None:+ def multiply(x: int, y: int) -> int:+ """Multiply two numbers."""+ return x * y++ double = functools.partial(multiply, y=2)+ setattr(double, "__name__", "double")+ setattr(double, "__doc__", docstring)+ tool = Tool.from_function(double)++ assert tool.name == "double"+ assert tool.description == (docstring or None)+ assert (await tool.run({"x": 3})).structured_content == {"result": 6}+ assert (await tool.run({"x": 3, "y": 5})).structured_content == {"result": 15}++ def test_partial_explicit_parameter_docs_are_preserved(self) -> None:+ def multiply(x: int, y: int) -> int:+ """Multiply two numbers.++ Args:+ x: Original input.+ """+ return x * y++ double = functools.partial(multiply, y=2)+ double.__doc__ = """Double the input.++ Args:+ x: Custom input.+ """+ tool = Tool.from_function(double, name="explicit_name", description="")+ assert tool.name == "explicit_name"+ assert tool.description == ""+ assert tool.parameters["properties"]["x"]["description"] == "Custom input."+def test_private_arguments(self):def add(_a: int, _b: int) -> int:"""Add two numbers."""