Skip to content

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

fix(server): rebuild tool argument errors instead of echoing pydantic's (#6107)

JohnnyXu8fba5f7fcaa2
diff --git a/fastmcp_slim/fastmcp/server/server.py b/fastmcp_slim/fastmcp/server/server.py
index 569b72637..7d4632314 100644
--- a/fastmcp_slim/fastmcp/server/server.py
+++ b/fastmcp_slim/fastmcp/server/server.py
@@ -152,6 +152,31 @@ def _validation_error_summary(error: PydanticValidationError) -> dict[str, Any]:
return {"error_count": error.error_count(), "error_types": sorted(error_types)}
+def _validation_error_message(tool_name: str, error: PydanticValidationError) -> str:
+ """Client-facing summary: which argument failed and why, nothing else.
+
+ `str(PydanticValidationError)` embeds the exact pydantic version URL, the
+ internal adapter name (`call[<tool>]`), and every submitted value with its
+ inferred type. None of that helps a caller fix the call, and the first two
+ are version/internal-name disclosure, so the message is rebuilt from the
+ error details without the URL, context or inputs.
+ """
+ details = error.errors(
+ include_url=False, include_context=False, include_input=False
+ )
+ lines = [
+ (
+ f"Invalid arguments for tool {tool_name!r}:"
+ f" {len(details)} validation error{'s' if len(details) != 1 else ''}"
+ )
+ ]
+ for detail in details:
+ location = ".".join(str(part) for part in detail.get("loc", ()))
+ message = detail.get("msg", "Invalid value")
+ lines.append(f"- {location}: {message}" if location else f"- {message}")
+ return "\n".join(lines)
+
+
def _version_request_meta(
version: VersionSpec | None,
) -> mcp_types.RequestParamsMeta | None:
@@ -1622,8 +1647,16 @@ class FastMCP(
name,
_validation_error_summary(cause),
)
- else:
- logger.warning("Invalid arguments for tool %r", name)
+ # Re-raise a rebuilt message: the original carries the
+ # pydantic version URL and the adapter name into the
+ # tool result the caller reads. Chaining from the
+ # pydantic cause keeps the type and cause that
+ # middleware, CodeMode and parent servers rely on.
+ raise ValidationError(
+ _validation_error_message(name, cause),
+ log_level=logging.WARNING,
+ ) from cause
+ logger.warning("Invalid arguments for tool %r", name)
raise
except FastMCPError as e:
logger.log(
diff --git a/tests/server/providers/local_provider_tools/test_parameters.py b/tests/server/providers/local_provider_tools/test_parameters.py
index 13e5e060e..e8dbc2166 100644
--- a/tests/server/providers/local_provider_tools/test_parameters.py
+++ b/tests/server/providers/local_provider_tools/test_parameters.py
@@ -187,7 +187,7 @@ class TestToolParameters:
def analyze(x: int = Field()) -> None:
pass
- with pytest.raises(ValidationError, match="missing"):
+ with pytest.raises(ValidationError, match="x: Missing required argument"):
await mcp.call_tool("analyze", {})
async def test_literal_type_validation_error(self):
diff --git a/tests/server/test_input_validation.py b/tests/server/test_input_validation.py
index 97d5baff1..2035a1eb9 100644
--- a/tests/server/test_input_validation.py
+++ b/tests/server/test_input_validation.py
@@ -25,6 +25,7 @@ from pydantic import (
StrictInt,
field_validator,
)
+from pydantic import ValidationError as PydanticValidationError
from pydantic_core import PydanticCustomError
from fastmcp import Client, FastMCP
@@ -533,6 +534,65 @@ class TestEdgeCases:
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "6"
+ async def test_client_error_omits_pydantic_details(self):
+ """The caller gets the failing arguments, not the library internals."""
+ mcp = FastMCP("TestServer")
+
+ @mcp.tool
+ def echo(message: str) -> str:
+ return message
+
+ async with Client(mcp) as client:
+ result = await client.call_tool(
+ "echo", {"message": 123, "extra": "x"}, raise_on_error=False
+ )
+
+ assert result.is_error
+ text = result.content[0].text
+ assert text.startswith("Invalid arguments for tool 'echo'")
+ assert "- message: Input should be a valid string" in text
+ assert "- extra: Unexpected keyword argument" in text
+ for leaked in (
+ "errors.pydantic.dev",
+ "call[",
+ "input_value",
+ "input_type",
+ "2 validation errors for",
+ ):
+ assert leaked not in text, leaked
+
+ async def test_call_tool_raises_validation_error_with_rebuilt_message(self):
+ """Direct callers still get ValidationError, chained from pydantic."""
+ mcp = FastMCP("TestServer")
+
+ @mcp.tool
+ def echo(message: str) -> str:
+ return message
+
+ with pytest.raises(ValidationError) as exc_info:
+ await mcp.call_tool("echo", {"message": 123})
+
+ assert not isinstance(exc_info.value, ToolError)
+ assert isinstance(exc_info.value.__cause__, PydanticValidationError)
+ assert str(exc_info.value).startswith("Invalid arguments for tool 'echo'")
+ assert "errors.pydantic.dev" not in str(exc_info.value)
+
+ async def test_mounted_tool_error_names_parent_tool(self):
+ child = FastMCP("Child")
+
+ @child.tool
+ def echo(message: str) -> str:
+ return message
+
+ parent = FastMCP("Parent")
+ parent.mount(child, namespace="child")
+
+ with pytest.raises(ValidationError) as exc_info:
+ await parent.call_tool("child_echo", {"message": 123})
+
+ assert isinstance(exc_info.value.__cause__, PydanticValidationError)
+ assert str(exc_info.value).startswith("Invalid arguments for tool 'child_echo'")
+
class TestExpectedToolFailureLogging:
@pytest.mark.parametrize("mask_error_details", [False, True])
@@ -668,8 +728,15 @@ class TestExpectedToolFailureLogging:
)
assert result.is_error
- # The client still gets its detailed validation error.
- assert "PRIVATE" in str(result.content)
+ # The client learns which argument failed and why, but the message no
+ # longer carries pydantic's version URL, the internal adapter name, or
+ # the submitted values.
+ client_message = str(result.content)
+ assert "Invalid arguments for tool 'submit'" in client_message
+ assert "errors.pydantic.dev" not in client_message
+ assert "input_value" not in client_message
+ assert "input_type" not in client_message
+ assert "call[" not in client_message
records = [r for r in caplog.records if r.name == "fastmcp.server.server"]
assert len(records) == 1
assert "PRIVATE" not in records[0].getMessage()
diff --git a/tests/tools/tool_transform/test_args.py b/tests/tools/tool_transform/test_args.py
index 047ac655d..a916797f4 100644
--- a/tests/tools/tool_transform/test_args.py
+++ b/tests/tools/tool_transform/test_args.py
@@ -579,7 +579,7 @@ class TestRenamedArgValidationErrors:
self, find_tool: Tool, arguments: dict[str, Any], location: str
):
error = await call_tool_error(find_tool, arguments)
- assert error.splitlines()[1] == location
+ assert error.splitlines()[1].startswith(f"- {location}: ")
async def test_error_uses_outermost_name_when_chained(self, find_tool: Tool):
lookup_tool = Tool.from_tool(
@@ -588,12 +588,13 @@ class TestRenamedArgValidationErrors:
transform_args={"max_results": ArgTransform(name="limit")},
)
error = await call_tool_error(lookup_tool, {"query": "x", "limit": 50})
- assert error.splitlines()[1] == "limit"
+ assert error.splitlines()[1].startswith("- 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
- )
+ find_error = await call_tool_error(find_tool, arguments)
+ search_error = await call_tool_error(search_tool, arguments)
+ # The header names the called tool; the error details are identical.
+ assert find_error.splitlines()[1:] == search_error.splitlines()[1:]