π The fast, Pythonic way to build MCP servers and clients.
Fix multipart string-array default encoding (#5121)
nate nowackf21e00dd47b4
diff --git a/docs/integrations/openapi.mdx b/docs/integrations/openapi.mdxindex 49857ea2f..6bac8da16 100644--- a/docs/integrations/openapi.mdx+++ b/docs/integrations/openapi.mdx@@ -454,6 +454,14 @@ FastMCP handles array parameters according to OpenAPI specifications:Header parameters are automatically converted to strings and included in the HTTP request.+### Multipart Request Bodies++For `multipart/form-data`, non-empty string arrays use one form field per element. Calling a tool with `{"tags": ["a", "b"]}` sends two `tags` fields, so a backend reading repeated fields receives `["a", "b"]`.++This applies when the property's `encoding` is omitted or explicitly uses the defaults: `style: form`, `explode: true`, `contentType: text/plain`, `allowReserved: false`, and no custom headers. Existing scalar fields and binary file parts keep their serialization.++Empty arrays still send one field containing `[]`, and non-string arrays still use their Python string representation. Custom encodings, including `explode: false`, JSON parts, and charset overrides, are not implemented by this fix and retain their existing serialization. If a backend depended on Python list strings for non-empty string arrays, adapt it to read repeated fields.+### JSON Request BodiesDictionary 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`.diff --git a/fastmcp_slim/fastmcp/utilities/openapi/director.py b/fastmcp_slim/fastmcp/utilities/openapi/director.pyindex 7f42184f4..6910ad624 100644--- a/fastmcp_slim/fastmcp/utilities/openapi/director.py+++ b/fastmcp_slim/fastmcp/utilities/openapi/director.py@@ -27,6 +27,20 @@ def _query_scalar_to_str(value: Any) -> str:return str(value)+def _uses_default_multipart_encoding(encoding: dict[str, Any]) -> bool:+ """Explicit defaults serialize like omitted encoding; overrides stay unchanged."""+ defaults = {+ "style": "form",+ "explode": True,+ "contentType": "text/plain",+ "allowReserved": False,+ "headers": {},+ }+ return all(+ key in defaults and value == defaults[key] for key, value in encoding.items()+ )++class RequestDirector:"""Builds httpx2.Request objects from HTTPRoute and arguments using openapi-core."""@@ -97,7 +111,7 @@ class RequestDirector:# Step 6: Handle request body β dispatch on declared content type.# httpx body kwargs (json, content, data, files) are mutually exclusive# but all accept None, so we set exactly one and pass all to Request().- files: dict[str, Any] | None = None+ files: list[tuple[str, Any]] | None = Nonedata: dict[str, Any] | None = Noneif body is not None:if declared_content_type == "multipart/form-data" and isinstance(@@ -107,17 +121,29 @@ class RequestDirector:# treats them as form fields. Scalars must be stringified# because httpx rejects non-string/bytes values in files=.# Use _query_scalar_to_str for booleans (true/false, not True/False).- files = {}+ files = []+ encoding = (+ route.request_body.encoding.get(raw_content_type, {})+ if route.request_body and raw_content_type is not None+ else {}+ )for k, v in body.items():- if isinstance(v, tuple):- files[k] = v+ if (+ isinstance(v, list)+ and v+ and all(isinstance(item, str) for item in v)+ and _uses_default_multipart_encoding(encoding.get(k, {}))+ ):+ files.extend((k, (None, item)) for item in v)+ elif isinstance(v, tuple):+ files.append((k, v))elif isinstance(v, bytes | io.IOBase):# bytes and file-like objects are passed directly so# httpx can transmit them as binary parts without# stringifying to their Python repr.- files[k] = (None, v)+ files.append((k, (None, v)))else:- files[k] = (None, _query_scalar_to_str(v))+ files.append((k, (None, _query_scalar_to_str(v))))elif (declared_content_type == "application/x-www-form-urlencoded"and isinstance(body, dict)diff --git a/fastmcp_slim/fastmcp/utilities/openapi/models.py b/fastmcp_slim/fastmcp/utilities/openapi/models.pyindex 03d2eb68d..5b6fb4c63 100644--- a/fastmcp_slim/fastmcp/utilities/openapi/models.py+++ b/fastmcp_slim/fastmcp/utilities/openapi/models.py@@ -34,6 +34,7 @@ class RequestBodyInfo(FastMCPBaseModel):default_factory=dict) # Key: media typedescription: str | None = None+ encoding: dict[str, dict[str, Any]] = Field(default_factory=dict)class ResponseInfo(FastMCPBaseModel):diff --git a/fastmcp_slim/fastmcp/utilities/openapi/parser.py b/fastmcp_slim/fastmcp/utilities/openapi/parser.pyindex 89f6a46b4..e329d198f 100644--- a/fastmcp_slim/fastmcp/utilities/openapi/parser.py+++ b/fastmcp_slim/fastmcp/utilities/openapi/parser.py@@ -372,6 +372,11 @@ class OpenAPIParser(# Extract content schemasif hasattr(request_body, "content") and request_body.content:for media_type_str, media_type_obj in request_body.content.items():+ if media_type_obj and media_type_obj.encoding:+ request_body_info.encoding[media_type_str] = {+ name: value.model_dump(by_alias=True, exclude_unset=True)+ for name, value in media_type_obj.encoding.items()+ }if (media_type_objand hasattr(media_type_obj, "media_type_schema")diff --git a/tests/server/providers/openapi/test_multipart_array_defaults.py b/tests/server/providers/openapi/test_multipart_array_defaults.pynew file mode 100644index 000000000..75e24bb64--- /dev/null+++ b/tests/server/providers/openapi/test_multipart_array_defaults.py@@ -0,0 +1,194 @@+"""Multipart string arrays arrive as repeated form fields."""++import io+from email.parser import BytesParser+from email.policy import default+from typing import Any++import httpx2+import pytest+from fastapi import FastAPI, Request+from jsonschema_path import SchemaPath++from fastmcp import Client, FastMCP+from fastmcp.utilities.openapi.director import RequestDirector+from fastmcp.utilities.openapi.models import HTTPRoute, RequestBodyInfo++[email protected]("include_label", [False, True])[email protected]("openapi_version", ["3.0.3", "3.1.0"])[email protected]("tags", [["a", "b"], ["a"], [], ["δΈζ", "a&b"]])+ "encoding,repeat",+ [+ (None, True),+ ({}, True),+ ({"explode": True}, True),+ ({"style": "form"}, True),+ ({"contentType": "text/plain"}, True),+ (+ {+ "style": "form",+ "explode": True,+ "contentType": "text/plain",+ "allowReserved": False,+ "headers": {},+ },+ True,+ ),+ ({"explode": False}, False),+ ({"contentType": "application/json"}, False),+ ({"contentType": "text/plain; charset=iso-8859-1"}, False),+ ({"headers": {"X-Part": {"schema": {"type": "string"}}}}, False),+ ],+)+async def test_multipart_string_array_defaults(+ include_label: bool,+ openapi_version: str,+ tags: list[str],+ encoding: dict[str, Any] | None,+ repeat: bool,+):+ app = FastAPI()++ @app.post("/items")+ async def receive(request: Request):+ form = await request.form()+ assert request.headers["content-type"].startswith(+ "multipart/form-data; boundary="+ )+ return {"tags": form.getlist("tags"), "label": form.get("label")}++ media: dict[str, Any] = {+ "schema": {+ "type": "object",+ "properties": {+ "tags": {"type": "array", "items": {"type": "string"}},+ "label": {"type": "string"},+ },+ "required": ["tags", "label"],+ }+ }+ if not include_label:+ del media["schema"]["properties"]["label"]+ media["schema"]["required"].remove("label")+ if encoding is not None:+ media["encoding"] = {"tags": encoding}+ spec = {+ "openapi": openapi_version,+ "info": {"title": "Multipart", "version": "1"},+ "paths": {+ "/items": {+ "post": {+ "operationId": "submit",+ "requestBody": {+ "required": True,+ "content": {"multipart/form-data": media},+ },+ "responses": {"200": {"description": "OK"}},+ }+ }+ },+ }+ async with httpx2.AsyncClient(+ base_url="http://test", transport=httpx2.ASGITransport(app=app)+ ) as http:+ server = FastMCP.from_openapi(openapi_spec=spec, client=http)+ async with Client(server) as client:+ arguments: dict[str, Any] = {"tags": tags}+ if include_label:+ arguments["label"] = "keep"+ result = await client.call_tool("submit", arguments)+ # Custom encodings keep their existing wire format.+ assert result.structured_content == {+ "tags": tags if tags and repeat else [str(tags)],+ "label": "keep" if include_label else None,+ }+++def test_only_empty_array_preserves_multipart_content_type() -> None:+ route = HTTPRoute(+ path="/items",+ method="POST",+ request_body=RequestBodyInfo(+ content_schema={+ "multipart/form-data": {+ "type": "object",+ "properties": {+ "tags": {"type": "array", "items": {"type": "string"}}+ },+ }+ }+ ),+ parameter_map={"tags": {"location": "body", "openapi_name": "tags"}},+ )+ request = RequestDirector(SchemaPath.from_dict({})).build(+ route, {"tags": []}, "http://test"+ )+ message = BytesParser(policy=default).parsebytes(+ f"Content-Type: {request.headers['content-type']}\r\n\r\n".encode()+ + request.read()+ )+ assert message.get_content_type() == "multipart/form-data"+ parts = list(message.iter_parts())+ assert len(parts) == 1+ assert parts[0].get_payload(decode=True) == b"[]"+++ "kind",+ ["tuple", "bytes", "stream", "object", "nested", "integers", "mixed", "boolean"],+)+def test_multipart_arrays_preserve_other_parts(kind: str) -> None:+ values = {+ "tuple": ("sample.txt", b"payload", "text/plain"),+ "bytes": b"payload",+ "stream": io.BytesIO(b"payload"),+ "object": {"name": "alice"},+ "nested": [["a"]],+ "integers": [1, 2],+ "mixed": ["a", 2],+ "boolean": True,+ }+ route = HTTPRoute(+ path="/items",+ method="POST",+ request_body=RequestBodyInfo(+ content_schema={+ "multipart/form-data": {+ "type": "object",+ "properties": {+ "tags": {"type": "array", "items": {"type": "string"}},+ "other": {},+ },+ }+ }+ ),+ parameter_map={+ name: {"location": "body", "openapi_name": name}+ for name in ["tags", "other"]+ },+ )+ try:+ request = RequestDirector(SchemaPath.from_dict({})).build(+ route, {"tags": ["a", "b"], "other": values[kind]}, "http://test"+ )+ raw = request.read()+ message = BytesParser(policy=default).parsebytes(+ f"Content-Type: {request.headers['content-type']}\r\n\r\n".encode() + raw+ )+ parts = list(message.iter_parts())+ assert [+ part.get_param("name", header="content-disposition") for part in parts+ ] == ["tags", "tags", "other"]+ assert [part.get_payload(decode=True) for part in parts[:2]] == [b"a", b"b"]+ expected = (+ b"payload"+ if kind in {"tuple", "bytes", "stream"}+ else ("true" if kind == "boolean" else str(values[kind])).encode()+ )+ assert parts[2].get_payload(decode=True) == expected+ if kind == "tuple":+ assert parts[2].get_filename() == "sample.txt"+ finally:+ values["stream"].close()