Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Use renamed argument names in transformed tool validation errors (#6158)

Kartik Madana8172c97c9d1
diff --git a/fastmcp_slim/fastmcp/tools/tool_transform.py b/fastmcp_slim/fastmcp/tools/tool_transform.py
index 9688da909..e11796dfc 100644
--- a/fastmcp_slim/fastmcp/tools/tool_transform.py
+++ b/fastmcp_slim/fastmcp/tools/tool_transform.py
@@ -5,7 +5,7 @@ from collections.abc import Callable
from contextvars import ContextVar
from copy import deepcopy
from dataclasses import dataclass
-from typing import Annotated, Any, Literal, cast
+from typing import Annotated, Any, Literal, LiteralString, cast
import mcp_types
from mcp_types import ToolAnnotations
@@ -14,7 +14,9 @@ from pydantic import ValidationError as PydanticValidationError
from pydantic.fields import Field
from pydantic.functional_validators import BeforeValidator
from pydantic.json_schema import SkipJsonSchema
+from pydantic_core import InitErrorDetails, PydanticCustomError
+from fastmcp.exceptions import ValidationError
from fastmcp.tools.base import (
InputRequiredToolResult,
Tool,
@@ -123,6 +125,29 @@ def _structural_kind(schema: dict[str, Any]) -> tuple[Any, ...]:
return ("type", schema_type)
+def _rename_error_locations(
+ exc: PydanticValidationError, old_to_new: dict[str, str]
+) -> PydanticValidationError:
+ """Rebuild a parent tool's validation error using the transformed argument names."""
+ line_errors: list[InitErrorDetails] = []
+ for error in exc.errors(include_url=False):
+ loc = error["loc"]
+ if loc and loc[0] in old_to_new:
+ loc = (old_to_new[loc[0]], *loc[1:])
+ # Custom errors: pydantic only rebuilds built-in error types by name.
+ line_errors.append(
+ {
+ "type": PydanticCustomError(
+ cast(LiteralString, error["type"]),
+ cast(LiteralString, error["msg"]),
+ ),
+ "loc": loc,
+ "input": error["input"],
+ }
+ )
+ return PydanticValidationError.from_exception_data(exc.title, line_errors)
+
+
# Context variable to store current transformed tool
_current_tool: ContextVar[TransformedTool | None] = ContextVar(
"_current_tool", default=None
@@ -840,6 +865,8 @@ class TransformedTool(Tool):
schema["$defs"] = parent_defs
schema = compress_schema(schema)
+ renamed_args = {old: new for new, old in new_to_old.items() if old != new}
+
# Create forwarding function that closes over everything it needs
async def _forward(**kwargs: Any):
# Validate arguments
@@ -874,7 +901,17 @@ class TransformedTool(Tool):
if callable(transform.default_factory):
parent_args[old_name] = transform.default_factory()
- return await parent_tool.run(parent_args)
+ try:
+ return await parent_tool.run(parent_args)
+ except ValidationError as exc:
+ # Report the parent's errors under this tool's argument names.
+ cause = exc.__cause__
+ if not renamed_args or not isinstance(cause, PydanticValidationError):
+ raise
+ renamed = _rename_error_locations(cause, renamed_args)
+ raise ValidationError(
+ str(renamed), log_level=exc.log_level
+ ) from renamed
return schema, _forward
diff --git a/tests/tools/tool_transform/test_args.py b/tests/tools/tool_transform/test_args.py
index bafe5b4cc..047ac655d 100644
--- a/tests/tools/tool_transform/test_args.py
+++ b/tests/tools/tool_transform/test_args.py
@@ -531,3 +531,69 @@ class TestEnableDisable:
with pytest.raises(ToolError):
await client.call_tool("new_add", {"x": 1, "y": 2})
+
+
+class SearchFilters(BaseModel):
+ limit: Annotated[int, Field(le=100)]
+
+
+def search(
+ q: str, n: Annotated[int, Field(le=10)] = 5, f: SearchFilters | None = None
+) -> str:
+ return q
+
+
+async def call_tool_error(tool: Tool, arguments: dict[str, Any]) -> str:
+ mcp = FastMCP()
+ mcp.add_tool(tool)
+ async with Client(mcp) as client:
+ result = await client.call_tool(tool.name, arguments, raise_on_error=False)
+ assert result.is_error
+ assert isinstance(result.content[0], TextContent)
+ return result.content[0].text
+
+
+class TestRenamedArgValidationErrors:
+ """Validation errors name the arguments the transformed tool exposes."""
+
+ @pytest.fixture
+ def find_tool(self) -> Tool:
+ return Tool.from_tool(
+ Tool.from_function(search),
+ name="find",
+ transform_args={
+ "q": ArgTransform(name="query"),
+ "n": ArgTransform(name="max_results"),
+ "f": ArgTransform(name="filters"),
+ },
+ )
+
+ @pytest.mark.parametrize(
+ ("arguments", "location"),
+ [
+ ({"query": "x", "max_results": 50}, "max_results"),
+ ({"query": "x", "filters": {"limit": 500}}, "filters.limit"),
+ ],
+ )
+ async def test_error_uses_renamed_arg(
+ self, find_tool: Tool, arguments: dict[str, Any], location: str
+ ):
+ error = await call_tool_error(find_tool, arguments)
+ assert error.splitlines()[1] == location
+
+ async def test_error_uses_outermost_name_when_chained(self, find_tool: Tool):
+ lookup_tool = Tool.from_tool(
+ find_tool,
+ name="lookup",
+ transform_args={"max_results": ArgTransform(name="limit")},
+ )
+ error = await call_tool_error(lookup_tool, {"query": "x", "limit": 50})
+ assert error.splitlines()[1] == "limit"
+
+ async def test_error_unchanged_without_renames(self):
+ search_tool = Tool.from_function(search)
+ find_tool = Tool.from_tool(search_tool, name="find")
+ arguments = {"q": "x", "n": 50}
+ assert await call_tool_error(find_tool, arguments) == await call_tool_error(
+ search_tool, arguments
+ )