Skip to content

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

fix(openapi): preserve dictionary request bodies (#5097)

astsc86b02deca86
diff --git a/docs/integrations/openapi.mdx b/docs/integrations/openapi.mdx
index 019619f28..33aa608fe 100644
--- a/docs/integrations/openapi.mdx
+++ b/docs/integrations/openapi.mdx
@@ -456,6 +456,8 @@ Header parameters are automatically converted to strings and included in the HTT
### JSON Request Bodies
+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`.
+
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/director.py b/fastmcp_slim/fastmcp/utilities/openapi/director.py
index 62059f36f..79ec11f50 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/director.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/director.py
@@ -263,17 +263,14 @@ class RequestDirector:
content_type = next(iter(route.request_body.content_schema))
body_schema = route.request_body.content_schema[content_type]
- if (
- isinstance(body_schema, dict)
- and body_schema.get("type") == "object"
- ):
+ # Only named properties are flattened into individual arguments.
+ if isinstance(body_schema, dict) and body_schema.get("properties"):
body = body_props
elif len(body_props) == 1:
- # If body schema is not an object and we have exactly one property,
- # use the property value directly
+ # Free-form objects, arrays, and primitives use a single
+ # argument containing the entire body.
body = next(iter(body_props.values()))
else:
- # Multiple properties but schema is not object - wrap in object
body = body_props
else:
body = body_props
diff --git a/tests/server/providers/openapi/test_object_request_bodies.py b/tests/server/providers/openapi/test_object_request_bodies.py
new file mode 100644
index 000000000..de2324040
--- /dev/null
+++ b/tests/server/providers/openapi/test_object_request_bodies.py
@@ -0,0 +1,172 @@
+"""Object request bodies retain their shape through OpenAPI tool calls."""
+
+import json
+from typing import Any
+
+import httpx2
+import pytest
+from fastapi import FastAPI
+
+from fastmcp import Client, FastMCP
+
+
[email protected]("openapi_version", ["3.0.3", "3.1.0"])
[email protected]("use_ref", [False, True], ids=["inline", "ref"])
+ "schema,arguments,expected",
+ [
+ pytest.param(
+ {"type": "object", "additionalProperties": {"type": "string"}},
+ {"body": {"team": "infra"}},
+ {"team": "infra"},
+ id="typed-dictionary",
+ ),
+ pytest.param(
+ {"type": "object", "additionalProperties": True},
+ {"body": {"team": {"name": "infra"}}},
+ {"team": {"name": "infra"}},
+ id="free-form-dictionary",
+ ),
+ pytest.param(
+ {
+ "type": "object",
+ "properties": {},
+ "additionalProperties": {"type": "string"},
+ },
+ {"body": {"team": "infra"}},
+ {"team": "infra"},
+ id="empty-properties",
+ ),
+ pytest.param(
+ {"type": "object", "additionalProperties": {"type": "string"}},
+ {"body": {}},
+ {},
+ id="empty-dictionary",
+ ),
+ pytest.param(
+ {
+ "type": "object",
+ "title": "Labels",
+ "additionalProperties": {"type": "string"},
+ },
+ {"labels": {"team": "infra"}},
+ {"team": "infra"},
+ id="titled-dictionary",
+ ),
+ pytest.param(
+ {"type": "object", "properties": {"body": {"type": "string"}}},
+ {"body": "message"},
+ {"body": "message"},
+ id="property-named-body",
+ ),
+ pytest.param(
+ {
+ "type": "object",
+ "title": "Labels",
+ "properties": {
+ "labels": {
+ "type": "object",
+ "additionalProperties": {"type": "string"},
+ }
+ },
+ },
+ {"labels": {"team": "infra"}},
+ {"labels": {"team": "infra"}},
+ id="property-matching-title",
+ ),
+ pytest.param(
+ {
+ "allOf": [
+ {
+ "type": "object",
+ "properties": {"body": {"type": "string"}},
+ }
+ ]
+ },
+ {"body": "message"},
+ {"body": "message"},
+ id="allof-property",
+ ),
+ ],
+)
+async def test_object_json_body_reaches_http_endpoint(
+ openapi_version: str,
+ use_ref: bool,
+ schema: dict[str, Any],
+ arguments: dict[str, Any],
+ expected: dict[str, Any],
+) -> None:
+ body_schema = {"$ref": "#/components/schemas/Labels"} if use_ref else schema
+ spec = {
+ "openapi": openapi_version,
+ "info": {"title": "Labels API", "version": "1.0"},
+ "paths": {
+ "/accounts/{account_id}/labels": {
+ "post": {
+ "operationId": "set_labels",
+ "parameters": [
+ {
+ "name": "account_id",
+ "in": "path",
+ "required": True,
+ "schema": {"type": "string"},
+ },
+ {
+ "name": "dry_run",
+ "in": "query",
+ "schema": {"type": "boolean"},
+ },
+ ],
+ "requestBody": {
+ "required": True,
+ "content": {"application/json": {"schema": body_schema}},
+ },
+ "responses": {"200": {"description": "OK"}},
+ }
+ }
+ },
+ "components": {"schemas": {"Labels": 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]
+ assert set(tool.input_schema["properties"]) == {
+ "account_id",
+ "dry_run",
+ *arguments,
+ }
+ await client.call_tool(
+ "set_labels", {"account_id": "acme", "dry_run": True, **arguments}
+ )
+
+ assert len(requests) == 1
+ assert requests[0].url.path == "/accounts/acme/labels"
+ assert dict(requests[0].url.params) == {"dry_run": "true"}
+ assert json.loads(requests[0].content) == expected
+
+
[email protected]("labels", [{"team": "infra"}, {}])
+async def test_fastapi_dictionary_body(labels: dict[str, str]) -> None:
+ app = FastAPI()
+
+ @app.post("/labels", operation_id="set_labels")
+ def set_labels(labels: dict[str, str]) -> dict[str, str]:
+ return labels
+
+ async with httpx2.AsyncClient(
+ base_url="https://example.com", transport=httpx2.ASGITransport(app)
+ ) as http_client:
+ server = FastMCP.from_openapi(openapi_spec=app.openapi(), client=http_client)
+ async with Client(server) as client:
+ result = await client.call_tool("set_labels", {"labels": labels})
+
+ assert result.structured_content == labels