π The fast, Pythonic way to build MCP servers and clients.
Reject undeclared OpenAPI tool arguments under strict input validation (#6140)
prassu0173642246a4c4c
diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdxindex 98c1203bc..1ec002dfb 100644--- a/docs/servers/tools.mdx+++ b/docs/servers/tools.mdx@@ -304,6 +304,7 @@ def add_numbers(a: int, b: int) -> int:| Lists with string elements (`["1", "2"]` for `list[int]`) | β Elements coerced | β Validation error || Pydantic model fields with type mismatches | β Fields coerced | β Validation error || Invalid values (`"abc"` for `int`) | β Validation error | β Validation error |+| Undeclared arguments to OpenAPI tools | β οΈ Dropped with a warning | β Validation error |<Note>**Note on Pydantic Models:** Even with `strict_input_validation=False`, Pydantic model parameters must be provided as JSON objects (dicts), not as stringified JSON. For example, `{"user": {"name": "Alice"}}` works, but `{"user": '{"name": "Alice"}'}` does not.diff --git a/fastmcp_slim/fastmcp/server/providers/openapi/components.py b/fastmcp_slim/fastmcp/server/providers/openapi/components.pyindex fb44f57a0..22a19e69a 100644--- a/fastmcp_slim/fastmcp/server/providers/openapi/components.py+++ b/fastmcp_slim/fastmcp/server/providers/openapi/components.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+import loggingimport refrom typing import TYPE_CHECKING, Any@@ -10,6 +11,7 @@ import httpx2from mcp_types import ToolAnnotationsfrom pydantic.networks import AnyUrl+from fastmcp.exceptions import ValidationErrorfrom fastmcp.resources import (Resource,ResourceContent,@@ -18,10 +20,11 @@ from fastmcp.resources import ()from fastmcp.server.dependencies import get_http_headersfrom fastmcp.tools.base import Tool, ToolResult+from fastmcp.tools.function_tool import _strict_input_validationfrom fastmcp.utilities.exceptions import is_request_error, is_timeout_errorfrom fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.openapi import HTTPRoute-from fastmcp.utilities.openapi.director import RequestDirector+from fastmcp.utilities.openapi.director import RequestDirector, _prepare_parameter_mapfrom fastmcp.utilities.tasks import TaskConfigif TYPE_CHECKING:@@ -221,6 +224,17 @@ class OpenAPITool(Tool):async def run(self, arguments: dict[str, Any]) -> ToolResult:"""Execute the HTTP request using RequestDirector."""+ # The director drops arguments outside its parameter map; strict+ # servers reject them instead, using the same key set.+ if _strict_input_validation():+ _, parameter_map = _prepare_parameter_map(self._route)+ accepted = {*self.parameters.get("properties", {}), *parameter_map}+ if unknown := sorted(arguments.keys() - accepted):+ raise ValidationError(+ f"Unknown arguments: {', '.join(unknown)}. "+ f"Accepted: {', '.join(sorted(accepted)) or 'none'}",+ log_level=logging.WARNING,+ )# Build the request β errors here are programming/schema issues,# not HTTP failures, so we catch them separately.try:diff --git a/tests/server/providers/openapi/test_undeclared_arguments.py b/tests/server/providers/openapi/test_undeclared_arguments.pyindex bf2946f83..d445cd8c6 100644--- a/tests/server/providers/openapi/test_undeclared_arguments.py+++ b/tests/server/providers/openapi/test_undeclared_arguments.py@@ -10,6 +10,7 @@ from jsonschema_path import SchemaPathfrom fastmcp import Client, FastMCPfrom fastmcp.client.transports import StreamableHttpTransportfrom fastmcp.exceptions import ToolError+from fastmcp.server.providers.openapi.components import OpenAPIToolfrom fastmcp.server.providers.openapi.routing import MCPType, RouteMapfrom fastmcp.utilities.openapi import director, parserfrom fastmcp.utilities.openapi.director import RequestDirector@@ -106,6 +107,27 @@ async def test_undeclared_arguments_are_ignored(assert request.content == b""+async def test_strict_input_validation_rejects_undeclared_arguments() -> None:+ schema = {"type": "object", "properties": {"name": {"type": "string"}}}+ request_body = {"content": {"application/json": {"schema": schema}}}+ spec = _spec("/agents", "post", {"requestBody": request_body})++ requests: list[httpx2.Request] = []+ async with _upstream_client(requests) as http_client:+ server = FastMCP.from_openapi(+ openapi_spec=spec, client=http_client, strict_input_validation=True+ )+ async with Client(server) as client:+ with pytest.raises(+ ToolError, match="Unknown arguments: usage_limits. Accepted: name"+ ):+ await client.call_tool(+ "operation", {"name": "agent", "usage_limits": {"requests": 5}}+ )++ assert requests == []++async def test_undeclared_arguments_are_ignored_after_schema_precalculation_fails(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -335,3 +357,37 @@ def test_manual_route_with_allof_body_sends_declared_properties() -> None:assert route.request_body.content_schema == {"application/json": {"allOf": [{"$ref": "#/components/schemas/Thing"}]}}+++async def test_strict_validation_accepts_suffix_on_manual_route() -> None:+ route = HTTPRoute(+ path="/users/{id}",+ method="GET",+ parameters=[+ ParameterInfo(+ name="id", location="path", required=True, schema={"type": "integer"}+ )+ ],+ )+ requests: list[httpx2.Request] = []+ async with _upstream_client(requests) as http_client:+ server = FastMCP(strict_input_validation=True)+ server.add_tool(+ OpenAPITool(+ client=http_client,+ route=route,+ director=RequestDirector(SchemaPath.from_dict({})),+ name="get_user",+ description="",+ parameters={+ "type": "object",+ "properties": {"id": {"type": "integer"}},+ },+ )+ )+ async with Client(server) as client:+ await client.call_tool("get_user", {"id__path": 123})+ with pytest.raises(ToolError, match="Unknown arguments: debug"):+ await client.call_tool("get_user", {"id": 1, "debug": True})++ assert [str(r.url) for r in requests] == [f"{BASE_URL}/users/123"]