Skip to content

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

Validate strict tool input in JSON mode (#5504)

Asem ahmed8d993b83e95b
diff --git a/fastmcp_slim/fastmcp/tools/function_tool.py b/fastmcp_slim/fastmcp/tools/function_tool.py
index 39aaf2bf9..630c89021 100644
--- a/fastmcp_slim/fastmcp/tools/function_tool.py
+++ b/fastmcp_slim/fastmcp/tools/function_tool.py
@@ -28,6 +28,7 @@ from mcp_types import Icon, ToolAnnotations
from pydantic import Field, TypeAdapter
from pydantic import ValidationError as PydanticValidationError
from pydantic.json_schema import SkipJsonSchema
+from pydantic_core import to_json
from fastmcp.decorators import get_fastmcp_meta
from fastmcp.exceptions import ValidationError
@@ -145,6 +146,38 @@ def _strict_input_validation() -> Literal[True] | None:
return True
+def _is_json_data(value: Any) -> bool:
+ """Whether *value* is built only from types a JSON parser produces."""
+ if value is None or isinstance(value, (str, int, float)):
+ return True
+ if isinstance(value, list):
+ return all(_is_json_data(item) for item in value)
+ if isinstance(value, dict):
+ return all(
+ isinstance(key, str) and _is_json_data(item) for key, item in value.items()
+ )
+ return False
+
+
+def _validate_input(
+ type_adapter: TypeAdapter[Any], value: Any, *, strict: bool | None
+) -> Any:
+ """Validate tool input with *type_adapter*, honoring ``strict``.
+
+ Tool arguments are JSON, but pydantic's strict mode on Python input only
+ accepts already-built objects: an enum member, a ``datetime``, a ``UUID``, a
+ dataclass instance, a ``tuple`` or ``set``. Their JSON spellings, which the
+ input schema tells clients to send, would never validate. Strict validation
+ of JSON data therefore runs in JSON mode, which still rejects lax coercions
+ such as the string ``"10"`` for an ``int``. Python objects passed by an
+ in-process caller are validated as Python, since serializing them can lose
+ information (a ``SecretStr`` serializes masked).
+ """
+ if not strict or not _is_json_data(value):
+ return type_adapter.validate_python(value, strict=strict)
+ return type_adapter.validate_json(to_json(value), strict=True)
+
+
F = TypeVar("F", bound=Callable[..., Any])
@@ -487,14 +520,14 @@ class FunctionTool(Tool):
# needs to handle async and threadpool-sync under a timeout.
if exec_is_async:
# Argument validation is synchronous; the body runs on await below.
- result = type_adapter.validate_python(arguments, strict=strict)
+ result = _validate_input(type_adapter, arguments, strict=strict)
elif self.run_in_thread:
# Sync function: run in threadpool to avoid blocking the event loop.
result = await call_sync_fn_in_threadpool(
- type_adapter.validate_python, arguments, strict=strict
+ _validate_input, type_adapter, arguments, strict=strict
)
else:
- result = type_adapter.validate_python(arguments, strict=strict)
+ result = _validate_input(type_adapter, arguments, strict=strict)
try:
if inspect.isawaitable(result):
diff --git a/fastmcp_tasks/fastmcp_tasks/components.py b/fastmcp_tasks/fastmcp_tasks/components.py
index dac63271b..2e9dec039 100644
--- a/fastmcp_tasks/fastmcp_tasks/components.py
+++ b/fastmcp_tasks/fastmcp_tasks/components.py
@@ -34,7 +34,11 @@ from fastmcp.resources.base import Resource
from fastmcp.resources.function_resource import FunctionResource
from fastmcp.resources.template import FunctionResourceTemplate, ResourceTemplate
from fastmcp.tools.base import Tool
-from fastmcp.tools.function_tool import FunctionTool, _resolve_param_hints
+from fastmcp.tools.function_tool import (
+ FunctionTool,
+ _resolve_param_hints,
+ _validate_input,
+)
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.types import get_cached_typeadapter
from fastmcp_tasks.input_loop import reentrant_task_fn
@@ -176,7 +180,7 @@ def coerce_task_arguments(
continue
adapter = get_cached_typeadapter(annotation)
try:
- coerced[name] = adapter.validate_python(value, strict=strict)
+ coerced[name] = _validate_input(adapter, value, strict=strict)
except PydanticValidationError as e:
raise ValidationError(str(e), log_level=logging.WARNING) from e
return coerced
diff --git a/tests/server/test_input_validation.py b/tests/server/test_input_validation.py
index a13fc59f7..ce2b81ad8 100644
--- a/tests/server/test_input_validation.py
+++ b/tests/server/test_input_validation.py
@@ -6,14 +6,25 @@ strict_input_validation=True) and Pydantic-based coercion (when
strict_input_validation=False, the default).
"""
+import datetime
+import enum
import json
+import uuid
+from dataclasses import dataclass
from typing import Annotated, Any
import httpx2
import pytest
from mcp.shared.exceptions import MCPError
from mcp_types import TextContent
-from pydantic import BaseModel, ConfigDict, Field, StrictInt, field_validator
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SecretStr,
+ StrictInt,
+ field_validator,
+)
from pydantic_core import PydanticCustomError
from fastmcp import Client, FastMCP
@@ -228,6 +239,93 @@ class TestPydanticModelArguments:
)
+class Color(enum.Enum):
+ RED = "red"
+
+
+@dataclass
+class Point:
+ x: int
+
+
+class TestStrictModeAcceptsJsonValues:
+ """Strict mode rejects lax coercion, not the JSON form of a declared type."""
+
+ @pytest.mark.parametrize(
+ ("annotation", "value", "expected"),
+ [
+ (Color, "red", Color.RED),
+ (datetime.datetime, "2026-01-01T00:00:00", datetime.datetime(2026, 1, 1)),
+ (datetime.date, "2026-01-01", datetime.date(2026, 1, 1)),
+ (
+ uuid.UUID,
+ "12345678-1234-5678-1234-567812345678",
+ uuid.UUID("12345678-1234-5678-1234-567812345678"),
+ ),
+ (Point, {"x": 1}, Point(x=1)),
+ (tuple[int, int], [1, 2], (1, 2)),
+ (set[int], [1], {1}),
+ (float, 1, 1.0),
+ ],
+ )
+ async def test_json_value_is_accepted(self, annotation, value, expected):
+ mcp = FastMCP("TestServer", strict_input_validation=True)
+ received = []
+
+ async def tool_fn(arg):
+ received.append(arg)
+ return "ok"
+
+ tool_fn.__annotations__["arg"] = annotation
+ mcp.tool(tool_fn, name="check")
+
+ async with Client(mcp) as client:
+ await client.call_tool("check", {"arg": value})
+
+ assert received == [expected]
+
+ async def test_lax_coercion_is_still_rejected(self):
+ mcp = FastMCP("TestServer", strict_input_validation=True)
+
+ @mcp.tool
+ def check(when: datetime.datetime, count: int) -> str:
+ return "ok"
+
+ async with Client(mcp) as client:
+ with pytest.raises(ToolError):
+ await client.call_tool(
+ "check", {"when": "2026-01-01T00:00:00", "count": "1"}
+ )
+ with pytest.raises(ToolError):
+ await client.call_tool("check", {"when": 1, "count": 1})
+
+ async def test_python_objects_are_accepted_when_called_directly(self):
+ mcp = FastMCP("TestServer", strict_input_validation=True)
+
+ @mcp.tool
+ def check(color: Color, when: datetime.datetime) -> str:
+ return f"{color.value} {when.year}"
+
+ result = await mcp.call_tool(
+ "check", {"color": Color.RED, "when": datetime.datetime(2026, 1, 1)}
+ )
+
+ assert isinstance(result.content[0], TextContent)
+ assert result.content[0].text == "red 2026"
+
+ async def test_python_objects_are_not_round_tripped_through_json(self):
+ mcp = FastMCP("TestServer", strict_input_validation=True)
+
+ @mcp.tool
+ def reveal(secret: SecretStr) -> str:
+ return secret.get_secret_value()
+
+ result = await mcp.call_tool("reveal", {"secret": SecretStr("s3cret")})
+
+ assert isinstance(result.content[0], TextContent)
+ assert result.content[0].text == "s3cret"
+
+
class TestFieldLevelStrictness:
"""Strictness declared on the parameter itself must survive lax server mode."""
diff --git a/tests/tasks/server/test_task_tools.py b/tests/tasks/server/test_task_tools.py
index 5aa2966b2..2dd166090 100644
--- a/tests/tasks/server/test_task_tools.py
+++ b/tests/tasks/server/test_task_tools.py
@@ -11,6 +11,8 @@ no client task-submission API until Phase 4.
from __future__ import annotations
import asyncio
+import datetime
+import enum
import functools
from typing import Annotated, Any
@@ -35,6 +37,10 @@ from tests.tasks.task_helpers import (
)
+class _Color(enum.Enum):
+ RED = "red"
+
+
class _Item(BaseModel):
value: str
@@ -145,6 +151,24 @@ async def test_valid_argument_submits_under_strict_validation():
assert final.result["structuredContent"] == {"result": 16}
+async def test_task_submission_accepts_json_values_under_strict_validation():
+ """Strict validation accepts the JSON form of an enum or datetime on the task path."""
+ mcp = FastMCP("strict-task-json-server", strict_input_validation=True)
+ mcp.add_extension(TasksExtension())
+
+ @mcp.tool(task=True)
+ async def describe(color: _Color, when: datetime.datetime) -> str:
+ return f"{color.value} {when.year}"
+
+ async with running_task_server(mcp):
+ final = await run_task(
+ mcp, "describe", {"color": "red", "when": "2026-01-01T00:00:00"}
+ )
+ assert final.status == "completed"
+ assert final.result is not None
+ assert final.result["structuredContent"] == {"result": "red 2026"}
+
+
async def test_task_submission_honors_field_level_strictness():
"""A lax server still rejects coercion the parameter itself declared strict."""
mcp = FastMCP("field-strict-task-server")