Skip to content

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

Preserve OpenAPI raw body content types (#5093)

Kunpeng Xie119339e90f80
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/director.py b/fastmcp_slim/fastmcp/utilities/openapi/director.py
index 79ec11f50..7f42184f4 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/director.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/director.py
@@ -2,6 +2,7 @@
import io
import json as _json
+from email.message import Message
from typing import Any, ClassVar
from urllib.parse import quote, urljoin
@@ -145,6 +146,15 @@ class RequestDirector:
json_body = body
else:
content = body
+ if raw_content_type is not None:
+ headers = dict(headers) if headers else {}
+ headers["Content-Type"] = raw_content_type
+ if isinstance(body, str):
+ media_type = Message()
+ media_type["Content-Type"] = raw_content_type
+ content = body.encode(
+ media_type.get_content_charset() or "utf-8"
+ )
# Step 7: Create httpx2.Request
return httpx2.Request(
diff --git a/tests/server/providers/openapi/test_raw_request_bodies.py b/tests/server/providers/openapi/test_raw_request_bodies.py
new file mode 100644
index 000000000..720174ecc
--- /dev/null
+++ b/tests/server/providers/openapi/test_raw_request_bodies.py
@@ -0,0 +1,25 @@
+"""Non-JSON request bodies retain the media type required by the endpoint."""
+
+import httpx2
+from fastapi import Body, FastAPI, Request
+
+from fastmcp import Client, FastMCP
+
+
+async def test_plain_text_body_reaches_http_endpoint() -> None:
+ app = FastAPI()
+
+ @app.post("/echo", operation_id="echo")
+ def echo(
+ request: Request, body: str = Body(media_type="text/plain")
+ ) -> dict[str, str | None]:
+ return {"text": body, "content_type": request.headers.get("content-type")}
+
+ async with httpx2.AsyncClient(
+ base_url="http://test", transport=httpx2.ASGITransport(app=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("echo", {"body": "hello from a tool"})
+
+ assert result.data == {"text": "hello from a tool", "content_type": "text/plain"}
diff --git a/tests/utilities/openapi/test_director.py b/tests/utilities/openapi/test_director.py
index a2f0940f0..cd0b43815 100644
--- a/tests/utilities/openapi/test_director.py
+++ b/tests/utilities/openapi/test_director.py
@@ -325,7 +325,22 @@ class TestRequestDirector:
request3 = director.build(basic_route, flat_args, "https://api.example.com/v1")
assert request3.url == "https://api.example.com/v1/users/123"
- def test_body_construction_single_value(self, director):
+ @pytest.mark.parametrize(
+ ("media_type", "body", "expected"),
+ [
+ ("text/plain", "£10", b"\xc2\xa310"),
+ ("text/plain; charset=utf-8", "£10", b"\xc2\xa310"),
+ ('text/plain; charset="iso-8859-1"', "£10", b"\xa310"),
+ (
+ "application/xml",
+ "<message>Hello</message>",
+ b"<message>Hello</message>",
+ ),
+ ("application/octet-stream", "Hello", b"Hello"),
+ ("application/octet-stream", b"\x00\xff", b"\x00\xff"),
+ ],
+ )
+ def test_body_construction_single_value(self, director, media_type, body, expected):
"""Test body construction when body schema is not an object."""
route = HTTPRoute(
path="/upload",
@@ -333,20 +348,21 @@ class TestRequestDirector:
operation_id="upload_file",
request_body=RequestBodyInfo(
required=True,
- content_schema={"text/plain": {"type": "string"}},
+ content_schema={media_type: {"type": "string"}},
),
parameter_map={
"content": {"location": "body", "openapi_name": "content"},
},
)
- flat_args = {"content": "Hello, World!"}
+ flat_args = {"content": body}
request = director.build(route, flat_args, "https://api.example.com")
assert request.method == "POST"
# For non-JSON content, httpx uses 'content' parameter which becomes bytes
- assert request.content == b"Hello, World!"
+ assert request.content == expected
+ assert request.headers["content-type"] == media_type
def test_body_construction_multiple_properties_non_object_schema(self, director):
"""Test body construction with multiple properties but non-object schema."""