Skip to content

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

fix(openapi): preserve HTTP parameters that match whole-body names (#5113)

astse0129eaa6fb3
diff --git a/docs/integrations/openapi.mdx b/docs/integrations/openapi.mdx
index 33aa608fe..49857ea2f 100644
--- a/docs/integrations/openapi.mdx
+++ b/docs/integrations/openapi.mdx
@@ -458,6 +458,8 @@ Header parameters are automatically converted to strings and included in the HTT
Dictionary bodies without named properties use one tool argument containing the entire dictionary. For a dictionary schema titled `Labels`, calling the tool with `{"labels": {"team": "infra"}}` sends `{"team": "infra"}` to the API. Schemas without a title use the argument name `body`.
+If a whole-body argument shares a name with a path, query, header, or cookie parameter, the HTTP parameter receives a location suffix. For example, an array body titled `Values` and a query parameter named `values` become `values` and `values__query`; calling with `{"values": [1, 2], "values__query": "active"}` sends `[1, 2]` as the body and `?values=active` in the URL.
+
For request bodies declared as `application/json` or a `+json` media type, pass strings, numbers, and booleans as their actual values. FastMCP JSON-encodes them and preserves the declared Content-Type, including media-type parameters. Do not JSON-encode a string yourself: passing `"true"` sends the JSON string `"true"`, while passing `True` sends the JSON boolean `true`.
Earlier versions sent string bodies as raw text even when the schema declared JSON. If you worked around that behavior by pre-encoding a string, remove the extra encoding. Bodies declared as `text/plain` continue to be sent as raw text.
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py b/fastmcp_slim/fastmcp/utilities/openapi/schemas.py
index c8fe95b9b..872bd10b0 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/schemas.py
@@ -1,5 +1,6 @@
"""Schema manipulation utilities for OpenAPI operations."""
+import re
from collections import Counter
from typing import Any
@@ -461,6 +462,17 @@ def _combine_schemas_and_map_params(
all_non_body_params.update(location_params)
body_param_names = set(body_props.keys())
+ body_param_name = "body"
+ if route.request_body and route.request_body.content_schema and not body_props:
+ # Whole-body arguments participate in collision detection too. References
+ # keep the name "body"; other schemas use their normalized title.
+ if "$ref" not in body_schema:
+ body_param_name = re.sub(
+ r"[^a-zA-Z0-9_]", "_", body_schema.get("title", "body").lower()
+ )
+ if not body_param_name or body_param_name[0].isdigit():
+ body_param_name = "body_data"
+ body_param_names.add(body_param_name)
non_body_param_counts = Counter(param.name for param in route.parameters)
colliding_params = (all_non_body_params & body_param_names) | {
name for name, count in non_body_param_counts.items() if count > 1
@@ -524,16 +536,7 @@ def _combine_schemas_and_map_params(
# Add request body properties (no suffixes for body parameters)
if route.request_body and route.request_body.content_schema:
- # If body is just a $ref, we need to handle it differently
- if "$ref" in body_schema and not body_props:
- # The entire body is a reference to a schema
- # We need to expand this inline or keep the ref
- # For simplicity, we'll keep it as a single property
- properties["body"] = body_schema
- if route.request_body.required:
- required.append("body")
- parameter_map["body"] = {"location": "body", "openapi_name": "body"}
- elif body_props:
+ if body_props:
# Normal case: body has properties
for prop_name, prop_schema in body_props.items():
properties[prop_name] = prop_schema
@@ -547,21 +550,13 @@ def _combine_schemas_and_map_params(
if route.request_body.required:
required.extend(body_schema.get("required", []))
else:
- # Handle direct array/primitive schemas (like list[str] parameters from FastAPI)
- # Use the schema title as parameter name, fall back to generic name
- param_name = body_schema.get("title", "body").lower()
-
- # Clean the parameter name to be valid
- import re
-
- param_name = re.sub(r"[^a-zA-Z0-9_]", "_", param_name)
- if not param_name or param_name[0].isdigit():
- param_name = "body_data"
-
- properties[param_name] = body_schema
+ properties[body_param_name] = body_schema
if route.request_body.required:
- required.append(param_name)
- parameter_map[param_name] = {"location": "body", "openapi_name": param_name}
+ required.append(body_param_name)
+ parameter_map[body_param_name] = {
+ "location": "body",
+ "openapi_name": body_param_name,
+ }
result = {
"type": "object",
diff --git a/tests/server/providers/openapi/test_whole_body_parameter_collisions.py b/tests/server/providers/openapi/test_whole_body_parameter_collisions.py
new file mode 100644
index 000000000..67e311926
--- /dev/null
+++ b/tests/server/providers/openapi/test_whole_body_parameter_collisions.py
@@ -0,0 +1,142 @@
+"""Whole-body arguments must not hide parameters in other HTTP locations."""
+
+import json
+from typing import Any
+
+import httpx2
+import pytest
+from fastapi import FastAPI, Query
+from jsonschema import Draft202012Validator
+
+from fastmcp import Client, FastMCP
+
+
[email protected]("openapi_version", ["3.0.3", "3.1.0"])
[email protected]("location", ["path", "query", "header", "cookie"])
+ "schema,body_name,payload,use_ref",
+ [
+ pytest.param(
+ {"type": "array", "items": {"type": "integer"}, "title": "Values"},
+ "values",
+ [1, 2],
+ False,
+ id="titled-array",
+ ),
+ pytest.param(
+ {"type": "string"}, "body", "message", False, id="untitled-scalar"
+ ),
+ pytest.param(
+ {
+ "type": "object",
+ "title": "Labels",
+ "additionalProperties": {"type": "string"},
+ },
+ "labels",
+ {"team": "infra"},
+ True,
+ id="referenced-dictionary",
+ ),
+ ],
+)
+async def test_whole_body_and_http_parameter_reach_their_locations(
+ openapi_version: str,
+ location: str,
+ schema: dict[str, Any],
+ body_name: str,
+ payload: Any,
+ use_ref: bool,
+) -> None:
+ path = f"/values/{{{body_name}}}" if location == "path" else "/values"
+ spec = {
+ "openapi": openapi_version,
+ "info": {"title": "Body collisions", "version": "1.0"},
+ "paths": {
+ path: {
+ "post": {
+ "operationId": "set_value",
+ "parameters": [
+ {
+ "name": body_name,
+ "in": location,
+ "required": True,
+ "schema": {"type": "string"},
+ }
+ ],
+ "requestBody": {
+ "required": True,
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Payload"}
+ if use_ref
+ else schema
+ }
+ },
+ },
+ "responses": {"200": {"description": "OK"}},
+ }
+ }
+ },
+ "components": {"schemas": {"Payload": schema}},
+ }
+ requests: list[httpx2.Request] = []
+
+ def capture(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ return httpx2.Response(200, json={"ok": True})
+
+ async with httpx2.AsyncClient(
+ base_url="https://example.com", transport=httpx2.MockTransport(capture)
+ ) as http_client:
+ server = FastMCP.from_openapi(openapi_spec=spec, client=http_client)
+ async with Client(server) as client:
+ tool = (await client.list_tools())[0]
+ arguments = {body_name: payload, f"{body_name}__{location}": "active"}
+ assert set(tool.input_schema["properties"]) == set(arguments)
+ Draft202012Validator.check_schema(tool.input_schema)
+ assert set(tool.input_schema["required"]) == set(arguments)
+ await client.call_tool("set_value", arguments)
+
+ assert len(requests) == 1
+ request = requests[0]
+ assert json.loads(request.content) == payload
+ if location == "path":
+ assert request.url.path == "/values/active"
+ elif location == "query":
+ assert dict(request.url.params) == {body_name: "active"}
+ elif location == "header":
+ assert request.headers[body_name] == "active"
+ else:
+ assert request.headers["cookie"] == f"{body_name}=active"
+
+
+async def test_fastapi_body_title_does_not_hide_query_alias() -> None:
+ app = FastAPI()
+
+ @app.post("/values", operation_id="set_values")
+ def set_values(
+ values: list[int], group: str = Query(alias="values")
+ ) -> dict[str, Any]:
+ return {"group": group, "values": values}
+
+ async with httpx2.AsyncClient(
+ base_url="https://example.com", transport=httpx2.ASGITransport(app)
+ ) as http_client:
+ direct = await http_client.post(
+ "/values", params={"values": "active"}, json=[1, 2]
+ )
+ assert direct.status_code == 200
+ server = FastMCP.from_openapi(openapi_spec=app.openapi(), client=http_client)
+ async with Client(server) as client:
+ result = await client.call_tool(
+ "set_values", {"values": [1, 2], "values__query": "active"}
+ )
+
+ assert (
+ result.structured_content
+ == direct.json()
+ == {
+ "group": "active",
+ "values": [1, 2],
+ }
+ )
diff --git a/tests/utilities/openapi/test_schemas.py b/tests/utilities/openapi/test_schemas.py
index ceac2bdd6..b02e47f54 100644
--- a/tests/utilities/openapi/test_schemas.py
+++ b/tests/utilities/openapi/test_schemas.py
@@ -1,5 +1,7 @@
"""Unit tests for schema processing and parameter mapping."""
+from typing import Any
+
import pytest
from fastmcp.utilities.json_schema import compress_schema
@@ -15,6 +17,72 @@ from fastmcp.utilities.openapi.schemas import (
)
+ "body_schema,param_name,body_name",
+ [
+ pytest.param(None, "body", None, id="no-body"),
+ pytest.param(
+ {"type": "object", "properties": {"body": {"type": "string"}}},
+ "body",
+ "body",
+ id="named-property",
+ ),
+ pytest.param(
+ {"$ref": "#/components/schemas/Values", "title": "Other"},
+ "body",
+ "body",
+ id="whole-body-reference",
+ ),
+ pytest.param(
+ {"type": "string", "title": "Value List"},
+ "value_list",
+ "value_list",
+ id="normalized-title",
+ ),
+ pytest.param(
+ {"type": "string", "title": "123Values"},
+ "body_data",
+ "body_data",
+ id="numeric-title",
+ ),
+ pytest.param(
+ {"type": "string", "title": ""},
+ "body_data",
+ "body_data",
+ id="empty-title",
+ ),
+ ],
+)
+def test_body_names_preserve_required_query_parameters(
+ body_schema: dict[str, Any] | None, param_name: str, body_name: str | None
+) -> None:
+ route = HTTPRoute(
+ path="/values",
+ method="POST",
+ parameters=[
+ ParameterInfo(
+ name=param_name,
+ location="query",
+ required=True,
+ schema={"type": "string"},
+ )
+ ],
+ request_body=RequestBodyInfo(content_schema={"application/json": body_schema})
+ if body_schema is not None
+ else None,
+ request_schemas={"Values": {"type": "array", "items": {"type": "integer"}}},
+ )
+
+ schema, param_map = _combine_schemas_and_map_params(route)
+ query_name = f"{param_name}__query" if body_name else param_name
+ expected_map = {query_name: {"location": "query", "openapi_name": param_name}}
+ if body_name:
+ expected_map[body_name] = {"location": "body", "openapi_name": body_name}
+ assert param_map == expected_map
+ assert set(schema["properties"]) == set(expected_map)
+ assert schema["required"] == [query_name]
+
+
class TestSchemaProcessing:
"""Test schema processing utilities."""