Skip to content

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

fix(openapi): preserve explicit null in nullable JSON body properties (#5633)

mumubirdea8bb322b08c
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/director.py b/fastmcp_slim/fastmcp/utilities/openapi/director.py
index 0a321939b..6c99747b9 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/director.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/director.py
@@ -8,6 +8,8 @@ from typing import Any, ClassVar
from urllib.parse import quote, unquote
import httpx2
+from jsonschema import Draft202012Validator
+from jsonschema.protocols import Validator
from jsonschema_path import SchemaPath
from fastmcp.utilities.logging import get_logger
@@ -285,11 +287,10 @@ class RequestDirector:
body_props = {}
route, parameter_map = _prepare_parameter_map(route)
+ null_validator: Validator | None = None
+ null_properties: dict[str, Any] = {}
for arg_name, value in flat_args.items():
- if value is None:
- continue # Skip None values for optional parameters
-
if arg_name not in parameter_map:
logger.warning(
f"Argument '{arg_name}' not found in parameter map for {route.operation_id}"
@@ -300,6 +301,28 @@ class RequestDirector:
location = mapping["location"]
openapi_name = mapping["openapi_name"]
+ if value is None:
+ # Only JSON body properties have a null representation. Consult
+ # the normalized input schema, including its reference definitions,
+ # rather than interpreting raw OpenAPI nullability a second time.
+ if location != "body" or not route.request_body:
+ continue
+ content_type = next(iter(route.request_body.content_schema), "")
+ media_type = content_type.split(";")[0].strip().lower()
+ if media_type != "application/json" and not media_type.endswith(
+ "+json"
+ ):
+ continue
+ if null_validator is None:
+ schema = route.flat_param_schema
+ if not schema:
+ schema, _ = _combine_schemas_and_map_params(route)
+ null_validator = Draft202012Validator(schema)
+ null_properties = schema.get("properties", {})
+ property_schema = null_properties.get(arg_name, False)
+ if not null_validator.evolve(schema=property_schema).is_valid(None):
+ continue
+
if location == "path":
path_params[openapi_name] = value
elif location == "query":
diff --git a/fastmcp_slim/pyproject.toml b/fastmcp_slim/pyproject.toml
index 0d4624dcc..c98d79c6a 100644
--- a/fastmcp_slim/pyproject.toml
+++ b/fastmcp_slim/pyproject.toml
@@ -101,6 +101,7 @@ server = [
"cyclopts>=4.0.0",
"griffelib>=2.0.0",
"jsonref>=1.1.0",
+ "jsonschema>=4.20.0",
"jsonschema-path>=0.3.4",
"joserfc>=1.5.0",
"openapi-pydantic>=0.6.0",
diff --git a/tests/utilities/openapi/test_null_body.py b/tests/utilities/openapi/test_null_body.py
new file mode 100644
index 000000000..03e10e1aa
--- /dev/null
+++ b/tests/utilities/openapi/test_null_body.py
@@ -0,0 +1,119 @@
+"""Explicit null body properties must survive JSON request construction."""
+
+import json
+from typing import Any
+
+import pytest
+from jsonschema_path import SchemaPath
+
+from fastmcp.utilities.openapi.director import RequestDirector
+from fastmcp.utilities.openapi.parser import parse_openapi_to_http_routes
+
+
+ ("version", "property_schema"),
+ [
+ ("3.0.3", {"type": "string", "nullable": True}),
+ ("3.1.0", {"type": ["string", "null"]}),
+ ("3.1.0", {"anyOf": [{"type": "string"}, {"type": "null"}]}),
+ ("3.1.0", {"oneOf": [{"type": "string"}, {"type": "null"}]}),
+ ("3.1.0", {"$ref": "#/components/schemas/NullableString"}),
+ ],
+)
[email protected]("with_name", [False, True])
+ "media_type", ["application/json", "application/merge-patch+json"]
+)
+def test_explicit_json_null(
+ version: str, property_schema: dict[str, Any], with_name: bool, media_type: str
+) -> None:
+ spec = _spec(version, property_schema, media_type)
+ route = parse_openapi_to_http_routes(spec)[0]
+ director = RequestDirector(SchemaPath.from_dict(spec))
+ arguments: dict[str, Any] = {"folder_id": None, "filter": None}
+ expected: dict[str, Any] = {"folder_id": None}
+ if with_name:
+ arguments["name"] = "report.pdf"
+ expected["name"] = "report.pdf"
+ request = director.build(route, arguments)
+ assert json.loads(request.content) == expected
+ assert request.headers["content-type"] == media_type
+ assert "filter" not in request.url.params
+
+ omitted = director.build(route, {"name": "report.pdf"})
+ assert json.loads(omitted.content) == {"name": "report.pdf"}
+
+
+ "media_type",
+ ["multipart/form-data", "application/x-www-form-urlencoded", "application/json"],
+)
+def test_null_not_allowed_by_encoding_or_schema(media_type: str) -> None:
+ property_schema = (
+ {"type": "string"}
+ if media_type == "application/json"
+ else {"type": ["string", "null"]}
+ )
+ spec = _spec("3.1.0", property_schema, media_type)
+ route = parse_openapi_to_http_routes(spec)[0]
+ director = RequestDirector(SchemaPath.from_dict(spec))
+ request = director.build(route, {"folder_id": None})
+ assert request.content == b""
+
+
+def test_null_uses_selected_media_type() -> None:
+ spec = _spec("3.1.0", {"type": "string"}, "application/json")
+ content = spec["paths"]["/files"]["patch"]["requestBody"]["content"]
+ content["application/merge-patch+json"] = {
+ "schema": {
+ "type": "object",
+ "properties": {"folder_id": {"type": ["string", "null"]}},
+ }
+ }
+ route = parse_openapi_to_http_routes(spec)[0]
+ request = RequestDirector(SchemaPath.from_dict(spec)).build(
+ route, {"folder_id": None}
+ )
+ assert request.content == b""
+
+
+def _spec(
+ version: str, property_schema: dict[str, Any], media_type: str
+) -> dict[str, Any]:
+ return {
+ "openapi": version,
+ "info": {"title": "Files", "version": "1.0"},
+ "components": {
+ "schemas": {
+ "NullableString": (
+ {"type": "string", "nullable": True}
+ if version.startswith("3.0")
+ else {"type": ["string", "null"]}
+ )
+ }
+ },
+ "paths": {
+ "/files": {
+ "patch": {
+ "operationId": "update_file",
+ "parameters": [
+ {"name": "filter", "in": "query", "schema": {"type": "string"}}
+ ],
+ "requestBody": {
+ "content": {
+ media_type: {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "folder_id": property_schema,
+ },
+ }
+ }
+ }
+ },
+ "responses": {"200": {"description": "OK"}},
+ }
+ }
+ },
+ }
diff --git a/uv.lock b/uv.lock
index db7df8b48..95831100f 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1128,6 +1128,7 @@ server = [
{ name = "httpx2" },
{ name = "joserfc" },
{ name = "jsonref" },
+ { name = "jsonschema" },
{ name = "jsonschema-path" },
{ name = "mcp" },
{ name = "openapi-pydantic" },
@@ -1169,6 +1170,7 @@ requires-dist = [
{ name = "joserfc", marker = "extra == 'server'", specifier = ">=1.5.0" },
{ name = "jsonref", marker = "extra == 'gemini'", specifier = ">=1.1.0" },
{ name = "jsonref", marker = "extra == 'server'", specifier = ">=1.1.0" },
+ { name = "jsonschema", marker = "extra == 'server'", specifier = ">=4.20.0" },
{ name = "jsonschema-path", marker = "extra == 'server'", specifier = ">=0.3.4" },
{ name = "mcp", marker = "extra == 'client'", specifier = ">=2.3.0,<3.0.0" },
{ name = "mcp", marker = "extra == 'mcp'", specifier = ">=2.3.0,<3.0.0" },