Skip to content

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

Fix tool body validation errors at the MCP boundary (#5485)

Qingsong Li2dd1c319c632
diff --git a/fastmcp_slim/fastmcp/tools/function_tool.py b/fastmcp_slim/fastmcp/tools/function_tool.py
index 630c89021..b9f642c42 100644
--- a/fastmcp_slim/fastmcp/tools/function_tool.py
+++ b/fastmcp_slim/fastmcp/tools/function_tool.py
@@ -62,7 +62,9 @@ class _ToolBodyError(Exception):
an argument-validation failure (a bad call). Errors a tool raises from its
own body β€” e.g. constructing a model from upstream data β€” are a different
class of problem (a server-side bug) that must not be reclassified as a bad
- call. We wrap the body so those are tagged and can be told apart. See #4128.
+ call. We wrap the body so those are tagged and can be told apart. The tagged
+ error propagates out of the tool like any other body exception, so
+ `FastMCP.call_tool` masks, logs, and converts it to a `ToolError`. See #4128.
"""
@@ -86,7 +88,7 @@ def _wrap_body_errors(
try:
return await fn(*args, **kwargs)
except PydanticValidationError as e:
- raise _ToolBodyError from e
+ raise _ToolBodyError(str(e)) from e
else:
def wrapper(*args: Any, **kwargs: Any) -> Any:
@@ -96,7 +98,7 @@ def _wrap_body_errors(
return list(result)
return result
except PydanticValidationError as e:
- raise _ToolBodyError from e
+ raise _ToolBodyError(str(e)) from e
# Mirror the original callable so TypeAdapter builds the identical schema and
# binds arguments the same way. Annotations must cover every signature
@@ -486,13 +488,6 @@ class FunctionTool(Tool):
# downstream error taxonomy (e.g. Sentry filters) can treat it as a
# client error rather than a server bug.
raise ValidationError(str(e), log_level=logging.WARNING) from e
- except _ToolBodyError as e:
- # The tool's own body raised a pydantic ValidationError. Surface the
- # original so it is treated as a server-side error, hiding the
- # internal sentinel while preserving the error's own chained cause.
- original = e.__cause__
- assert original is not None
- raise original from original.__cause__
return result
@@ -538,7 +533,7 @@ class FunctionTool(Tool):
except PydanticValidationError as e:
# A pydantic error from awaiting the result or materializing a
# generator is body execution, not argument validation.
- raise _ToolBodyError from e
+ raise _ToolBodyError(str(e)) from e
@staticmethod
async def _materialize_generator(result: Any) -> Any:
diff --git a/tests/apps/test_form.py b/tests/apps/test_form.py
index 6610396b8..763874b74 100644
--- a/tests/apps/test_form.py
+++ b/tests/apps/test_form.py
@@ -11,6 +11,7 @@ from fastmcp.apps.form import (
FormInput,
_backfill_boolean_defaults,
)
+from fastmcp.exceptions import ToolError
from fastmcp.server.providers.addressing import hashed_backend_name
@@ -126,7 +127,7 @@ class TestFormInputProvider:
# Should reach model validation (not crash with "missing required argument"
# for the data parameter itself). Pydantic will still reject missing
# required fields like title/content, but that's expected.
- with pytest.raises(pydantic.ValidationError, match="title"):
+ with pytest.raises(ToolError, match="title"):
await server.call_tool(hashed_backend_name("NoteForm", "submit_form"), {})
async def test_multiple_models(self):
diff --git a/tests/server/test_generator_dependency_lifetime.py b/tests/server/test_generator_dependency_lifetime.py
index b4a6038de..5d6a038a9 100644
--- a/tests/server/test_generator_dependency_lifetime.py
+++ b/tests/server/test_generator_dependency_lifetime.py
@@ -7,13 +7,12 @@ from contextlib import asynccontextmanager
import pytest
from pydantic import BaseModel
-from pydantic import ValidationError as PydanticValidationError
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.dependencies import Depends
from fastmcp.exceptions import ValidationError
-from fastmcp.tools.function_tool import FunctionTool
+from fastmcp.tools.function_tool import FunctionTool, _ToolBodyError
@pytest.mark.parametrize("run_in_thread", [False, True])
@@ -108,7 +107,7 @@ async def test_generator_failure_closes_dependency_after_generator(failure: str)
with pytest.raises(asyncio.CancelledError):
await task
else:
- error = RuntimeError if failure == "exception" else PydanticValidationError
+ error = RuntimeError if failure == "exception" else _ToolBodyError
with pytest.raises(error):
await tool.run({})
assert events == ["enter", "body", "generator-finally", "exit"]
diff --git a/tests/server/test_input_validation.py b/tests/server/test_input_validation.py
index ce2b81ad8..97d5baff1 100644
--- a/tests/server/test_input_validation.py
+++ b/tests/server/test_input_validation.py
@@ -29,7 +29,10 @@ from pydantic_core import PydanticCustomError
from fastmcp import Client, FastMCP
from fastmcp.exceptions import ToolError, ValidationError
+from fastmcp.server.middleware import Middleware
+from fastmcp.server.transforms import ToolTransform
from fastmcp.tools.base import Tool, ToolResult
+from fastmcp.tools.tool_transform import ToolTransformConfig
class UserProfile(BaseModel):
@@ -532,6 +535,73 @@ class TestEdgeCases:
class TestExpectedToolFailureLogging:
+ @pytest.mark.parametrize("mask_error_details", [False, True])
+ @pytest.mark.parametrize(
+ "tool_path", ["direct", "transformed", "mounted", "middleware"]
+ )
+ async def test_tool_body_validation_error_returns_error_result(
+ self, mask_error_details: bool, tool_path: str, caplog
+ ):
+ class StoredRecord(BaseModel):
+ content: str
+
+ mcp = FastMCP("TestServer", mask_error_details=mask_error_details)
+
+ @mcp.tool
+ def load_record(record: dict[str, Any]) -> str:
+ return StoredRecord.model_validate(record).content
+
+ tool_name = "load_record"
+ server = mcp
+ if tool_path == "transformed":
+ mcp.add_transform(
+ ToolTransform(
+ {"load_record": ToolTransformConfig(name="load_transformed")}
+ )
+ )
+ tool_name = "load_transformed"
+ elif tool_path == "mounted":
+ server = FastMCP("Parent", mask_error_details=mask_error_details)
+ server.mount(mcp, namespace="child")
+ tool_name = "child_load_record"
+ elif tool_path == "middleware":
+
+ class Reroute(Middleware):
+ async def on_call_tool(self, context, call_next):
+ if context.message.name == "outer":
+ return await context.fastmcp_context.fastmcp.call_tool(
+ "load_record", {"record": {}}
+ )
+ return await call_next(context)
+
+ @mcp.tool
+ def outer() -> str:
+ return "not reached"
+
+ mcp.add_middleware(Reroute())
+ tool_name = "outer"
+
+ with caplog.at_level("DEBUG"):
+ async with Client(server) as client:
+ result = await client.call_tool(
+ tool_name, {"record": {}}, raise_on_error=False
+ )
+
+ assert result.is_error
+ assert ("content" in str(result.content)) is not mask_error_details
+ assert not any(
+ "Invalid arguments for tool" in record.getMessage()
+ for record in caplog.records
+ )
+ error_records = [
+ record
+ for record in caplog.records
+ if record.levelname == "ERROR"
+ and record.getMessage().startswith("Error calling tool")
+ and record.exc_info
+ ]
+ assert len(error_records) == 1
+
async def test_validation_error_logs_warning_without_traceback(self, caplog):
mcp = FastMCP("TestServer", strict_input_validation=False)
diff --git a/tests/tools/tool/test_argument_validation.py b/tests/tools/tool/test_argument_validation.py
index a526eae3f..105f0609e 100644
--- a/tests/tools/tool/test_argument_validation.py
+++ b/tests/tools/tool/test_argument_validation.py
@@ -4,7 +4,7 @@ See https://github.com/PrefectHQ/fastmcp/issues/4128: a bad call (invalid
arguments) should surface as fastmcp's ``ValidationError`` so downstream error
taxonomy (middleware, Sentry filters) can treat it as a client error, while a
``pydantic.ValidationError`` raised by the tool's own body is a server-side bug
-and must propagate unchanged.
+and must not be reclassified as a bad call.
"""
from typing import Annotated, Any
@@ -15,6 +15,7 @@ from pydantic import ValidationError as PydanticValidationError
from fastmcp.exceptions import ValidationError
from fastmcp.tools.base import Tool
+from fastmcp.tools.function_tool import _ToolBodyError
class _Inner(BaseModel):
@@ -67,12 +68,11 @@ class TestToolBodyErrors:
return 1
tool = Tool.from_function(tool_fn)
- with pytest.raises(PydanticValidationError):
- await tool.run({"data": "valid"})
- # And it must not be fastmcp's ValidationError.
- with pytest.raises(PydanticValidationError) as exc_info:
+ with pytest.raises(_ToolBodyError) as exc_info:
await tool.run({"data": "valid"})
+ # It must not be fastmcp's ValidationError, and the original is chained.
assert not isinstance(exc_info.value, ValidationError)
+ assert isinstance(exc_info.value.__cause__, PydanticValidationError)
async def test_sync_body_pydantic_error_propagates(self):
def tool_fn(data: str) -> int:
@@ -81,8 +81,9 @@ class TestToolBodyErrors:
return 1
tool = Tool.from_function(tool_fn)
- with pytest.raises(PydanticValidationError):
+ with pytest.raises(_ToolBodyError) as exc_info:
await tool.run({"data": "valid"})
+ assert isinstance(exc_info.value.__cause__, PydanticValidationError)
class TestTaskArgumentValidation: