π The fast, Pythonic way to build MCP servers and clients.
fix: guard recursive refs in json_schema_to_type (#4312)
Jianke LINba77e4626b57
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema_type.py b/fastmcp_slim/fastmcp/utilities/json_schema_type.pyindex 140fc6041..de1db2900 100644--- a/fastmcp_slim/fastmcp/utilities/json_schema_type.py+++ b/fastmcp_slim/fastmcp/utilities/json_schema_type.py@@ -349,18 +349,20 @@ def _create_enum(name: str, values: list[Any]) -> type:def _create_array_type(- schema: Mapping[str, Any], schemas: Mapping[str, Any]+ schema: Mapping[str, Any],+ schemas: Mapping[str, Any],+ resolving_refs: frozenset[str],) -> type | Annotated[Any, ...]:"""Create list/set type with optional constraints."""items = schema.get("items", {})if isinstance(items, list):# Handle positional item schemas- item_types = [_schema_to_type(s, schemas) for s in items]+ item_types = [_schema_to_type(s, schemas, resolving_refs) for s in items]combined = Union[tuple(item_types)] # noqa: UP007base = list[combined] # type: ignore[valid-type] # ty:ignore[invalid-type-form]else:# Handle single item schema- item_type = _schema_to_type(items, schemas)+ item_type = _schema_to_type(items, schemas, resolving_refs)base_class = set if schema.get("uniqueItems") else listbase = base_class[item_type]@@ -384,6 +386,7 @@ def _object_schema_to_type(schema: Mapping[str, Any],schemas: Mapping[str, Any],name: str | None = None,+ resolving_refs: frozenset[str] = frozenset(),) -> type:"""Convert an object schema to the appropriate Python type.@@ -408,20 +411,22 @@ def _object_schema_to_type(if not has_properties and additional_props:if additional_props is True:return dict[str, Any]- value_type = _schema_to_type(additional_props, schemas)+ value_type = _schema_to_type(additional_props, schemas, resolving_refs)return cast(type[Any], dict[str, value_type]) # type: ignore[valid-type] # ty:ignore[invalid-type-form]if not has_properties and not additional_props:return dict[str, Any]if has_properties and additional_props is True:- return _create_pydantic_model(schema, class_name, schemas)+ return _create_pydantic_model(schema, class_name, schemas, resolving_refs)- return _create_dataclass(schema, class_name, schemas)+ return _create_dataclass(schema, class_name, schemas, resolving_refs)def _get_from_type_handler(- schema: Mapping[str, Any], schemas: Mapping[str, Any]+ schema: Mapping[str, Any],+ schemas: Mapping[str, Any],+ resolving_refs: frozenset[str],) -> Callable[..., Any]:"""Get the appropriate type handler for the schema."""@@ -431,8 +436,10 @@ def _get_from_type_handler("number": lambda s: _create_numeric_type(float, s),"boolean": lambda _: bool,"null": lambda _: type(None),- "array": lambda s: _create_array_type(s, schemas),- "object": lambda s: _object_schema_to_type(s, schemas),+ "array": lambda s: _create_array_type(s, schemas, resolving_refs),+ "object": lambda s: _object_schema_to_type(+ s, schemas, resolving_refs=resolving_refs+ ),}return type_handlers.get(schema.get("type", None), _return_Any)@@ -440,6 +447,7 @@ def _get_from_type_handler(def _schema_to_type(schema: Mapping[str, Any] | bool,schemas: Mapping[str, Any],+ resolving_refs: frozenset[str] = frozenset(),) -> type | ForwardRef:"""Convert schema to appropriate Python type."""# Boolean schemas are valid in JSON Schema draft-06+:@@ -462,7 +470,16 @@ def _schema_to_type(# Handle self-referenceif ref == "#":return ForwardRef(schema.get("title", "Root"))- return _schema_to_type(_resolve_ref(ref, schemas), schemas)+ if ref in resolving_refs:+ resolved = _resolve_ref(ref, schemas)+ if isinstance(resolved, Mapping) and (+ resolved.get("type") == "object" or "properties" in resolved+ ):+ return _schema_to_type(resolved, schemas, resolving_refs)+ return Any+ return _schema_to_type(+ _resolve_ref(ref, schemas), schemas, resolving_refs | {ref}+ )if "const" in schema:return Literal[schema["const"]] # type: ignore@@ -473,7 +490,8 @@ def _schema_to_type(# Handle anyOf unionsif "anyOf" in schema:types: list[type | Any] = [- _schema_to_type(subschema, schemas) for subschema in schema["anyOf"]+ _schema_to_type(subschema, schemas, resolving_refs)+ for subschema in schema["anyOf"]]# Check if one of the types is None (null)@@ -503,7 +521,7 @@ def _schema_to_type(for t in schema_type:type_schema = dict(schema)type_schema["type"] = t- types.append(_schema_to_type(type_schema, schemas))+ types.append(_schema_to_type(type_schema, schemas, resolving_refs))has_null = type(None) in typestypes = [t for t in types if t is not type(None)]if has_null:@@ -513,7 +531,7 @@ def _schema_to_type(return Union[(*types, type(None))] # type: ignorereturn Union[tuple(types)] # type: ignore # noqa: UP007- return _get_from_type_handler(schema, schemas)(schema)+ return _get_from_type_handler(schema, schemas, resolving_refs)(schema)def _sanitize_name(name: str) -> str:@@ -570,6 +588,7 @@ def _create_pydantic_model(schema: Mapping[str, Any],name: str | None = None,schemas: Mapping[str, Any] | None = None,+ resolving_refs: frozenset[str] = frozenset(),) -> type:"""Create Pydantic BaseModel from object schema with additionalProperties."""name = name or schema.get("title", "Root")@@ -600,10 +619,10 @@ def _create_pydantic_model(# Boolean schemas (JSON Schema draft-06+): resolve type directly,# then use an empty dict for .get() calls below.if isinstance(prop_schema, bool):- field_type = _schema_to_type(prop_schema, schemas or {})+ field_type = _schema_to_type(prop_schema, schemas or {}, resolving_refs)prop_schema = {}else:- field_type = _schema_to_type(prop_schema, schemas or {})+ field_type = _schema_to_type(prop_schema, schemas or {}, resolving_refs)# Handle defaultsdefault_value = prop_schema.get("default", MISSING)@@ -634,6 +653,7 @@ def _create_dataclass(schema: Mapping[str, Any],name: str | None = None,schemas: Mapping[str, Any] | None = None,+ resolving_refs: frozenset[str] = frozenset(),) -> type:"""Create dataclass from object schema."""name = name or schema.get("title", "Root")@@ -659,7 +679,10 @@ def _create_dataclass(ref = schema["$ref"]if ref == "#":return ForwardRef(sanitized_name) # type: ignore[return-value] # ty:ignore[invalid-return-type]+ if ref in resolving_refs:+ return Anyschema = _resolve_ref(ref, schemas or {})+ resolving_refs = resolving_refs | {ref}properties = schema.get("properties", {})required = schema.get("required", [])@@ -680,13 +703,13 @@ def _create_dataclass(# Boolean schemas (JSON Schema draft-06+): resolve type directly,# then use an empty dict for .get() calls below.if isinstance(prop_schema, bool):- field_type = _schema_to_type(prop_schema, schemas or {})+ field_type = _schema_to_type(prop_schema, schemas or {}, resolving_refs)prop_schema = {}elif prop_schema.get("$ref") == "#":# Check for self-reference in propertyfield_type = ForwardRef(sanitized_name)else:- field_type = _schema_to_type(prop_schema, schemas or {})+ field_type = _schema_to_type(prop_schema, schemas or {}, resolving_refs)default_val = prop_schema.get("default", MISSING)is_required = prop_name in requireddiff --git a/tests/utilities/json_schema_type/test_advanced.py b/tests/utilities/json_schema_type/test_advanced.pyindex 9240e04b5..01f4900ee 100644--- a/tests/utilities/json_schema_type/test_advanced.py+++ b/tests/utilities/json_schema_type/test_advanced.py@@ -497,6 +497,34 @@ class TestEdgeCases:assert result.node.value == "default" # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]assert result.node.next is None # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]+ def test_recursive_ref_in_anyof_does_not_recurse_forever(self):+ schema = {+ "type": "object",+ "properties": {+ "items": {"type": "array", "items": {"$ref": "#/$defs/JSONValue"}},+ },+ "$defs": {+ "JSONValue": {+ "anyOf": [+ {"type": "string"},+ {"type": "array", "items": {"$ref": "#/$defs/JSONValue"}},+ {+ "type": "object",+ "additionalProperties": {"$ref": "#/$defs/JSONValue"},+ },+ ]+ }+ },+ }++ Type = json_schema_to_type(schema)+ validator = TypeAdapter(Type)+ result = validator.validate_python(+ {"items": ["value", ["nested"], {"key": ["leaf"]}]}+ )++ assert result.items == ["value", ["nested"], {"key": ["leaf"]}] # type: ignore[attr-defined] # ty:ignore[unresolved-attribute]+def test_mixed_type_array(self):schema = {"type": "array",