Skip to content

🚀 The fast, Pythonic way to build MCP servers and clients.

fix(openapi): encode JSON scalar request bodies (#5052)

Gonghan-Princess443227165a2b
diff --git a/docs/integrations/openapi.mdx b/docs/integrations/openapi.mdx
index 52538781a..019619f28 100644
--- a/docs/integrations/openapi.mdx
+++ b/docs/integrations/openapi.mdx
@@ -454,6 +454,12 @@ FastMCP handles array parameters according to OpenAPI specifications:
Header parameters are automatically converted to strings and included in the HTTP request.
+### JSON Request Bodies
+
+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.
+
### Composed Request Bodies
A request body becomes a flat set of tool arguments, which is the shape LLM tool-calling APIs fill in most reliably. Schemas composed with `allOf` are resolved first, following `$ref` members, so fields inherited from a parent schema appear alongside the ones a schema declares itself.
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/director.py b/fastmcp_slim/fastmcp/utilities/openapi/director.py
index bb6bd206c..62059f36f 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/director.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/director.py
@@ -73,7 +73,7 @@ class RequestDirector:
method: str = route.method.upper()
params = query_params if query_params else None
headers = header_params if header_params else None
- json_body: dict[str, Any] | list[Any] | None = None
+ json_body: dict[str, Any] | list[Any] | str | int | float | bool | None = None
content: str | bytes | None = None
# Step 5: Determine the declared content type from the OpenAPI spec.
@@ -122,16 +122,22 @@ class RequestDirector:
and isinstance(body, dict)
):
data = body
- elif isinstance(body, dict | list):
+ elif (
+ isinstance(body, dict | list)
+ or declared_content_type == "application/json"
+ or (
+ declared_content_type is not None
+ and declared_content_type.endswith("+json")
+ )
+ ):
if (
declared_content_type is not None
- and declared_content_type != "application/json"
+ and raw_content_type != "application/json"
and "json" in declared_content_type
):
- # JSON-compatible types like application/json-patch+json
- # or application/merge-patch+json need an explicit
- # Content-Type header since httpx's json= always
- # sets application/json.
+ # JSON media types with parameters or custom subtypes need
+ # an explicit Content-Type header since httpx's json=
+ # always sets bare application/json.
content = _json.dumps(body, allow_nan=False).encode("utf-8")
headers = dict(headers) if headers else {}
headers["Content-Type"] = raw_content_type
diff --git a/tests/server/providers/openapi/test_json_request_bodies.py b/tests/server/providers/openapi/test_json_request_bodies.py
new file mode 100644
index 000000000..d24937c1f
--- /dev/null
+++ b/tests/server/providers/openapi/test_json_request_bodies.py
@@ -0,0 +1,71 @@
+"""JSON scalar request bodies retain their type through OpenAPI tool calls."""
+
+import json
+
+import httpx2
+import pytest
+
+from fastmcp import Client, FastMCP
+
+
+ "media_type",
+ [
+ "application/json",
+ "application/json; charset=utf-8",
+ 'application/json; profile="https://example.com/schema"',
+ "application/vnd.example+json",
+ "application/merge-patch+json; charset=utf-8",
+ ],
+)
+ "schema_type,value",
+ [
+ ("string", "hello"),
+ ("string", "true"),
+ ("string", ""),
+ ("string", 'café "quoted"\ntext'),
+ ("integer", 42),
+ ("integer", 0),
+ ("number", 1.25),
+ ("boolean", True),
+ ("boolean", False),
+ ],
+)
+async def test_scalar_json_body_reaches_http_endpoint(
+ media_type: str, schema_type: str, value: str | int | float | bool
+) -> None:
+ spec = {
+ "openapi": "3.1.0",
+ "info": {"title": "Scalar API", "version": "1.0"},
+ "paths": {
+ "/value": {
+ "post": {
+ "operationId": "set_value",
+ "requestBody": {
+ "required": True,
+ "content": {media_type: {"schema": {"type": schema_type}}},
+ },
+ "responses": {"200": {"description": "OK"}},
+ }
+ }
+ },
+ }
+ 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:
+ await client.call_tool("set_value", {"body": value})
+
+ assert len(requests) == 1
+ assert requests[0].headers["content-type"] == media_type
+ decoded = json.loads(requests[0].content)
+ assert decoded == value
+ assert type(decoded) is type(value)
diff --git a/tests/utilities/openapi/test_director.py b/tests/utilities/openapi/test_director.py
index 777566688..a2f0940f0 100644
--- a/tests/utilities/openapi/test_director.py
+++ b/tests/utilities/openapi/test_director.py
@@ -476,7 +476,15 @@ class TestContentTypeHandling:
assert request.headers["content-type"] == "application/merge-patch+json"
assert json.loads(request.content) == {"name": "test"}
- def test_content_type_preserves_media_type_parameters(self, director):
+ @pytest.mark.parametrize(
+ "media_type",
+ [
+ "application/json-patch+json; charset=utf-8",
+ "application/json; charset=utf-8",
+ 'application/json; profile="https://example.com/schema"',
+ ],
+ )
+ def test_content_type_preserves_media_type_parameters(self, director, media_type):
"""Media-type parameters like charset are preserved on the wire."""
route = HTTPRoute(
path="/items",
@@ -485,7 +493,7 @@ class TestContentTypeHandling:
request_body=RequestBodyInfo(
required=True,
content_schema={
- "application/json-patch+json; charset=utf-8": {
+ media_type: {
"type": "object",
"properties": {"name": {"type": "string"}},
}
@@ -497,10 +505,7 @@ class TestContentTypeHandling:
)
request = director.build(route, {"name": "test"}, "https://example.com")
- assert (
- request.headers["content-type"]
- == "application/json-patch+json; charset=utf-8"
- )
+ assert request.headers["content-type"] == media_type
assert json.loads(request.content) == {"name": "test"}
def test_custom_content_type_preserves_other_headers(self, director):