π The fast, Pythonic way to build MCP servers and clients.
Preserve field-level strict validation in lax mode (#5141)
nate nowack053f1289191c
diff --git a/fastmcp_slim/fastmcp/tools/function_tool.py b/fastmcp_slim/fastmcp/tools/function_tool.pyindex b166cead7..1398eabf9 100644--- a/fastmcp_slim/fastmcp/tools/function_tool.py+++ b/fastmcp_slim/fastmcp/tools/function_tool.py@@ -121,19 +121,21 @@ def _wrap_body_errors(fn: Callable[..., Any]) -> Callable[..., Any]:return wrapper-def _strict_input_validation() -> bool:- """Whether the running server enforces strict argument validation.+def _strict_input_validation() -> Literal[True] | None:+ """The ``strict`` value to pass to pydantic for the running server.Reads ``strict_input_validation`` off the active request's ``FastMCP``- instance. Returns ``False`` outside a request context (e.g. a tool invoked- directly in tests), preserving the default coercing behavior.+ instance. Returns ``None`` when the server is lax or outside a request+ context (e.g. a tool invoked directly in tests): pydantic then keeps any+ strictness declared on the parameters themselves, whereas an explicit+ ``False`` would override it."""from fastmcp.server.context import _current_contextcontext = _current_context.get(None)- if context is None:- return False- return context.fastmcp.strict_input_validation+ if context is None or not context.fastmcp.strict_input_validation:+ return None+ return TrueF = TypeVar("F", bound=Callable[..., Any])@@ -406,7 +408,7 @@ class FunctionTool(Tool):exec_is_async: bool,arguments: dict[str, Any],*,- strict: bool,+ strict: bool | None,) -> Any:"""Validate arguments and execute the body, applying any timeout."""try:@@ -453,7 +455,7 @@ class FunctionTool(Tool):exec_is_async: bool,arguments: dict[str, Any],*,- strict: bool = False,+ strict: bool | None = None,) -> Any:"""Validate arguments and execute the tool body.diff --git a/fastmcp_tasks/fastmcp_tasks/components.py b/fastmcp_tasks/fastmcp_tasks/components.pyindex e1aae8df1..dac63271b 100644--- a/fastmcp_tasks/fastmcp_tasks/components.py+++ b/fastmcp_tasks/fastmcp_tasks/components.py@@ -144,7 +144,7 @@ def coerce_task_arguments(component: FastMCPComponent,arguments: dict[str, Any],*,- strict: bool = False,+ strict: bool | None = None,) -> dict[str, Any]:"""Validate and coerce task arguments before any task state is created.diff --git a/tests/server/test_input_validation.py b/tests/server/test_input_validation.pyindex 44fdf5f61..abe1fbc90 100644--- a/tests/server/test_input_validation.py+++ b/tests/server/test_input_validation.py@@ -7,12 +7,12 @@ strict_input_validation=False, the default)."""import json-from typing import Any+from typing import Annotated, Anyimport pytestfrom mcp.shared.exceptions import MCPErrorfrom mcp_types import TextContent-from pydantic import BaseModel, ConfigDict, Field, field_validator+from pydantic import BaseModel, ConfigDict, Field, StrictInt, field_validatorfrom pydantic_core import PydanticCustomErrorfrom fastmcp import Client, FastMCP@@ -227,6 +227,62 @@ class TestPydanticModelArguments:)+class TestFieldLevelStrictness:+ """Strictness declared on the parameter itself must survive lax server mode."""++ async def test_strict_field_rejects_coercion(self):+ mcp = FastMCP("TestServer")++ @mcp.tool+ def echo(value: Annotated[int, Field(strict=True)]) -> int:+ return value++ async with Client(mcp) as client:+ with pytest.raises(ToolError):+ await client.call_tool("echo", {"value": "5"})+ result = await client.call_tool("echo", {"value": 5})+ assert isinstance(result.content[0], TextContent)+ assert result.content[0].text == "5"++ async def test_strict_type_rejects_coercion(self):+ mcp = FastMCP("TestServer")++ @mcp.tool+ def echo(value: StrictInt) -> int:+ return value++ async with Client(mcp) as client:+ with pytest.raises(ToolError):+ await client.call_tool("echo", {"value": 5.0})++ async def test_strict_model_config_rejects_coercion(self):+ class Payload(BaseModel):+ model_config = ConfigDict(strict=True)+ count: int++ mcp = FastMCP("TestServer")++ @mcp.tool+ def echo(payload: Payload) -> int:+ return payload.count++ async with Client(mcp) as client:+ with pytest.raises(ToolError):+ await client.call_tool("echo", {"payload": {"count": "5"}})++ async def test_lax_fields_still_coerce(self):+ mcp = FastMCP("TestServer")++ @mcp.tool+ def echo(value: int) -> int:+ return value++ async with Client(mcp) as client:+ result = await client.call_tool("echo", {"value": "5"})+ assert isinstance(result.content[0], TextContent)+ assert result.content[0].text == "5"++class TestValidationErrorMessages:"""Test the quality of validation error messages."""diff --git a/tests/tasks/server/test_task_tools.py b/tests/tasks/server/test_task_tools.pyindex 0f7ed3c09..5aa2966b2 100644--- a/tests/tasks/server/test_task_tools.py+++ b/tests/tasks/server/test_task_tools.py@@ -12,11 +12,11 @@ from __future__ import annotationsimport asyncioimport functools-from typing import Any+from typing import Annotated, Anyimport pytestfrom fastmcp_tasks.models import CreateTaskResult-from pydantic import BaseModel+from pydantic import BaseModel, Fieldimport fastmcp.tools.function_tool as function_toolfrom fastmcp import FastMCP@@ -145,6 +145,24 @@ async def test_valid_argument_submits_under_strict_validation():assert final.result["structuredContent"] == {"result": 16}+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")+ mcp.add_extension(TasksExtension())++ @mcp.tool(task=True)+ async def square(n: Annotated[int, Field(strict=True)]) -> int:+ return n * n++ async with running_task_server(mcp):+ with pytest.raises(ValidationError):+ await submit_task(mcp, "square", {"n": "1"})+ final = await run_task(mcp, "square", {"n": 3})+ assert final.status == "completed"+ assert final.result is not None+ assert final.result["structuredContent"] == {"result": 9}++def test_resolve_param_hints_handles_partials(monkeypatch: pytest.MonkeyPatch):"""Resolve partials via their function when direct introspection is empty.