π The fast, Pythonic way to build MCP servers and clients.
Keep referenced body fields when a request body schema adds sibling properties (#5440)
Jeremiah Lowin0ac49deec724
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/director.py b/fastmcp_slim/fastmcp/utilities/openapi/director.pyindex 8f6113da4..84cf9a787 100644--- a/fastmcp_slim/fastmcp/utilities/openapi/director.py+++ b/fastmcp_slim/fastmcp/utilities/openapi/director.py@@ -12,7 +12,7 @@ from jsonschema_path import SchemaPathfrom fastmcp.utilities.logging import get_loggerfrom .models import HTTPRoute, ParameterInfo-from .schemas import _combine_schemas_and_map_params+from .schemas import _combine_schemas_and_map_params, _ref_is_mergeable_objectlogger = get_logger(__name__)@@ -292,7 +292,11 @@ class RequestDirector:body_schema = route.request_body.content_schema[content_type]# Only named properties are flattened into individual arguments.- if isinstance(body_schema, dict) and body_schema.get("properties"):+ if (+ isinstance(body_schema, dict)+ and body_schema.get("properties")+ and _ref_is_mergeable_object(body_schema, route.request_schemas)+ ):body = body_propselif len(body_props) == 1:# Free-form objects, arrays, and primitives use a singlediff --git a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py b/fastmcp_slim/fastmcp/utilities/openapi/schemas.pyindex 7f08d6a94..4527347b1 100644--- a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py+++ b/fastmcp_slim/fastmcp/utilities/openapi/schemas.py@@ -108,7 +108,7 @@ def _replace_ref_with_defs(f"FastMCP only supports local schema references starting with '#/'. "f"Please include all schema definitions within the OpenAPI document.")- elif properties := schema.get("properties"):+ if properties := schema.get("properties"):if "$ref" in properties:schema["properties"] = _replace_ref_with_defs(properties)else:@@ -116,7 +116,7 @@ def _replace_ref_with_defs(prop_name: _replace_ref_with_defs(prop_schema)for prop_name, prop_schema in properties.items()}- elif item_schema := schema.get("items"):+ if item_schema := schema.get("items"):schema["items"] = _replace_ref_with_defs(item_schema)if "prefixItems" in schema:schema["prefixItems"] = [@@ -248,7 +248,9 @@ def _allof_members(members = _allof_members(referenced_schema, schema_defs, resolving | {name})- return members + ([siblings] if siblings else [])+ if siblings:+ members.extend(_allof_members(siblings, schema_defs, resolving))+ return membersbreakall_of = schema.get("allOf")@@ -264,6 +266,60 @@ def _allof_members(return [schema]+# Keywords the properties/required merge represents, or that only annotate.+# A discriminator is carried through and expanded by+# _flatten_discriminator_subtypes, which also accounts for its oneOf.+_MERGEABLE_OBJECT_KEYWORDS = frozenset(+ {+ "type",+ "properties",+ "required",+ "title",+ "description",+ "example",+ "examples",+ "deprecated",+ "discriminator",+ "oneOf",+ }+)+++def _is_mergeable_object(schema: dict[str, Any]) -> bool:+ """Whether flattening *schema* into ``properties``/``required`` loses nothing.++ Only keywords the merge fully represents are allowed; any other constraint+ (``anyOf``, ``not``, ``patternProperties``, ``additionalProperties``, ...)+ would vanish from the merged schema, so the ``$ref`` is kept instead. A+ ``oneOf`` is representable only beside a discriminator mapping, whose+ subtype fields are flattened in afterwards.+ """+ if schema.get("type", "object") != "object":+ return False+ if not set(schema) <= _MERGEABLE_OBJECT_KEYWORDS:+ return False+ if "oneOf" in schema:+ discriminator = schema.get("discriminator")+ return (+ isinstance(discriminator, dict)+ and isinstance(discriminator.get("propertyName"), str)+ and isinstance(discriminator.get("mapping"), dict)+ )+ return True+++def _ref_is_mergeable_object(+ schema: dict[str, Any], schema_defs: dict[str, Any]+) -> bool:+ """Whether *schema*'s ``$ref`` (if any) can be dropped by a property merge."""+ if "$ref" not in schema:+ return True+ return all(+ _is_mergeable_object(member)+ for member in _allof_members({"$ref": schema["$ref"]}, schema_defs)+ )++def _discriminator_target_name(target: str) -> str | None:"""Resolve a ``discriminator.mapping`` value to a local schema name.@@ -423,25 +479,59 @@ def _combine_schemas_and_map_params(if route.request_body.description and not body_schema.get("description"):body_schema["description"] = route.request_body.description- # Handle allOf at the top level by merging all schemas- if "allOf" in body_schema and isinstance(body_schema["allOf"], list):+ # Handle allOf at the top level by merging all schemas. A $ref that+ # sits beside its own properties is merged the same way; there, a+ # property defined by both sides must satisfy both definitions.+ has_all_of = isinstance(body_schema.get("allOf"), list)+ ref_is_object = _ref_is_mergeable_object(body_schema, route.request_schemas)+ has_ref_with_properties = (+ "$ref" in body_schema+ and isinstance(body_schema.get("properties"), dict)+ and ref_is_object+ )+ if has_all_of or has_ref_with_properties:merged_props = {}merged_required = []for sub_schema in _allof_members(body_schema, route.request_schemas):# Merge properties- if "properties" in sub_schema:- merged_props.update(sub_schema["properties"])+ for prop_name, prop_schema in sub_schema.get("properties", {}).items():+ if (+ not has_all_of+ and prop_name in merged_props+ and merged_props[prop_name] != prop_schema+ ):+ prop_schema = {"allOf": [merged_props[prop_name], prop_schema]}+ merged_props[prop_name] = prop_schema# Merge required fieldsif "required" in sub_schema:merged_required.extend(sub_schema["required"])+ # The referenced schema's discriminator is kept so its subtypes+ # are flattened below; the sibling schema comes last and wins.+ if not has_all_of and isinstance(sub_schema.get("discriminator"), dict):+ body_schema["discriminator"] = sub_schema["discriminator"]# Update body_schema with merged propertiesbody_schema["properties"] = merged_propsif merged_required:body_schema["required"] = list(dict.fromkeys(merged_required))- # Remove the allOf since we've merged it+ # The $ref is dropped only when the merge represents the whole+ # referenced schema; otherwise it keeps carrying the target's type.body_schema.pop("allOf", None)+ if ref_is_object:+ body_schema.pop("$ref", None)++ # A kept $ref is paired with its siblings through allOf: resolving a+ # $ref that has siblings lets the siblings overwrite the target's keywords.+ if not ref_is_object:+ ref = body_schema.pop("$ref")+ if not body_schema.get("properties"):+ body_schema.pop("properties", None)+ body_schema = (+ {"allOf": [{"$ref": ref}, body_schema]}+ if body_schema+ else {"$ref": ref}+ )# Merge discriminated subtype fields in as optional. The discriminator# itself is dropped: its mapping points at definitions that are pruned@@ -454,7 +544,9 @@ def _combine_schemas_and_map_params(body_schema["properties"] = flattened_propsbody_schema.pop("discriminator", None)- body_props = body_schema.get("properties", {})+ # A kept $ref still carries constraints the properties cannot express,+ # so the whole schema is exposed as one argument.+ body_props = {} if not ref_is_object else body_schema.get("properties", {})# Detect collisions: parameters that exist in multiple non-body locations# or between body and path/query/header/cookie.diff --git a/tests/server/providers/openapi/test_body_ref_siblings.py b/tests/server/providers/openapi/test_body_ref_siblings.pynew file mode 100644index 000000000..ed54b8289--- /dev/null+++ b/tests/server/providers/openapi/test_body_ref_siblings.py@@ -0,0 +1,309 @@+"""Request body schemas that combine a $ref with sibling properties."""++import json+from typing import Any++import httpx2++from fastmcp import Client, FastMCP+++def build_spec(+ body_schema: dict[str, Any], components: dict[str, Any]+) -> dict[str, Any]:+ return {+ "openapi": "3.1.0",+ "info": {"title": "API", "version": "1"},+ "paths": {+ "/things": {+ "post": {+ "operationId": "make_thing",+ "requestBody": {+ "required": True,+ "content": {"application/json": {"schema": body_schema}},+ },+ "responses": {"200": {"description": "OK"}},+ }+ }+ },+ "components": {"schemas": components},+ }+++async def call_make_thing(+ spec: dict[str, Any], arguments: dict[str, Any]+) -> tuple[dict[str, Any], Any]:+ seen: list[Any] = []++ def handler(request: httpx2.Request) -> httpx2.Response:+ seen.append(json.loads(request.content or b"null"))+ return httpx2.Response(200, json={"ok": True})++ async with httpx2.AsyncClient(+ base_url="https://api.example.com",+ transport=httpx2.MockTransport(handler),+ ) as http:+ server = FastMCP.from_openapi(openapi_spec=spec, client=http)+ async with Client(server) as client:+ tool = (await client.list_tools())[0]+ await client.call_tool("make_thing", arguments)+ return tool.input_schema, seen[0]+++BASE = {+ "type": "object",+ "properties": {"name": {"type": "string"}},+ "required": ["name"],+}+++async def test_ref_with_sibling_properties_advertises_both_fields():+ spec = build_spec(+ {+ "$ref": "#/components/schemas/Base",+ "properties": {"local": {"type": "string"}},+ },+ {"Base": BASE},+ )+ schema, _ = await call_make_thing(spec, {"name": "n", "local": "l"})+ assert set(schema["properties"]) == {"name", "local"}+++async def test_ref_with_sibling_properties_sends_both_fields():+ spec = build_spec(+ {+ "$ref": "#/components/schemas/Base",+ "properties": {"local": {"type": "string"}},+ },+ {"Base": BASE},+ )+ _, body = await call_make_thing(spec, {"name": "n", "local": "l"})+ assert body == {"name": "n", "local": "l"}+++async def test_ref_with_sibling_properties_merges_required():+ spec = build_spec(+ {+ "$ref": "#/components/schemas/Base",+ "properties": {"local": {"type": "string"}},+ "required": ["local"],+ },+ {"Base": BASE},+ )+ schema, _ = await call_make_thing(spec, {"name": "n", "local": "l"})+ assert sorted(schema["required"]) == ["local", "name"]+++async def test_overlapping_property_applies_both_schemas():+ spec = build_spec(+ {+ "$ref": "#/components/schemas/Base",+ "properties": {"name": {"type": "string", "minLength": 2}},+ },+ {"Base": BASE},+ )+ schema, body = await call_make_thing(spec, {"name": "nn"})+ assert schema["properties"]["name"] == {+ "allOf": [{"type": "string"}, {"type": "string", "minLength": 2}]+ }+ assert body == {"name": "nn"}+++async def test_identical_overlapping_property_stays_flat():+ spec = build_spec(+ {+ "$ref": "#/components/schemas/Base",+ "properties": {"name": {"type": "string"}},+ },+ {"Base": BASE},+ )+ schema, _ = await call_make_thing(spec, {"name": "n"})+ assert schema["properties"]["name"] == {"type": "string"}+++async def test_reference_inside_sibling_property_is_resolved():+ spec = build_spec(+ {+ "$ref": "#/components/schemas/Base",+ "properties": {"child": {"$ref": "#/components/schemas/Child"}},+ },+ {+ "Base": BASE,+ "Child": {"type": "object", "properties": {"id": {"type": "integer"}}},+ },+ )+ schema, body = await call_make_thing(spec, {"name": "n", "child": {"id": 1}})+ assert schema["properties"]["child"]["properties"] == {"id": {"type": "integer"}}+ assert body == {"name": "n", "child": {"id": 1}}+++async def test_ref_chain_with_sibling_properties_sends_all_fields():+ spec = build_spec(+ {+ "$ref": "#/components/schemas/Middle",+ "properties": {"local": {"type": "string"}},+ },+ {+ "Base": BASE,+ "Middle": {+ "$ref": "#/components/schemas/Base",+ "properties": {"middle": {"type": "string"}},+ },+ },+ )+ schema, body = await call_make_thing(+ spec, {"name": "n", "middle": "m", "local": "l"}+ )+ assert set(schema["properties"]) == {"name", "middle", "local"}+ assert body == {"name": "n", "middle": "m", "local": "l"}+++async def test_nested_reference_in_referenced_property_is_resolved():+ spec = build_spec(+ {+ "$ref": "#/components/schemas/Base",+ "properties": {"local": {"type": "string"}},+ },+ {+ "Base": {+ "type": "object",+ "properties": {"child": {"$ref": "#/components/schemas/Child"}},+ },+ "Child": {"type": "object", "properties": {"id": {"type": "integer"}}},+ },+ )+ schema, body = await call_make_thing(spec, {"child": {"id": 1}, "local": "l"})+ assert schema["properties"]["child"]["properties"] == {"id": {"type": "integer"}}+ assert body == {"child": {"id": 1}, "local": "l"}+++async def test_ref_without_siblings_exposes_referenced_fields():+ spec = build_spec({"$ref": "#/components/schemas/Base"}, {"Base": BASE})+ schema, body = await call_make_thing(spec, {"name": "n"})+ assert set(schema["properties"]) == {"name"}+ assert schema["required"] == ["name"]+ assert body == {"name": "n"}+++PET_COMPONENTS = {+ "Pet": {+ "type": "object",+ "required": ["petType"],+ "properties": {"petType": {"type": "string"}},+ "oneOf": [+ {"$ref": "#/components/schemas/Cat"},+ {"$ref": "#/components/schemas/Dog"},+ ],+ "discriminator": {+ "propertyName": "petType",+ "mapping": {+ "cat": "#/components/schemas/Cat",+ "dog": "#/components/schemas/Dog",+ },+ },+ },+ "Cat": {+ "type": "object",+ "properties": {"meowVolume": {"type": "integer"}},+ },+ "Dog": {+ "type": "object",+ "properties": {"barkVolume": {"type": "integer"}},+ },+}++PET_BODY = {+ "$ref": "#/components/schemas/Pet",+ "properties": {"owner": {"type": "string"}},+}+++async def test_ref_with_discriminator_advertises_subtype_fields():+ spec = build_spec(PET_BODY, PET_COMPONENTS)+ schema, _ = await call_make_thing(spec, {"petType": "cat"})+ assert set(schema["properties"]) == {+ "petType",+ "owner",+ "meowVolume",+ "barkVolume",+ }+++async def test_ref_with_discriminator_sends_subtype_fields():+ spec = build_spec(PET_BODY, PET_COMPONENTS)+ _, body = await call_make_thing(+ spec, {"petType": "cat", "owner": "sam", "meowVolume": 3}+ )+ assert body == {"petType": "cat", "owner": "sam", "meowVolume": 3}+++STRING_COMPONENTS = {"Code": {"type": "string", "minLength": 3}}+++async def test_ref_to_string_with_all_of_keeps_referenced_constraints():+ body = {+ "$ref": "#/components/schemas/Code",+ "allOf": [{"description": "A code"}],+ }+ spec = build_spec(body, STRING_COMPONENTS)+ schema, sent = await call_make_thing(spec, {"body": "abc"})+ assert schema["properties"]["body"]["type"] == "string"+ assert schema["properties"]["body"]["minLength"] == 3+ assert sent == "abc"+++async def test_ref_to_object_with_all_of_still_merges():+ body = {+ "$ref": "#/components/schemas/Base",+ "allOf": [{"properties": {"extra": {"type": "string"}}}],+ }+ spec = build_spec(body, {"Base": BASE})+ schema, _ = await call_make_thing(spec, {"name": "n", "extra": "e"})+ assert set(schema["properties"]) == {"name", "extra"}+++SIBLING_BODY = {+ "$ref": "#/components/schemas/Base",+ "properties": {"local": {"type": "string"}},+}+++async def test_ref_to_one_of_target_keeps_the_ref():+ base = {+ **BASE,+ "oneOf": [+ {"required": ["a"], "properties": {"a": {"type": "string"}}},+ {"required": ["b"], "properties": {"b": {"type": "string"}}},+ ],+ }+ spec = build_spec(SIBLING_BODY, {"Base": base})+ schema, _ = await call_make_thing(+ spec, {"body": {"name": "n", "local": "l", "a": "x"}}+ )+ dumped = json.dumps(schema)+ assert '"a"' in dumped+ assert '"name"' in dumped+++async def test_ref_to_any_of_target_keeps_the_ref():+ base = {+ **BASE,+ "anyOf": [{"required": ["a"]}, {"required": ["b"]}],+ }+ spec = build_spec(SIBLING_BODY, {"Base": base})+ schema, _ = await call_make_thing(spec, {"body": {"name": "n", "local": "l"}})+ assert "anyOf" in json.dumps(schema)+++async def test_ref_to_pattern_properties_target_keeps_the_ref():+ base = {**BASE, "patternProperties": {"^x-": {"type": "string"}}}+ spec = build_spec(SIBLING_BODY, {"Base": base})+ schema, _ = await call_make_thing(spec, {"body": {"name": "n", "local": "l"}})+ assert "patternProperties" in json.dumps(schema)+++async def test_ref_to_additional_properties_target_keeps_the_ref():+ base = {**BASE, "additionalProperties": False}+ spec = build_spec(SIBLING_BODY, {"Base": base})+ schema, _ = await call_make_thing(spec, {"body": {"name": "n", "local": "l"}})+ assert "additionalProperties" in json.dumps(schema)