Skip to content

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

Rewrite component refs under not, if/then/else and similar keywords (#5698)

Asem ahmeda51b40962ff5
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py b/fastmcp_slim/fastmcp/utilities/openapi/schemas.py
index 49981d4f5..0faf3f6bd 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/schemas.py
@@ -74,6 +74,20 @@ def clean_schema_for_display(schema: JsonSchema | None) -> JsonSchema | None:
return cleaned
+# Keywords whose value is a single subschema
+_SUBSCHEMA_KEYWORDS = (
+ "propertyNames",
+ "contentSchema",
+ "not",
+ "if",
+ "then",
+ "else",
+ "contains",
+ "unevaluatedItems",
+ "unevaluatedProperties",
+)
+
+
def _replace_ref_with_defs(
info: dict[str, Any], description: str | None = None
) -> dict[str, Any]:
@@ -131,18 +145,18 @@ def _replace_ref_with_defs(
schema["additionalProperties"] = _replace_ref_with_defs(
additionalProperties
)
- # Handle propertyNames
- if property_names := schema.get("propertyNames"):
- if isinstance(property_names, dict):
- schema["propertyNames"] = _replace_ref_with_defs(property_names)
- # Handle patternProperties
- if pattern_properties := schema.get("patternProperties"):
- if isinstance(pattern_properties, dict):
- schema["patternProperties"] = {
- pattern: _replace_ref_with_defs(subschema)
+ # Handle single-schema keywords
+ for keyword in _SUBSCHEMA_KEYWORDS:
+ if isinstance(schema.get(keyword), dict):
+ schema[keyword] = _replace_ref_with_defs(schema[keyword])
+ # Handle patternProperties and dependentSchemas
+ for keyword in ("patternProperties", "dependentSchemas"):
+ if isinstance(schema.get(keyword), dict):
+ schema[keyword] = {
+ name: _replace_ref_with_defs(subschema)
if isinstance(subschema, dict)
else subschema
- for pattern, subschema in pattern_properties.items()
+ for name, subschema in schema[keyword].items()
}
if info.get("description", description) and not schema.get("description"):
schema["description"] = description
diff --git a/tests/utilities/openapi/test_subschema_keyword_refs.py b/tests/utilities/openapi/test_subschema_keyword_refs.py
new file mode 100644
index 000000000..0341aa573
--- /dev/null
+++ b/tests/utilities/openapi/test_subschema_keyword_refs.py
@@ -0,0 +1,97 @@
+"""Component references under single-schema keywords become $defs references."""
+
+from typing import Any
+
+import httpx2
+import pytest
+
+from fastmcp import Client, FastMCP
+from fastmcp.utilities.openapi.schemas import _replace_ref_with_defs
+
+REF = {"$ref": "#/components/schemas/Reserved"}
+DEFS_REF = {"$ref": "#/$defs/Reserved"}
+
+
+ "keyword",
+ [
+ "not",
+ "if",
+ "then",
+ "else",
+ "contains",
+ "unevaluatedItems",
+ "unevaluatedProperties",
+ "propertyNames",
+ "contentSchema",
+ ],
+)
+def test_single_schema_keyword_refs_are_rewritten(keyword: str):
+ schema = {"type": "string", keyword: REF}
+ assert _replace_ref_with_defs(schema) == {"type": "string", keyword: DEFS_REF}
+
+
+def test_dependent_schemas_refs_are_rewritten():
+ schema = {"type": "object", "dependentSchemas": {"credit_card": REF}}
+ assert _replace_ref_with_defs(schema) == {
+ "type": "object",
+ "dependentSchemas": {"credit_card": DEFS_REF},
+ }
+
+
[email protected]("version", ["3.0.3", "3.1.0"])
+async def test_not_reference_resolves_in_tool_schemas(version: str):
+ reserved = {"type": "string", "enum": ["root", "admin"]}
+ username: dict[str, Any] = {"type": "string", "not": REF}
+ spec = {
+ "openapi": version,
+ "info": {"title": "Users", "version": "1"},
+ "paths": {
+ "/users": {
+ "post": {
+ "operationId": "create_user",
+ "requestBody": {
+ "required": True,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {"username": username},
+ "required": ["username"],
+ }
+ }
+ },
+ },
+ "responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {"username": username},
+ }
+ }
+ },
+ }
+ },
+ }
+ }
+ },
+ "components": {"schemas": {"Reserved": reserved}},
+ }
+
+ def handler(request: httpx2.Request) -> httpx2.Response:
+ return httpx2.Response(200, json={"username": "alice"})
+
+ http = httpx2.AsyncClient(
+ base_url="http://test", transport=httpx2.MockTransport(handler)
+ )
+ async with Client(FastMCP.from_openapi(openapi_spec=spec, client=http)) as client:
+ (tool,) = await client.list_tools()
+ assert tool.input_schema["properties"]["username"]["not"] == reserved
+ assert tool.output_schema is not None
+ assert tool.output_schema["properties"]["username"]["not"] == reserved
+
+ result = await client.call_tool("create_user", {"username": "alice"})
+ assert result.structured_content == {"username": "alice"}