Skip to content

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

fix(openapi): JSON-encode object form fields in urlencoded request bodies (#5851)

ε“ˆεŸΊη±³c15826ad8626
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/director.py b/fastmcp_slim/fastmcp/utilities/openapi/director.py
index cf9b53681..c3e9470df 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/director.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/director.py
@@ -48,6 +48,180 @@ def _uses_default_multipart_encoding(encoding: dict[str, Any]) -> bool:
)
+def _is_json_media_type(content_type: str | None) -> bool:
+ """Return whether a media type denotes JSON, ignoring parameters."""
+ if not content_type:
+ return False
+ media_type = content_type.split(";")[0].strip().lower()
+ return media_type == "application/json" or media_type.endswith("+json")
+
+
+def _resolve_schema_ref(
+ schema: Any,
+ definitions: dict[str, Any],
+ active_refs: frozenset[str] = frozenset(),
+) -> tuple[dict[str, Any], frozenset[str]]:
+ """Resolve a local `$ref`, tracking references active on this traversal path.
+
+ Returns the resolved schema (empty when the chain cycles or cannot be
+ resolved) plus the extended active-reference set. Callers recurse through
+ composition keywords with that set so mutually recursive component graphs
+ terminate instead of overflowing the stack.
+ """
+ while isinstance(schema, dict) and isinstance(schema.get("$ref"), str):
+ ref = schema["$ref"]
+ if ref in active_refs:
+ return {}, active_refs
+ active_refs = active_refs | {ref}
+ target = definitions.get(ref.rsplit("/", 1)[-1])
+ if not isinstance(target, dict):
+ return {}, active_refs
+ schema = target
+ return (schema if isinstance(schema, dict) else {}), active_refs
+
+
+def _schema_type_includes(schema: dict[str, Any], type_name: str) -> bool:
+ """Return whether `type` declares the given type, including type lists."""
+ schema_type = schema.get("type")
+ if schema_type == type_name:
+ return True
+ return isinstance(schema_type, list) and type_name in schema_type
+
+
+def _schema_is_object(
+ schema: Any,
+ definitions: dict[str, Any],
+ active_refs: frozenset[str] = frozenset(),
+) -> bool:
+ """Return whether a schema (or any composition branch) describes an object."""
+ schema, active_refs = _resolve_schema_ref(schema, definitions, active_refs)
+ if not schema:
+ return False
+ if (
+ _schema_type_includes(schema, "object")
+ or "properties" in schema
+ or "additionalProperties" in schema
+ ):
+ return True
+ for keyword in ("allOf", "anyOf", "oneOf"):
+ members = schema.get(keyword)
+ if isinstance(members, list) and any(
+ _schema_is_object(member, definitions, active_refs) for member in members
+ ):
+ return True
+ return False
+
+
+def _schema_is_array_of_objects(
+ schema: Any,
+ definitions: dict[str, Any],
+ value: list[Any],
+ active_refs: frozenset[str] = frozenset(),
+) -> bool:
+ """Return whether a schema describes an object array matching `value`.
+
+ Composition alternatives are chosen against the runtime items: a `oneOf`
+ or `anyOf` that offers both `array<object>` and `array<string>` keeps a
+ string list on the string branch, so it is not JSON-encoded for an unused
+ object branch.
+ """
+ schema, active_refs = _resolve_schema_ref(schema, definitions, active_refs)
+ if not schema:
+ return False
+ if _schema_type_includes(schema, "array"):
+ item_schemas: list[Any] = []
+ items = schema.get("items")
+ if isinstance(items, list):
+ item_schemas.extend(items)
+ elif items is not None:
+ item_schemas.append(items)
+ prefix_items = schema.get("prefixItems")
+ if isinstance(prefix_items, list):
+ item_schemas.extend(prefix_items)
+ if any(
+ _schema_is_object(item, definitions, active_refs) for item in item_schemas
+ ):
+ # Empty arrays carry no runtime type information; preserve the
+ # object-array behavior there.
+ return not value or any(isinstance(item, dict) for item in value)
+ return False
+ for keyword in ("allOf", "anyOf", "oneOf"):
+ members = schema.get(keyword)
+ if isinstance(members, list) and any(
+ _schema_is_array_of_objects(member, definitions, value, active_refs)
+ for member in members
+ ):
+ return True
+ return False
+
+
+def _form_property_schemas(
+ body_schema: dict[str, Any], definitions: dict[str, Any]
+) -> tuple[dict[str, Any], dict[str, Any] | None]:
+ """Collect a form body's property schemas, merging `allOf` members.
+
+ Returns the declared properties plus the `additionalProperties` schema
+ (if any) that applies to names not declared in `properties`.
+ """
+ properties: dict[str, Any] = {}
+ additional_properties: dict[str, Any] | None = None
+
+ def collect(schema: Any, active_refs: frozenset[str] = frozenset()) -> None:
+ nonlocal additional_properties
+ schema, active_refs = _resolve_schema_ref(schema, definitions, active_refs)
+ if not schema:
+ return
+ if isinstance(schema.get("properties"), dict):
+ properties.update(schema["properties"])
+ if additional_properties is None:
+ extra = schema.get("additionalProperties")
+ if isinstance(extra, dict):
+ additional_properties = extra
+ members = schema.get("allOf")
+ if isinstance(members, list):
+ for member in members:
+ collect(member, active_refs)
+
+ collect(body_schema)
+ return properties, additional_properties
+
+
+def _build_form_urlencoded_data(
+ body: dict[str, Any],
+ body_schema: dict[str, Any],
+ encoding: dict[str, dict[str, Any]],
+ definitions: dict[str, Any],
+) -> dict[str, Any]:
+ """Serialize structured urlencoded fields as JSON per the OAS Encoding Object.
+
+ Object properties default to `contentType: application/json`, so they must
+ be JSON-encoded rather than passed to httpx for Python `repr` stringification.
+ An explicit encoding `contentType` overrides that default. Scalars and
+ arrays of scalars keep httpx's form encoding (arrays repeat the key).
+ """
+ properties, additional_properties = _form_property_schemas(body_schema, definitions)
+ data: dict[str, Any] = {}
+ for name, value in body.items():
+ content_type = encoding.get(name, {}).get("contentType")
+ if content_type is not None:
+ json_encode = _is_json_media_type(content_type)
+ else:
+ prop_schema = properties.get(name, additional_properties or {})
+ json_encode = (
+ (
+ isinstance(value, dict)
+ and _schema_is_object(prop_schema, definitions)
+ )
+ or (
+ isinstance(value, list)
+ and _schema_is_array_of_objects(prop_schema, definitions, value)
+ )
+ or (value is None and _schema_is_object(prop_schema, definitions))
+ )
+ data[name] = _json.dumps(value, allow_nan=False) if json_encode else value
+ return data
+
+
def _required_json_object_without_properties(route: HTTPRoute) -> bool:
"""Return whether an omitted required JSON object body should be sent empty.
@@ -235,7 +409,23 @@ class RequestDirector:
declared_content_type == "application/x-www-form-urlencoded"
and isinstance(body, dict)
):
- data = body
+ request_body = route.request_body
+ body_schema = (
+ request_body.content_schema.get(raw_content_type, {})
+ if request_body and raw_content_type is not None
+ else {}
+ )
+ definitions = dict(route.request_schemas)
+ if isinstance(body_schema.get("$defs"), dict):
+ definitions.update(body_schema["$defs"])
+ encoding = (
+ request_body.encoding.get(raw_content_type, {})
+ if request_body and raw_content_type is not None
+ else {}
+ )
+ data = _build_form_urlencoded_data(
+ body, body_schema, encoding, definitions
+ )
elif (
isinstance(body, dict | list)
or declared_content_type == "application/json"
diff --git a/tests/server/providers/openapi/test_object_request_bodies.py b/tests/server/providers/openapi/test_object_request_bodies.py
index e9740c145..16a975e79 100644
--- a/tests/server/providers/openapi/test_object_request_bodies.py
+++ b/tests/server/providers/openapi/test_object_request_bodies.py
@@ -2,6 +2,7 @@
import json
from typing import Any
+from urllib.parse import parse_qs
import httpx2
import pytest
@@ -172,6 +173,415 @@ async def test_fastapi_dictionary_body(labels: dict[str, str]) -> None:
assert result.structured_content == labels
+def _form_urlencoded_spec(
+ properties: dict[str, Any],
+ *,
+ required: list[str] | None = None,
+ encoding: dict[str, Any] | None = None,
+ schema_ref: str | None = None,
+) -> dict[str, Any]:
+ """Build a spec whose only operation takes a form-urlencoded body."""
+ body_schema: dict[str, Any] = {
+ "type": "object",
+ "properties": properties,
+ }
+ if required:
+ body_schema["required"] = required
+ media_type: dict[str, Any] = {"schema": body_schema}
+ if encoding is not None:
+ media_type["encoding"] = encoding
+ spec: dict[str, Any] = {
+ "openapi": "3.1.0",
+ "info": {"title": "Form API", "version": "1.0"},
+ "paths": {
+ "/submit": {
+ "post": {
+ "operationId": "submit",
+ "requestBody": {
+ "required": True,
+ "content": {"application/x-www-form-urlencoded": media_type},
+ },
+ "responses": {"200": {"description": "OK"}},
+ }
+ }
+ },
+ }
+ if schema_ref is not None:
+ body_schema["properties"]["filter"] = {"$ref": schema_ref}
+ spec["components"] = {
+ "schemas": {
+ "Filter": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "age": {"type": "integer"},
+ },
+ }
+ }
+ }
+ return spec
+
+
+async def _submit_and_capture(
+ spec: dict[str, Any], arguments: dict[str, Any]
+) -> httpx2.Request:
+ 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("submit", arguments)
+
+ assert len(requests) == 1
+ return requests[0]
+
+
+def _form_fields(request: httpx2.Request) -> dict[str, list[str]]:
+ return parse_qs(request.content.decode("utf-8"), keep_blank_values=True)
+
+
+def _form_body_schema_spec(
+ body_schema: dict[str, Any],
+ components: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Build a form-urlencoded spec around an arbitrary body schema."""
+ spec: dict[str, Any] = {
+ "openapi": "3.1.0",
+ "info": {"title": "Form API", "version": "1.0"},
+ "paths": {
+ "/submit": {
+ "post": {
+ "operationId": "submit",
+ "requestBody": {
+ "required": True,
+ "content": {
+ "application/x-www-form-urlencoded": {"schema": body_schema}
+ },
+ },
+ "responses": {"200": {"description": "OK"}},
+ }
+ }
+ },
+ }
+ if components is not None:
+ spec["components"] = {"schemas": components}
+ return spec
+
+
[email protected]("use_ref", [False, True], ids=["inline", "ref"])
+async def test_form_urlencoded_object_property_is_json_encoded(
+ use_ref: bool,
+) -> None:
+ """Object properties default to contentType application/json in OAS."""
+ spec = _form_urlencoded_spec(
+ {
+ "filter": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "age": {"type": "integer"},
+ },
+ },
+ "tags": {"type": "array", "items": {"type": "string"}},
+ "limit": {"type": "integer"},
+ },
+ required=["filter"],
+ schema_ref="#/components/schemas/Filter" if use_ref else None,
+ )
+
+ request = await _submit_and_capture(
+ spec,
+ {
+ "filter": {"name": "alice", "age": 30},
+ "tags": ["a", "b"],
+ "limit": 5,
+ },
+ )
+
+ assert request.headers["content-type"] == "application/x-www-form-urlencoded"
+ fields = _form_fields(request)
+ payload = fields["filter"][0]
+ assert "'name'" not in payload
+ assert json.loads(payload) == {"name": "alice", "age": 30}
+ # Arrays of primitives keep httpx's repeated-key form encoding.
+ assert fields["tags"] == ["a", "b"]
+ assert fields["limit"] == ["5"]
+
+
+async def test_form_urlencoded_object_property_encodes_nested_null() -> None:
+ """Nested None inside a JSON-encoded object becomes JSON null."""
+ spec = _form_urlencoded_spec(
+ {
+ "filter": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "metadata": {"type": ["string", "null"]},
+ },
+ }
+ },
+ required=["filter"],
+ )
+
+ request = await _submit_and_capture(
+ spec, {"filter": {"name": "alice", "metadata": None}}
+ )
+
+ payload = _form_fields(request)["filter"][0]
+ assert "None" not in payload
+ assert "null" in payload
+ assert json.loads(payload) == {"name": "alice", "metadata": None}
+
+
+async def test_form_urlencoded_array_of_objects_is_json_encoded() -> None:
+ spec = _form_urlencoded_spec(
+ {
+ "rows": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {"type": "integer"},
+ "note": {"type": ["string", "null"]},
+ },
+ },
+ }
+ },
+ required=["rows"],
+ )
+
+ request = await _submit_and_capture(
+ spec, {"rows": [{"id": 1}, {"id": 2, "note": None}]}
+ )
+
+ payload = _form_fields(request)["rows"][0]
+ assert "None" not in payload
+ assert "'id'" not in payload
+ assert json.loads(payload) == [{"id": 1}, {"id": 2, "note": None}]
+
+
+async def test_form_urlencoded_explicit_json_encoding_is_honored() -> None:
+ """An explicit encoding contentType overrides the default serialization."""
+ spec = _form_urlencoded_spec(
+ {"tags": {"type": "array", "items": {"type": "string"}}},
+ required=["tags"],
+ encoding={"tags": {"contentType": "application/json"}},
+ )
+
+ request = await _submit_and_capture(spec, {"tags": ["a", "b"]})
+
+ tags = _form_fields(request)["tags"]
+ assert len(tags) == 1
+ assert json.loads(tags[0]) == ["a", "b"]
+
+
+async def test_json_object_body_serialization_is_unchanged() -> None:
+ """JSON request bodies keep using a JSON document, not form encoding."""
+ spec = {
+ "openapi": "3.1.0",
+ "info": {"title": "JSON API", "version": "1.0"},
+ "paths": {
+ "/submit": {
+ "post": {
+ "operationId": "submit",
+ "requestBody": {
+ "required": True,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "filter": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "metadata": {
+ "type": ["string", "null"]
+ },
+ },
+ },
+ "tags": {
+ "type": "array",
+ "items": {"type": "string"},
+ },
+ },
+ }
+ }
+ },
+ },
+ "responses": {"200": {"description": "OK"}},
+ }
+ }
+ },
+ }
+
+ request = await _submit_and_capture(
+ spec, {"filter": {"name": "alice", "metadata": None}, "tags": ["a", "b"]}
+ )
+
+ assert request.headers["content-type"] == "application/json"
+ assert json.loads(request.content) == {
+ "filter": {"name": "alice", "metadata": None},
+ "tags": ["a", "b"],
+ }
+
+
+_ROW_OBJECT_SCHEMA = {
+ "type": "object",
+ "properties": {"id": {"type": "integer"}},
+}
+
+
+ "rows_schema",
+ [
+ pytest.param(
+ {
+ "anyOf": [
+ {"type": "array", "items": _ROW_OBJECT_SCHEMA},
+ {"type": "null"},
+ ]
+ },
+ id="anyOf",
+ ),
+ pytest.param(
+ {
+ "oneOf": [
+ {"type": "array", "items": _ROW_OBJECT_SCHEMA},
+ {"type": "null"},
+ ]
+ },
+ id="oneOf",
+ ),
+ pytest.param(
+ {"type": ["array", "null"], "items": _ROW_OBJECT_SCHEMA},
+ id="type-list",
+ ),
+ pytest.param(
+ {"allOf": [{"type": "array", "items": _ROW_OBJECT_SCHEMA}]},
+ id="allOf",
+ ),
+ ],
+)
+async def test_form_urlencoded_nullable_array_of_objects_is_json_encoded(
+ rows_schema: dict[str, Any],
+) -> None:
+ """Nullable/composed array schemas still identify arrays of objects."""
+ spec = _form_urlencoded_spec({"rows": rows_schema}, required=["rows"])
+
+ request = await _submit_and_capture(spec, {"rows": [{"id": 1}]})
+
+ payload = _form_fields(request)["rows"][0]
+ assert "'id'" not in payload
+ assert json.loads(payload) == [{"id": 1}]
+
+
+async def test_form_urlencoded_ref_to_nullable_array_of_objects_is_json_encoded() -> (
+ None
+):
+ """A `$ref` resolving to a nullable array of objects is JSON-encoded."""
+ spec = _form_urlencoded_spec(
+ {"rows": {"$ref": "#/components/schemas/NullableRows"}},
+ required=["rows"],
+ )
+ spec["components"] = {
+ "schemas": {
+ "Row": _ROW_OBJECT_SCHEMA,
+ "NullableRows": {
+ "anyOf": [
+ {"type": "array", "items": {"$ref": "#/components/schemas/Row"}},
+ {"type": "null"},
+ ]
+ },
+ }
+ }
+
+ request = await _submit_and_capture(spec, {"rows": [{"id": 1}]})
+
+ payload = _form_fields(request)["rows"][0]
+ assert "'id'" not in payload
+ assert json.loads(payload) == [{"id": 1}]
+
+
[email protected]("composition", ["oneOf", "anyOf"])
+async def test_form_urlencoded_union_array_uses_matching_branch(
+ composition: str,
+) -> None:
+ """Runtime items choose the union branch instead of any alternative."""
+ rows_schema = {
+ composition: [
+ {"type": "array", "items": _ROW_OBJECT_SCHEMA},
+ {"type": "array", "items": {"type": "string"}},
+ ]
+ }
+ spec = _form_urlencoded_spec({"rows": rows_schema}, required=["rows"])
+
+ scalar_request = await _submit_and_capture(spec, {"rows": ["a", "b"]})
+ # The unused array-of-objects branch must not force JSON into one value.
+ assert _form_fields(scalar_request)["rows"] == ["a", "b"]
+
+ object_request = await _submit_and_capture(spec, {"rows": [{"id": 1}]})
+ payload = _form_fields(object_request)["rows"][0]
+ assert json.loads(payload) == [{"id": 1}]
+
+
+async def test_form_urlencoded_cyclic_component_graph_is_serialized() -> None:
+ """Mutually recursive composition refs terminate instead of recursing."""
+ components = {
+ "A": {
+ "allOf": [
+ {"$ref": "#/components/schemas/B"},
+ {
+ "type": "object",
+ "properties": {"name": {"type": "string"}},
+ },
+ ]
+ },
+ "B": {"$ref": "#/components/schemas/A"},
+ }
+ spec = _form_urlencoded_spec(
+ {"filter": {"$ref": "#/components/schemas/A"}}, required=["filter"]
+ )
+ spec["components"] = {"schemas": components}
+
+ request = await _submit_and_capture(spec, {"filter": {"name": "alice"}})
+
+ payload = _form_fields(request)["filter"][0]
+ assert json.loads(payload) == {"name": "alice"}
+
+
[email protected]("use_ref", [False, True], ids=["inline", "ref"])
+async def test_form_urlencoded_additional_properties_objects_are_json_encoded(
+ use_ref: bool,
+) -> None:
+ """Object map values from additionalProperties are JSON-encoded."""
+ labels_schema = {
+ "type": "object",
+ "additionalProperties": {
+ "type": "object",
+ "properties": {"name": {"type": "string"}},
+ },
+ }
+ if use_ref:
+ spec = _form_body_schema_spec(
+ {"$ref": "#/components/schemas/Labels"}, {"Labels": labels_schema}
+ )
+ else:
+ spec = _form_body_schema_spec(labels_schema)
+
+ request = await _submit_and_capture(spec, {"body": {"team": {"name": "infra"}}})
+
+ payload = _form_fields(request)["team"][0]
+ assert "'name'" not in payload
+ assert json.loads(payload) == {"name": "infra"}
+
+
@pytest.mark.parametrize("openapi_version", ["3.0.3", "3.1.0"])
@pytest.mark.parametrize(
("required", "arguments", "expected"),
diff --git a/tests/utilities/openapi/test_director.py b/tests/utilities/openapi/test_director.py
index 4d71f521d..98231b9a6 100644
--- a/tests/utilities/openapi/test_director.py
+++ b/tests/utilities/openapi/test_director.py
@@ -1459,6 +1459,39 @@ class TestContentTypeDispatch:
body = json.loads(request.content.decode("utf-8"))
assert body == {"name": "widget"}
+ def test_form_urlencoded_allof_additional_properties_json_encoded(self, director):
+ """allOf-wrapped additionalProperties schemas drive JSON encoding."""
+ route = HTTPRoute(
+ path="/submit",
+ method="POST",
+ operation_id="submit",
+ request_body=RequestBodyInfo(
+ required=True,
+ content_schema={
+ "application/x-www-form-urlencoded": {
+ "allOf": [
+ {
+ "type": "object",
+ "additionalProperties": {
+ "type": "object",
+ "properties": {"name": {"type": "string"}},
+ },
+ }
+ ]
+ }
+ },
+ ),
+ parameter_map={
+ "body": {"location": "body", "openapi_name": "body"},
+ },
+ )
+
+ request = director.build(route, {"body": {"team": {"name": "infra"}}})
+
+ body = request.content.decode("utf-8")
+ assert "team=%7B%22name%22%3A+%22infra%22%7D" in body
+ assert "%27name%27" not in body
+
class TestCookieParameters:
"""Test that cookie parameters are properly routed."""