Skip to content

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

Fix OpenAPI query explode defaults (#5065)

nate nowackcecd26e1fbec
diff --git a/docs/integrations/openapi.mdx b/docs/integrations/openapi.mdx
index 4769f6576..52538781a 100644
--- a/docs/integrations/openapi.mdx
+++ b/docs/integrations/openapi.mdx
@@ -436,14 +436,14 @@ await client.call_tool("get_user", {"user_id": None})
FastMCP handles array parameters according to OpenAPI specifications:
-- **Query arrays**: Serialized based on the `explode` parameter (default: `True`)
+- **Query arrays**: Serialized based on `style` and `explode`. When omitted, `explode` defaults to `True` for `form` (the default query style) and `False` for other styles. With `explode=False`, `form` uses commas, `pipeDelimited` uses pipes, and `spaceDelimited` uses spaces.
- **Path arrays**: Serialized as comma-separated values (OpenAPI 'simple' style)
```python
-# Query array with explode=true (default)
+# Query array with style=form, explode=true (defaults)
# ?tags=red&tags=blue&tags=green
-# Query array with explode=false
+# Query array with style=form, explode=false
# ?tags=red,blue,green
# Path array (always comma-separated)
@@ -469,4 +469,4 @@ await client.call_tool("create_pet", {
The discriminator stays required; every variant field is optional, because only one variant applies to any given call.
-This trades local strictness for a schema models complete accurately. The generated schema permits any combination of variant fields, so sending `packSize` with `petType: "cat"` passes FastMCP's validation and is rejected by the API itself, exactly as it would be for any other HTTP client. Where two variants declare the same field differently, the declarations are combined with `anyOf` so that neither variant's constraints are advertised as applying to both.
\ No newline at end of file
+This trades local strictness for a schema models complete accurately. The generated schema permits any combination of variant fields, so sending `packSize` with `petType: "cat"` passes FastMCP's validation and is rejected by the API itself, exactly as it would be for any other HTTP client. Where two variants declare the same field differently, the declarations are combined with `anyOf` so that neither variant's constraints are advertised as applying to both.
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/director.py b/fastmcp_slim/fastmcp/utilities/openapi/director.py
index 2f3e11ae2..bb6bd206c 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/director.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/director.py
@@ -290,7 +290,9 @@ class RequestDirector:
Serialize query parameter values according to their OpenAPI style/explode settings.
By default (style=form, explode=true), list values are passed through as-is
- so httpx repeats the key (e.g. values=a&values=b). When explode=false,
+ so httpx repeats the key (e.g. values=a&values=b). For pipeDelimited and
+ spaceDelimited arrays, omitted explode defaults to false. Object values
+ retain the existing default of true. When explode=false,
list values are joined with the style-appropriate delimiter:
- form (default): comma (values=a,b)
- pipeDelimited: pipe (values=a|b)
@@ -308,7 +310,14 @@ class RequestDirector:
for key, value in query_params.items():
param_info = param_lookup.get(key)
if param_info is not None:
+ style = param_info.style or "form"
explode = param_info.explode if param_info.explode is not None else True
+ if (
+ param_info.explode is None
+ and isinstance(value, list)
+ and style in {"pipeDelimited", "spaceDelimited"}
+ ):
+ explode = False
if isinstance(value, dict):
if not value:
continue
@@ -321,7 +330,6 @@ class RequestDirector:
property_name = f"{key}[{property_name}]"
serialized[property_name] = _query_scalar_to_str(v)
else:
- style = param_info.style or "form"
delimiter = self._STYLE_DELIMITERS.get(style, ",")
# form,explode=false on objects: key,value pairs
# e.g. {"R": 100, "G": 200} β†’ "R,100,G,200"
@@ -332,7 +340,6 @@ class RequestDirector:
serialized[key] = delimiter.join(parts)
continue
if not explode:
- style = param_info.style or "form"
delimiter = self._STYLE_DELIMITERS.get(style, ",")
if isinstance(value, list):
if not value:
diff --git a/tests/server/providers/openapi/test_query_array_defaults.py b/tests/server/providers/openapi/test_query_array_defaults.py
new file mode 100644
index 000000000..771996113
--- /dev/null
+++ b/tests/server/providers/openapi/test_query_array_defaults.py
@@ -0,0 +1,103 @@
+"""Query array serialization follows the declared OpenAPI style."""
+
+from typing import Any
+
+import httpx2
+import pytest
+from jsonschema_path import SchemaPath
+
+from fastmcp import Client, FastMCP
+from fastmcp.utilities.openapi.director import RequestDirector
+from fastmcp.utilities.openapi.models import HTTPRoute, ParameterInfo
+
+
+ "style,explode,expected",
+ [
+ (None, None, [("ids", "a"), ("ids", "b")]),
+ ("form", None, [("ids", "a"), ("ids", "b")]),
+ ("pipeDelimited", None, [("ids", "a|b")]),
+ ("spaceDelimited", None, [("ids", "a b")]),
+ ("form", False, [("ids", "a,b")]),
+ ("pipeDelimited", False, [("ids", "a|b")]),
+ ("spaceDelimited", False, [("ids", "a b")]),
+ ("form", True, [("ids", "a"), ("ids", "b")]),
+ ("pipeDelimited", True, [("ids", "a"), ("ids", "b")]),
+ ("spaceDelimited", True, [("ids", "a"), ("ids", "b")]),
+ ],
+)
+async def test_query_array_serialization(
+ style: str | None,
+ explode: bool | None,
+ expected: list[tuple[str, str]],
+) -> None:
+ parameter: dict[str, Any] = {
+ "name": "ids",
+ "in": "query",
+ "required": True,
+ "schema": {"type": "array", "items": {"type": "string"}},
+ }
+ if style is not None:
+ parameter["style"] = style
+ if explode is not None:
+ parameter["explode"] = explode
+ spec = {
+ "openapi": "3.1.0",
+ "info": {"title": "Query arrays", "version": "1"},
+ "paths": {
+ "/items": {
+ "get": {
+ "operationId": "list_items",
+ "parameters": [parameter],
+ "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.test", 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("list_items", {"ids": ["a", "b"]})
+
+ assert len(requests) == 1
+ assert requests[0].url.params.multi_items() == expected
+
+
+ "style,expected",
+ [
+ ("form", [("name", "alice")]),
+ ("deepObject", [("filter[name]", "alice")]),
+ ("pipeDelimited", [("name", "alice")]),
+ ("spaceDelimited", [("name", "alice")]),
+ ],
+)
+def test_object_query_defaults_preserve_existing_behavior(
+ style: str, expected: list[tuple[str, str]]
+) -> None:
+ route = HTTPRoute(
+ path="/items",
+ method="GET",
+ parameters=[
+ ParameterInfo(
+ name="filter",
+ location="query",
+ required=True,
+ schema={"type": "object", "properties": {"name": {"type": "string"}}},
+ style=style,
+ )
+ ],
+ parameter_map={"filter": {"location": "query", "openapi_name": "filter"}},
+ )
+ request = RequestDirector(SchemaPath.from_dict({})).build(
+ route, {"filter": {"name": "alice"}}, "https://example.test"
+ )
+ assert request.url.params.multi_items() == expected