Skip to content

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

Keep client data out of tool validation warnings (#5106)

nate nowack784ae75b2d2b
diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx
index 37bafb425..39b5e2649 100644
--- a/docs/servers/tools.mdx
+++ b/docs/servers/tools.mdx
@@ -812,7 +812,7 @@ For reusable serialization across multiple tools, create a wrapper decorator tha
If your tool encounters an error, you can raise a standard Python exception (`ValueError`, `TypeError`, `FileNotFoundError`, custom exceptions, etc.) or a FastMCP `ToolError`.
-By default, all exceptions (including their details) are logged and converted into an MCP error response to be sent back to the client LLM. This helps the LLM understand failures and react appropriately.
+By default, exceptions are converted into an MCP error response to be sent back to the client LLM. This helps the LLM understand failures and react appropriately. Validation warnings identify the tool and, for Pydantic errors, include the error count and built-in error types (such as `int_parsing`). Custom error codes are reported as `custom_error`. Argument values, validation locations, and validator messages are omitted because they may contain private client data. This does not change the validation details returned to the caller or redact explicit debug logging or custom middleware logs.
If you want to mask internal error details for security reasons, you can:
diff --git a/fastmcp_slim/fastmcp/server/server.py b/fastmcp_slim/fastmcp/server/server.py
index e71f953f4..6f999f69c 100644
--- a/fastmcp_slim/fastmcp/server/server.py
+++ b/fastmcp_slim/fastmcp/server/server.py
@@ -16,7 +16,16 @@ from contextlib import (
)
from functools import partial
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, cast, overload
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Generic,
+ Literal,
+ TypeVar,
+ cast,
+ get_args,
+ overload,
+)
import httpx2
import mcp_types
@@ -31,6 +40,7 @@ from mcp_types import (
from mcp_types.jsonrpc import MISSING_REQUIRED_CLIENT_CAPABILITY
from pydantic import AnyUrl
from pydantic import ValidationError as PydanticValidationError
+from pydantic_core import ErrorType
from starlette.routing import BaseRoute
from typing_extensions import Self
@@ -112,6 +122,21 @@ if TYPE_CHECKING:
logger = get_logger(__name__)
+_BUILTIN_VALIDATION_ERROR_TYPES = frozenset(get_args(ErrorType))
+
+
+def _validation_error_summary(error: PydanticValidationError) -> dict[str, Any]:
+ """Keep counts and built-in codes, never input-derived validation details."""
+ error_types = {
+ detail["type"]
+ if detail["type"] in _BUILTIN_VALIDATION_ERROR_TYPES
+ else "custom_error"
+ for detail in error.errors(
+ include_url=False, include_context=False, include_input=False
+ )
+ }
+ return {"error_count": error.error_count(), "error_types": sorted(error_types)}
+
def _version_request_meta(
version: VersionSpec | None,
@@ -1491,18 +1516,15 @@ class FastMCP(
try:
return await tool._run(arguments or {})
except ValidationError as e:
- # Argument-validation failure (a bad call). FunctionTool
- # converts pydantic's call-validation error into fastmcp's
- # ValidationError (see #4128) so it can be filtered as a
- # client error. Log the underlying detail without a URL or
- # traceback, matching the previous pydantic-error logging.
cause = e.__cause__
- detail = (
- cause.errors(include_url=False)
- if isinstance(cause, PydanticValidationError)
- else str(e)
- )
- logger.warning("Invalid arguments for tool %r: %s", name, detail)
+ if isinstance(cause, PydanticValidationError):
+ logger.warning(
+ "Invalid arguments for tool %r: %s",
+ name,
+ _validation_error_summary(cause),
+ )
+ else:
+ logger.warning("Invalid arguments for tool %r", name)
raise
except FastMCPError as e:
logger.log(
@@ -1516,7 +1538,7 @@ class FastMCP(
logger.warning(
"Invalid arguments for tool %r: %s",
name,
- e.errors(include_url=False),
+ _validation_error_summary(e),
)
raise
except Exception as e:
diff --git a/tests/server/test_input_validation.py b/tests/server/test_input_validation.py
index 777574d47..44fdf5f61 100644
--- a/tests/server/test_input_validation.py
+++ b/tests/server/test_input_validation.py
@@ -7,13 +7,17 @@ strict_input_validation=False, the default).
"""
import json
+from typing import Any
import pytest
+from mcp.shared.exceptions import MCPError
from mcp_types import TextContent
-from pydantic import BaseModel
+from pydantic import BaseModel, ConfigDict, Field, field_validator
+from pydantic_core import PydanticCustomError
from fastmcp import Client, FastMCP
-from fastmcp.exceptions import ToolError
+from fastmcp.exceptions import ToolError, ValidationError
+from fastmcp.tools.base import Tool, ToolResult
class UserProfile(BaseModel):
@@ -24,6 +28,27 @@ class UserProfile(BaseModel):
email: str
+class PrivatePayload(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ token: str
+ values: dict[str, int] = Field(default_factory=dict)
+
+ @field_validator("token")
+ @classmethod
+ def reject_private_token(cls, value: str) -> str:
+ # Simulate a validator that includes the rejected input in its message.
+ if value != "ok":
+ raise ValueError(f"Rejected token: {value}")
+ return value
+
+
+class RawValidationTool(Tool):
+ async def run(self, arguments: dict[str, Any]) -> ToolResult:
+ PrivatePayload.model_validate(arguments)
+ return ToolResult(content="ok")
+
+
class TestStringToIntegerCoercion:
"""Test string-to-integer coercion behavior."""
@@ -374,8 +399,134 @@ class TestExpectedToolFailureLogging:
assert records[0].levelname == "WARNING"
assert records[0].exc_info is None
assert "int_parsing" in records[0].getMessage()
+ assert "'error_count': 1" in records[0].getMessage()
assert "errors.pydantic.dev" not in records[0].getMessage()
+ @pytest.mark.parametrize(
+ "arguments, error_type",
+ [
+ ({"note": "PRIVATE_VALUE"}, "missing_argument"),
+ ({"payload": ["PRIVATE_VALUE"]}, "model_type"),
+ (
+ {"payload": {"token": "ok"}, "PRIVATE_KEY": 1},
+ "unexpected_keyword_argument",
+ ),
+ ({"payload": {"token": "ok", "PRIVATE_KEY": 1}}, "extra_forbidden"),
+ (
+ {"payload": {"token": "ok", "values": {"PRIVATE_KEY": "bad"}}},
+ "int_parsing",
+ ),
+ ({"payload": {"token": "PRIVATE_TOKEN"}}, "value_error"),
+ ],
+ ids=[
+ "missing",
+ "wrong-type",
+ "extra",
+ "nested-extra",
+ "dict-key",
+ "validator-message",
+ ],
+ )
+ async def test_validation_logs_omit_client_data(
+ self, caplog, arguments, error_type
+ ):
+ mcp = FastMCP("TestServer")
+
+ @mcp.tool
+ def submit(payload: PrivatePayload, note: str = "") -> str:
+ return "ok"
+
+ with caplog.at_level("WARNING", logger="fastmcp.server.server"):
+ async with Client(mcp) as client:
+ result = await client.call_tool(
+ "submit", arguments, raise_on_error=False
+ )
+
+ assert result.is_error
+ # The client still gets its detailed validation error.
+ assert "PRIVATE" in str(result.content)
+ records = [r for r in caplog.records if r.name == "fastmcp.server.server"]
+ assert len(records) == 1
+ assert "PRIVATE" not in records[0].getMessage()
+ assert error_type in records[0].getMessage()
+ assert "'error_count': 1" in records[0].getMessage()
+ assert records[0].exc_info is None
+
+ @pytest.mark.parametrize("raw_pydantic", [False, True])
+ async def test_other_validation_logs_omit_client_data(self, caplog, raw_pydantic):
+ mcp = FastMCP("TestServer")
+ if raw_pydantic:
+ mcp.add_tool(
+ RawValidationTool(name="submit", parameters={"type": "object"})
+ )
+ arguments = {"token": "PRIVATE_TOKEN"}
+ else:
+
+ @mcp.tool
+ def submit() -> str:
+ raise ValidationError("PRIVATE_CUSTOM_ERROR")
+
+ arguments = {}
+
+ with caplog.at_level("WARNING", logger="fastmcp.server.server"):
+ async with Client(mcp) as client:
+ if raw_pydantic:
+ with pytest.raises(MCPError, match="Invalid request parameters"):
+ await client.call_tool(
+ "submit", arguments, raise_on_error=False
+ )
+ else:
+ result = await client.call_tool(
+ "submit", arguments, raise_on_error=False
+ )
+ assert result.is_error
+ assert "PRIVATE" in str(result.content)
+
+ records = [r for r in caplog.records if r.name == "fastmcp.server.server"]
+ assert len(records) == 1
+ assert "PRIVATE" not in records[0].getMessage()
+ if raw_pydantic:
+ assert "value_error" in records[0].getMessage()
+ else:
+ assert records[0].getMessage() == "Invalid arguments for tool 'submit'"
+ assert records[0].exc_info is None
+
+ async def test_custom_error_codes_are_not_logged(self, caplog):
+ class Payload(BaseModel):
+ values: list[str]
+
+ @field_validator("values")
+ @classmethod
+ def reject_values(cls, values: list[str]) -> list[str]:
+ # Runtime validators can use input-derived codes despite the type hint.
+ raise PydanticCustomError(
+ values[0], # ty: ignore[invalid-argument-type]
+ "Rejected {value}",
+ {"value": values},
+ )
+
+ mcp = FastMCP("TestServer")
+
+ @mcp.tool
+ def submit(payload: Payload, count: int) -> str:
+ return "ok"
+
+ async with Client(mcp) as client:
+ result = await client.call_tool(
+ "submit",
+ {"payload": {"values": ["PRIVATE_CODE"]}, "count": "PRIVATE_VALUE"},
+ raise_on_error=False,
+ )
+ assert result.is_error
+ assert "PRIVATE" in str(result.content)
+ records = [r for r in caplog.records if r.name == "fastmcp.server.server"]
+ assert len(records) == 1
+ assert "PRIVATE" not in records[0].getMessage()
+ assert "'error_count': 2" in records[0].getMessage()
+ assert "custom_error" in records[0].getMessage()
+ assert "int_parsing" in records[0].getMessage()
+ assert records[0].exc_info is None
+
async def test_tool_raised_tool_error_logs_without_traceback(self, caplog):
mcp = FastMCP("TestServer")