π The fast, Pythonic way to build MCP servers and clients.
fix(openapi): keep media-type $defs beside component schemas (#5709)
εεΊη±³ccc8602bdb13
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py b/fastmcp_slim/fastmcp/utilities/openapi/schemas.pyindex 0faf3f6bd..93c2e135b 100644--- a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py+++ b/fastmcp_slim/fastmcp/utilities/openapi/schemas.py@@ -531,6 +531,7 @@ def _combine_schemas_and_map_params(}body_schema: dict[str, Any] = {}body_props: dict[str, Any] = {}+ body_defs: dict[str, Any] = {}for param in route.parameters:param_names_by_location[param.location].add(param.name)@@ -545,6 +546,15 @@ def _combine_schemas_and_map_params()else:body_schema = route.request_body.content_schema[content_type]+ # The body schema's own $defs resolve its #/$defs/... references+ # alongside the component schemas, so refs inside them are rewritten+ # to #/$defs/... as well.+ body_defs = {+ name: _replace_ref_with_defs(def_schema)+ if isinstance(def_schema, dict)+ else def_schema+ for name, def_schema in (body_schema.get("$defs") or {}).items()+ }if route.request_body.description and not body_schema.get("description"):body_schema["description"] = route.request_body.description@@ -727,7 +737,7 @@ def _combine_schemas_and_map_params("required": required,}# Add schema definitions if available- schema_defs = route.request_schemas+ schema_defs = {**route.request_schemas, **body_defs}if schema_defs:if convert_refs:# Need to convert refs and prune@@ -908,6 +918,16 @@ def extract_output_schema_from_responses(definitions=definitions,)+ # The schema's own $defs must be caught before wrapping hides them one+ # level down; its #/$defs/... references keep resolving against the root,+ # so refs inside them are rewritten to #/$defs/... as well.+ inline_defs = {+ name: _replace_ref_with_defs(def_schema)+ if isinstance(def_schema, dict)+ else def_schema+ for name, def_schema in (output_schema.get("$defs") or {}).items()+ }+# MCP requires output schemas to be objects. If this schema is not an object,# we need to wrap it similar to how ParsedFunction.from_function() does itif output_schema.get("type") != "object":@@ -920,7 +940,10 @@ def extract_output_schema_from_responses(}output_schema = wrapped_schema- # Add schema definitions if available+ # Reattach the definitions at the root even when there are no component+ # schemas: the non-object wrap moves the schema's own $defs one level down,+ # while its #/$defs/... references keep resolving against the root.+ processed_defs: dict[str, Any] = {}if schema_definitions:processed_defs = definitions.copy()@@ -934,7 +957,10 @@ def extract_output_schema_from_responses(definitions=definitions,)- output_schema["$defs"] = processed_defs+ if processed_defs or inline_defs:+ # Same-named inline $defs win: the schema's #/$defs/... references+ # are local to it, not to the component schemas.+ output_schema["$defs"] = {**processed_defs, **inline_defs}return output_schemadiff --git a/tests/utilities/openapi/test_inline_defs.py b/tests/utilities/openapi/test_inline_defs.pynew file mode 100644index 000000000..2acb6f9aa--- /dev/null+++ b/tests/utilities/openapi/test_inline_defs.py@@ -0,0 +1,231 @@+"""A media-type schema's own ``$defs`` must survive beside component schemas.++OpenAPI 3.1 schema objects are JSON Schema 2020-12 resources, so a request or+response media-type schema may declare its own ``$defs`` and reference them+with ``#/$defs/...``. When ``components/schemas`` is non-empty, those inline+definitions used to be replaced by the component-derived ones, leaving the+media-type schema's ``#/$defs/...`` references dangling.+"""++import httpx2+from jsonschema import validate as validate_json_schema++from fastmcp import Client, FastMCP+from fastmcp.utilities.openapi.models import (+ HTTPRoute,+ RequestBodyInfo,+ ResponseInfo,+)+from fastmcp.utilities.openapi.parser import parse_openapi_to_http_routes+from fastmcp.utilities.openapi.schemas import (+ _combine_schemas_and_map_params,+ extract_output_schema_from_responses,+)++ITEM_SCHEMA = {"type": "object", "properties": {"name": {"type": "string"}}}+BODY = {"item": {"name": "n"}, "extra": "hello"}+++def _inline_defs_schema() -> dict:+ """A media-type schema that declares its own ``$defs``."""+ return {+ "type": "object",+ "properties": {+ "item": {"$ref": "#/components/schemas/Item"},+ "extra": {"$ref": "#/$defs/Extra"},+ },+ "$defs": {"Extra": {"type": "string"}},+ }+++SPEC = {+ "openapi": "3.1.0",+ "info": {"title": "t", "version": "1.0.0"},+ "components": {"schemas": {"Item": ITEM_SCHEMA}},+ "paths": {+ "/items": {+ "post": {+ "operationId": "createItem",+ "requestBody": {+ "required": True,+ "content": {"application/json": {"schema": _inline_defs_schema()}},+ },+ "responses": {+ "200": {+ "description": "ok",+ "content": {+ "application/json": {"schema": _inline_defs_schema()}+ },+ }+ },+ }+ }+ },+}+++def test_output_schema_keeps_media_type_defs():+ responses = {+ "200": ResponseInfo(+ description="ok",+ content_schema={"application/json": _inline_defs_schema()},+ )+ }++ result = extract_output_schema_from_responses(+ responses, {"Item": ITEM_SCHEMA}, "3.1.0"+ )++ assert result is not None+ assert result["properties"]["extra"] == {"$ref": "#/$defs/Extra"}+ assert result["$defs"]["Extra"] == {"type": "string"}+ assert "Item" in result["$defs"]++ # The advertised schema must resolve every reference it carries.+ validate_json_schema(BODY, result)+++def test_input_schema_keeps_media_type_defs():+ route = HTTPRoute(+ path="/items",+ method="POST",+ operation_id="createItem",+ request_body=RequestBodyInfo(+ required=True,+ content_schema={"application/json": _inline_defs_schema()},+ ),+ request_schemas={"Item": ITEM_SCHEMA},+ )++ combined, _ = _combine_schemas_and_map_params(route)++ assert combined["properties"]["extra"] == {"$ref": "#/$defs/Extra"}+ assert combined["$defs"]["Extra"] == {"type": "string"}+ assert "Item" in combined["$defs"]++ validate_json_schema(BODY, combined)+++def test_output_schema_rewrites_refs_inside_media_type_defs():+ schema = {+ "type": "object",+ "properties": {"extra": {"$ref": "#/$defs/Extra"}},+ "$defs": {+ "Extra": {+ "type": "object",+ "properties": {"inner": {"$ref": "#/components/schemas/Item"}},+ }+ },+ }+ responses = {+ "200": ResponseInfo(+ description="ok",+ content_schema={"application/json": schema},+ )+ }++ result = extract_output_schema_from_responses(+ responses, {"Item": ITEM_SCHEMA}, "3.1.0"+ )++ assert result is not None+ assert result["$defs"]["Extra"]["properties"]["inner"] == {"$ref": "#/$defs/Item"}+ assert "Item" in result["$defs"]++ validate_json_schema({"extra": {"inner": {"name": "n"}}}, result)+++def test_output_schema_keeps_media_type_defs_after_wrap_without_components():+ schema = {+ "type": "array",+ "items": {"$ref": "#/$defs/Extra"},+ "$defs": {"Extra": {"type": "string"}},+ }+ responses = {+ "200": ResponseInfo(+ description="ok",+ content_schema={"application/json": schema},+ )+ }++ result = extract_output_schema_from_responses(responses, {}, "3.1.0")++ assert result is not None+ assert result["x-fastmcp-wrap-result"] is True+ assert result["properties"]["result"]["items"] == {"$ref": "#/$defs/Extra"}+ assert result["$defs"]["Extra"] == {"type": "string"}++ # The advertised schema must resolve every reference it carries.+ validate_json_schema({"result": ["hello"]}, result)+++def test_parsed_route_flat_schema_keeps_media_type_defs():+ route = parse_openapi_to_http_routes(SPEC)[0]++ flat = route.flat_param_schema++ assert flat["properties"]["extra"] == {"$ref": "#/$defs/Extra"}+ assert flat["$defs"]["Extra"] == {"type": "string"}+ assert "Item" in flat["$defs"]+++def test_parsed_route_input_rewrites_refs_inside_media_type_defs():+ spec = {+ "openapi": "3.1.0",+ "info": {"title": "t", "version": "1.0.0"},+ "components": {"schemas": {"Item": ITEM_SCHEMA}},+ "paths": {+ "/items": {+ "post": {+ "operationId": "createItem",+ "requestBody": {+ "required": True,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "extra": {"$ref": "#/$defs/Extra"},+ },+ "$defs": {+ "Extra": {+ "type": "object",+ "properties": {+ "inner": {+ "$ref": "#/components/schemas/Item"+ }+ },+ }+ },+ }+ }+ },+ },+ "responses": {"200": {"description": "ok"}},+ }+ }+ },+ }++ route = parse_openapi_to_http_routes(spec)[0]++ flat = route.flat_param_schema++ assert flat["properties"]["extra"] == {"$ref": "#/$defs/Extra"}+ assert flat["$defs"]["Extra"]["properties"]["inner"] == {"$ref": "#/$defs/Item"}+ assert "Item" in flat["$defs"]++ validate_json_schema({"extra": {"inner": {"name": "n"}}}, flat)+++async def test_tool_call_with_media_type_defs():+ def handler(request: httpx2.Request) -> httpx2.Response:+ return httpx2.Response(200, json=BODY)++ http = httpx2.AsyncClient(transport=httpx2.MockTransport(handler))+ mcp = FastMCP.from_openapi(SPEC, client=http)++ async with Client(mcp) as client:+ result = await client.call_tool("createItem", BODY)++ assert result.structured_content == BODY