Skip to content

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

Keep OpenAPI refs that point into a component schema intact (#6245)

nate nowack1b651fe71638
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/json_schema_converter.py b/fastmcp_slim/fastmcp/utilities/openapi/json_schema_converter.py
index c074395d5..32f7cdd36 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/json_schema_converter.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/json_schema_converter.py
@@ -331,6 +331,25 @@ def _needs_recursive_processing(
return False
+def resolve_definition_pointer(definitions: dict[str, Any] | None, pointer: str) -> Any:
+ """Look up ``pointer``, the part of a ``#/$defs/...`` reference after
+ ``#/$defs/``, in ``definitions``.
+
+ The pointer can continue into a definition, as in
+ ``Pet/properties/status``. Returns None when any segment is missing.
+ """
+ node: Any = definitions or {}
+ for segment in pointer.split("/"):
+ key = segment.replace("~1", "/").replace("~0", "~")
+ if isinstance(node, dict):
+ node = node.get(key)
+ elif isinstance(node, list) and key.isdigit() and int(key) < len(node):
+ node = node[int(key)]
+ else:
+ return None
+ return node
+
+
def _scope_schemas(
schema: dict[str, Any],
definitions: dict[str, Any] | None,
@@ -349,7 +368,7 @@ def _scope_schemas(
ref = schema.get("$ref")
if isinstance(ref, str) and ref.startswith("#/$defs/") and ref not in seen_refs:
seen_refs.add(ref)
- target = (definitions or {}).get(ref[len("#/$defs/") :])
+ target = resolve_definition_pointer(definitions, ref[len("#/$defs/") :])
if isinstance(target, dict):
yield from _scope_schemas(target, definitions, seen_refs)
all_of = schema.get("allOf")
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/parser.py b/fastmcp_slim/fastmcp/utilities/openapi/parser.py
index 5df5690ad..12f9f6fcd 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/parser.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/parser.py
@@ -37,6 +37,7 @@ from .models import (
from .schemas import (
_combine_schemas_and_map_params,
_discriminator_target_name,
+ _ref_component_name,
_replace_ref_with_defs,
)
@@ -529,7 +530,13 @@ class OpenAPIParser(
if isinstance(ref_str, str) and ref_str.startswith(
"#/components/schemas/"
):
- top_level_schema_name = ref_str.split("/")[-1]
+ pointer = ref_str.removeprefix(
+ "#/components/schemas/"
+ )
+ # Only a whole component is a top-level
+ # schema; a pointer into one is not.
+ if "/" not in pointer:
+ top_level_schema_name = pointer
schema_dict = self._extract_schema_as_dict(media_schema)
# Add marker for top-level schema if it was a ref
@@ -619,9 +626,8 @@ class OpenAPIParser(
if "$ref" in obj and isinstance(obj["$ref"], str):
ref = obj["$ref"]
# Handle both converted and unconverted refs
- if ref.startswith(("#/$defs/", "#/components/schemas/")):
- schema_name = ref.split("/")[-1]
- else:
+ schema_name = _ref_component_name(ref)
+ if schema_name is None:
return
# Add this schema and recursively find its dependencies
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py b/fastmcp_slim/fastmcp/utilities/openapi/schemas.py
index 3f9111306..f1dc29af8 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/schemas.py
@@ -6,7 +6,10 @@ from typing import Any
from fastmcp.utilities.logging import get_logger
-from .json_schema_converter import convert_openapi_schema_to_json_schema
+from .json_schema_converter import (
+ convert_openapi_schema_to_json_schema,
+ resolve_definition_pointer,
+)
from .models import HTTPRoute, JsonSchema, ResponseInfo
logger = get_logger(__name__)
@@ -88,6 +91,18 @@ _SUBSCHEMA_KEYWORDS = (
)
+def _ref_component_name(ref: str) -> str | None:
+ """Return the component schema a local `$ref` points into, if any.
+
+ The name is the segment after `#/$defs/` or `#/components/schemas/`, so
+ `#/$defs/Pet/properties/status` needs the `Pet` definition.
+ """
+ for prefix in ("#/$defs/", "#/components/schemas/"):
+ if ref.startswith(prefix):
+ return ref.removeprefix(prefix).split("/")[0] or None
+ return None
+
+
def _replace_ref_with_defs(
info: dict[str, Any], description: str | None = None
) -> dict[str, Any]:
@@ -114,8 +129,11 @@ def _replace_ref_with_defs(
if ref_path := schema.get("$ref"):
if isinstance(ref_path, str):
if ref_path.startswith("#/components/schemas/"):
- schema_name = ref_path.split("/")[-1]
- schema["$ref"] = f"#/$defs/{schema_name}"
+ # Keep the whole pointer: one into a component, such as
+ # #/components/schemas/Pet/properties/status, has the same path
+ # under $defs.
+ pointer = ref_path.removeprefix("#/components/schemas/")
+ schema["$ref"] = f"#/$defs/{pointer}"
elif not ref_path.startswith("#/"):
raise ValueError(
f"External or non-local reference not supported: {ref_path}. "
@@ -295,7 +313,11 @@ def _allof_members(
if ref.startswith(prefix):
name = ref.removeprefix(prefix)
dependencies.add(name)
- referenced = schema_defs.get(name) if name not in refs else None
+ referenced = (
+ resolve_definition_pointer(schema_defs, name)
+ if name not in refs
+ else None
+ )
contextual |= name in refs
break
children: list[tuple[dict[str, Any], set[str]]] = []
@@ -755,8 +777,10 @@ def _combine_schemas_and_map_params(
if isinstance(value, dict):
if "$ref" in value and isinstance(value["$ref"], str):
ref = value["$ref"]
- if ref.startswith("#/$defs/"):
- used_refs.add(ref.split("/")[-1])
+ if ref.startswith("#/$defs/") and (
+ name := _ref_component_name(ref)
+ ):
+ used_refs.add(name)
for v in value.values():
find_refs_in_value(v)
elif isinstance(value, list):
@@ -944,7 +968,8 @@ def extract_output_schema_from_responses(
if "$ref" in output_schema and schema_definitions:
ref_path = output_schema["$ref"]
if ref_path.startswith("#/$defs/"):
- schema_name = ref_path.split("/")[-1]
+ # Only a reference to a whole definition can be replaced by it.
+ schema_name = ref_path.removeprefix("#/$defs/")
if schema_name in schema_definitions:
# Replace $ref with the actual schema definition
output_schema = _replace_ref_with_defs(schema_definitions[schema_name])
diff --git a/tests/server/providers/openapi/test_component_property_refs.py b/tests/server/providers/openapi/test_component_property_refs.py
new file mode 100644
index 000000000..dbabd063d
--- /dev/null
+++ b/tests/server/providers/openapi/test_component_property_refs.py
@@ -0,0 +1,130 @@
+"""References that point into a component schema rather than at a whole one."""
+
+from typing import Any
+
+import httpx2
+import pytest
+
+from fastmcp import Client, FastMCP
+from fastmcp.utilities.openapi.schemas import _replace_ref_with_defs
+
+STATUS_REF = {"$ref": "#/components/schemas/Pet/properties/status"}
+STATUS: dict[str, Any] = {"type": "string", "enum": ["available", "sold"]}
+PET = {"type": "object", "properties": {"status": STATUS}}
+
+
+def build_spec(
+ components: dict[str, Any],
+ body: dict[str, Any] | None = None,
+ response: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ if body is None:
+ body = {
+ "type": "object",
+ "properties": {"status": STATUS_REF},
+ "required": ["status"],
+ }
+ if response is None:
+ response = body
+ return {
+ "openapi": "3.1.0",
+ "info": {"title": "API", "version": "1"},
+ "paths": {
+ "/pets": {
+ "post": {
+ "operationId": "create_pet",
+ "requestBody": {
+ "required": True,
+ "content": {"application/json": {"schema": body}},
+ },
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {"application/json": {"schema": response}},
+ }
+ },
+ }
+ }
+ },
+ "components": {"schemas": components},
+ }
+
+
+def test_replace_ref_with_defs_keeps_the_pointer_into_the_component():
+ assert _replace_ref_with_defs(STATUS_REF) == {
+ "$ref": "#/$defs/Pet/properties/status"
+ }
+
+
+async def list_only_tool(spec: dict[str, Any]) -> Any:
+ async with httpx2.AsyncClient(base_url="https://api.example.com") as http:
+ server = FastMCP.from_openapi(openapi_spec=spec, client=http)
+ async with Client(server) as client:
+ (tool,) = await client.list_tools()
+ return tool
+
+
+ "components",
+ [
+ pytest.param({"Pet": PET}, id="no other component"),
+ pytest.param(
+ {"Pet": PET, "status": {"type": "integer"}},
+ id="component named like the last segment",
+ ),
+ ],
+)
+async def test_tool_schemas_use_the_referenced_property(components: dict[str, Any]):
+ """The pointer used to be cut to its last segment, so it named a `status`
+ definition: missing, or an unrelated component of that name."""
+ tool = await list_only_tool(build_spec(components))
+
+ assert tool.input_schema["properties"]["status"] == STATUS
+ assert tool.output_schema is not None
+ assert tool.output_schema["properties"]["status"] == STATUS
+
+
+async def test_response_drops_a_referenced_write_only_property():
+ """Responses never contain writeOnly properties, including one reached
+ through a pointer into a component."""
+ components = {
+ "Pet": {
+ "type": "object",
+ "properties": {"secret": {"type": "string", "writeOnly": True}},
+ }
+ }
+ response = {
+ "type": "object",
+ "properties": {
+ "secret": {"$ref": "#/components/schemas/Pet/properties/secret"},
+ "id": {"type": "integer"},
+ },
+ "required": ["secret", "id"],
+ }
+
+ tool = await list_only_tool(build_spec(components, response=response))
+
+ assert tool.output_schema is not None
+ assert tool.output_schema["properties"] == {"id": {"type": "integer"}}
+ assert tool.output_schema["required"] == ["id"]
+
+
+async def test_allof_body_member_pointing_into_a_component_keeps_its_fields():
+ components = {
+ "Pet": {
+ "type": "object",
+ "properties": {
+ "details": {
+ "type": "object",
+ "properties": {"color": {"type": "string"}},
+ "required": ["color"],
+ }
+ },
+ }
+ }
+ body = {"allOf": [{"$ref": "#/components/schemas/Pet/properties/details"}]}
+
+ tool = await list_only_tool(build_spec(components, body=body))
+
+ assert tool.input_schema["properties"] == {"color": {"type": "string"}}
+ assert tool.input_schema["required"] == ["color"]
diff --git a/tests/utilities/openapi/test_schemas.py b/tests/utilities/openapi/test_schemas.py
index 9217279c9..a08a69391 100644
--- a/tests/utilities/openapi/test_schemas.py
+++ b/tests/utilities/openapi/test_schemas.py
@@ -762,3 +762,50 @@ class TestExtractOutputSchema:
responses = {"200": invitation, "201": invitation}
assert extract_output_schema_from_responses(responses) == self.invitation_schema
+
+
+# A pointer into a component, next to a component named like its last segment.
+PET_STATUS_DEFS: dict[str, Any] = {
+ "Pet": {
+ "type": "object",
+ "properties": {"status": {"type": "string", "enum": ["a", "b"]}},
+ },
+ "status": {"type": "integer"},
+}
+
+
+def test_request_defs_keep_the_component_a_pointer_reaches_into():
+ route = HTTPRoute(
+ path="/pets",
+ method="POST",
+ request_body=RequestBodyInfo(
+ required=True,
+ content_schema={
+ "application/json": {
+ "type": "object",
+ "properties": {"status": {"$ref": "#/$defs/Pet/properties/status"}},
+ }
+ },
+ ),
+ request_schemas=PET_STATUS_DEFS,
+ )
+
+ schema, _ = _combine_schemas_and_map_params(route)
+
+ assert set(schema["$defs"]) == {"Pet"}
+
+
+def test_output_schema_does_not_inline_a_component_named_like_the_pointer_tail():
+ responses = {
+ "200": ResponseInfo(
+ description="ok",
+ content_schema={
+ "application/json": {"$ref": "#/$defs/Pet/properties/status"}
+ },
+ )
+ }
+
+ schema = extract_output_schema_from_responses(responses, PET_STATUS_DEFS, "3.1.0")
+
+ assert schema is not None
+ assert schema["properties"]["result"] == {"$ref": "#/$defs/Pet/properties/status"}