Skip to content

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

fix: name root self-references after the generated root class (#5671)

ε“ˆεŸΊη±³2c3a2deb9b98
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema_type.py b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
index c913927d7..1c29c8ad7 100644
--- a/fastmcp_slim/fastmcp/utilities/json_schema_type.py
+++ b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
@@ -235,6 +235,9 @@ class _Conversion:
root_hash: str
root_size: int
+ # Sanitized name of the class generated for the root schema; `"$ref": "#"`
+ # resolves to that class.
+ root_class_name: str
resolved_refs: dict[str, Any] = field(default_factory=dict)
building: set[tuple[str, str]] = field(default_factory=set)
depth: int = 0
@@ -352,7 +355,17 @@ def json_schema_to_type(
def _convert_normalized(schema: dict[str, Any], name: str | None) -> type:
root_hash, root_size = _schema_digest(schema)
- token = _conversion.set(_Conversion(root_hash=root_hash, root_size=root_size))
+ # `title` can carry any JSON value in a malformed schema; only a string
+ # (including the empty string) is a valid class-name source.
+ title = schema.get("title")
+ root_title = title if isinstance(title, str) else "Root"
+ token = _conversion.set(
+ _Conversion(
+ root_hash=root_hash,
+ root_size=root_size,
+ root_class_name=_sanitize_name(name or root_title),
+ )
+ )
try:
# Always use the top-level schema for references
if schema.get("type") == "object":
@@ -835,7 +848,7 @@ def _convert_schema(
ref = schema["$ref"]
# Handle self-reference
if ref == "#":
- return ForwardRef(_sanitize_name(schema.get("title", "Root")))
+ return ForwardRef(_conversion.get().root_class_name)
if ref in resolving_refs:
resolved = _resolve_ref(ref, schemas)
if isinstance(resolved, Mapping) and (
@@ -890,6 +903,16 @@ def _convert_schema(
# Create a copy of the schema for each type, but keep all constraints
types: list[type | Any] = []
for t in schema_type:
+ if t == "object" and schema is schemas:
+ # The root narrowed to its object member: convert the schema
+ # itself, not a copy, so the generated class keeps the root
+ # identity (and name) that "$ref": "#" resolves to.
+ types.append(
+ _object_schema_to_type(
+ schema, schemas, resolving_refs=resolving_refs
+ )
+ )
+ continue
type_schema = dict(schema)
type_schema["type"] = t
types.append(_schema_to_type(type_schema, schemas, resolving_refs))
@@ -1007,6 +1030,24 @@ def _create_field_with_default(
return field(default=default_value)
+def _nested_class_name(
+ sanitized_name: str,
+ conversion: _Conversion,
+ schema: Mapping[str, Any],
+ schemas: Mapping[str, Any] | None,
+) -> str:
+ """Disambiguate a nested class named like the conversion root.
+
+ Pydantic resolves a class's annotations with the class's own name bound
+ to that class before the conversion root, so a nested class sharing the
+ root's name would capture every ``"$ref": "#"`` reference inside it.
+ Keep the root name pointing at the root class.
+ """
+ if sanitized_name == conversion.root_class_name and schema is not schemas:
+ return f"{sanitized_name}_2"
+ return sanitized_name
+
+
def _create_pydantic_model(
schema: Mapping[str, Any],
name: str | None = None,
@@ -1019,8 +1060,15 @@ def _create_pydantic_model(
raise ValueError("Name is required")
sanitized_name = _sanitize_name(name)
conversion = _conversion.get()
+ sanitized_name = _nested_class_name(sanitized_name, conversion, schema, schemas)
schema_hash = _hash_schema(schema)
- cache_key = (schema_hash + conversion.root_hash, sanitized_name)
+ # Nested classes bake the root class name into their forward references,
+ # so conversions that differ only in the root's name must not share
+ # cache entries.
+ cache_key = (
+ schema_hash + conversion.root_hash + conversion.root_class_name,
+ sanitized_name,
+ )
# Return existing class if already built
existing = _classes.get(cache_key)
@@ -1100,8 +1148,15 @@ def _create_dataclass(
raise ValueError("Name is required")
sanitized_name = _sanitize_name(name)
conversion = _conversion.get()
+ sanitized_name = _nested_class_name(sanitized_name, conversion, schema, schemas)
schema_hash = _hash_schema(schema)
- cache_key = (schema_hash + conversion.root_hash, sanitized_name)
+ # Nested classes bake the root class name into their forward references,
+ # so conversions that differ only in the root's name must not share
+ # cache entries.
+ cache_key = (
+ schema_hash + conversion.root_hash + conversion.root_class_name,
+ sanitized_name,
+ )
# Return existing class if already built
existing = _classes.get(cache_key)
@@ -1132,7 +1187,8 @@ def _build_dataclass(
if "$ref" in schema:
ref = schema["$ref"]
if ref == "#":
- return ForwardRef(sanitized_name)
+ # "#" resolves to the conversion root, not to this class.
+ return ForwardRef(_conversion.get().root_class_name)
if ref in resolving_refs:
return Any
schema = _resolve_ref(ref, schemas)
@@ -1160,8 +1216,9 @@ def _build_dataclass(
field_type = _schema_to_type(prop_schema, schemas, resolving_refs)
prop_schema = {}
elif prop_schema.get("$ref") == "#":
- # Check for self-reference in property
- field_type = ForwardRef(sanitized_name)
+ # A direct "#" reference points at the conversion root, which
+ # may be a different class than the one being built here.
+ field_type = ForwardRef(_conversion.get().root_class_name)
else:
field_type = _schema_to_type(prop_schema, schemas, resolving_refs)
diff --git a/tests/utilities/json_schema_type/test_advanced.py b/tests/utilities/json_schema_type/test_advanced.py
index 121e9099f..dbbbf7c42 100644
--- a/tests/utilities/json_schema_type/test_advanced.py
+++ b/tests/utilities/json_schema_type/test_advanced.py
@@ -1,7 +1,7 @@
"""Advanced JSON schema type conversion features."""
from dataclasses import Field
-from typing import Any, Union
+from typing import Any, Union, cast
import pytest
from pydantic import BaseModel, TypeAdapter, ValidationError
@@ -17,6 +17,12 @@ def get_dataclass_field(type: type, field_name: str) -> Field:
return type.__dataclass_fields__[field_name] # ty: ignore[unresolved-attribute]
+def unwrap_optional(field: Field) -> Any:
+ """Return a field's bare type, unwrapping an Optional[T] annotation to T."""
+ field_type = cast(Any, field.type)
+ return field_type.__args__[0] if hasattr(field_type, "__args__") else field_type
+
+
class TestDefaultValues:
"""Test suite for default value handling."""
@@ -181,6 +187,261 @@ class TestCircularReferences:
assert result.person.friend.name == "Spot"
assert result.person.friend.owner.name == "Bob"
+ def test_titled_root_self_reference_in_union(self):
+ node_type = json_schema_to_type(
+ {
+ "type": "object",
+ "title": "Node",
+ "properties": {
+ "name": {"type": "string"},
+ "next": {"anyOf": [{"$ref": "#"}, {"type": "null"}]},
+ },
+ }
+ )
+ assert node_type.__name__ == "Node"
+
+ validator: TypeAdapter[Any] = TypeAdapter(node_type)
+ node = validator.validate_python({"name": "a", "next": {"name": "b"}})
+ assert node.next.name == "b"
+ assert node.next.next is None
+
+ def test_titled_root_self_reference_in_items(self):
+ node_type = json_schema_to_type(
+ {
+ "type": "object",
+ "title": "Node",
+ "properties": {
+ "name": {"type": "string"},
+ "children": {"type": "array", "items": {"$ref": "#"}},
+ },
+ }
+ )
+ assert node_type.__name__ == "Node"
+
+ validator: TypeAdapter[Any] = TypeAdapter(node_type)
+ node = validator.validate_python({"name": "a", "children": [{"name": "b"}]})
+ assert node.children[0].name == "b"
+ assert node.children[0].children is None
+
+ def test_titled_root_self_reference_in_property_with_extras(self):
+ # additionalProperties: True builds a Pydantic model, whose fields
+ # all go through the generic reference handling.
+ node_type = json_schema_to_type(
+ {
+ "type": "object",
+ "title": "Node",
+ "additionalProperties": True,
+ "properties": {
+ "name": {"type": "string"},
+ "next": {"$ref": "#"},
+ },
+ }
+ )
+ assert node_type.__name__ == "Node"
+
+ validator: TypeAdapter[Any] = TypeAdapter(node_type)
+ node = validator.validate_python({"name": "a", "next": {"name": "b"}})
+ assert node.next.name == "b"
+ assert node.next.next is None
+
+ def test_explicit_name_root_self_reference(self):
+ # An explicit name overrides the title for the generated class, so
+ # the self-reference must target the override, not the title.
+ node_type = json_schema_to_type(
+ {
+ "type": "object",
+ "title": "Node",
+ "properties": {
+ "name": {"type": "string"},
+ "next": {"anyOf": [{"$ref": "#"}, {"type": "null"}]},
+ },
+ },
+ name="CustomNode",
+ )
+ assert node_type.__name__ == "CustomNode"
+
+ validator: TypeAdapter[Any] = TypeAdapter(node_type)
+ node = validator.validate_python({"name": "a", "next": {"name": "b"}})
+ assert node.next.name == "b"
+ assert node.next.next is None
+
+ def test_nested_class_named_like_root_does_not_shadow_root(self):
+ # A nested object titled like the root must not capture the root's
+ # `"$ref": "#"` references: pydantic binds a class's own name to that
+ # class before the conversion root, so the nested class is renamed.
+ node_type = json_schema_to_type(
+ {
+ "type": "object",
+ "title": "Node",
+ "required": ["name", "count"],
+ "properties": {
+ "name": {"type": "string"},
+ "count": {"type": "integer"},
+ "child": {
+ "type": "object",
+ "title": "Node",
+ "required": ["name", "tag"],
+ "properties": {
+ "name": {"type": "string"},
+ "tag": {"type": "string"},
+ "next": {"anyOf": [{"$ref": "#"}, {"type": "null"}]},
+ },
+ },
+ },
+ }
+ )
+ assert node_type.__name__ == "Node"
+
+ child_cls = unwrap_optional(get_dataclass_field(node_type, "child"))
+ assert child_cls.__name__ == "Node_2"
+
+ validator: TypeAdapter[Any] = TypeAdapter(node_type)
+ # `next` is the ROOT schema, so a root-shaped instance validates...
+ node = validator.validate_python(
+ {
+ "name": "r",
+ "count": 1,
+ "child": {"name": "c", "tag": "t", "next": {"name": "n", "count": 1}},
+ }
+ )
+ assert node.child.next.count == 1
+ # ...and shapes that violate the root schema are rejected, whether
+ # or not they satisfy the nested class's fields.
+ with pytest.raises(ValidationError):
+ validator.validate_python(
+ {
+ "name": "r",
+ "count": 1,
+ "child": {"name": "c", "tag": "t", "next": {"name": "n"}},
+ }
+ )
+ with pytest.raises(ValidationError):
+ validator.validate_python(
+ {
+ "name": "r",
+ "count": 1,
+ "child": {
+ "name": "c",
+ "tag": "t",
+ "next": {"name": "n", "tag": "t"},
+ },
+ }
+ )
+
+ def test_name_override_does_not_reuse_stale_nested_class(self):
+ # A nested class bakes the root's name into its forward references,
+ # so conversions of the same schema under different `name=` overrides
+ # must not share nested-class cache entries.
+ schema = {
+ "type": "object",
+ "title": "Doc",
+ "properties": {
+ "value": {"type": "string"},
+ "nested": {
+ "type": "object",
+ "title": "Nested",
+ "properties": {
+ "root_ref": {"anyOf": [{"$ref": "#"}, {"type": "null"}]}
+ },
+ },
+ },
+ }
+ first_type = json_schema_to_type(schema, name="First")
+ second_type = json_schema_to_type(schema, name="Second")
+
+ first_nested = unwrap_optional(get_dataclass_field(first_type, "nested"))
+ second_nested = unwrap_optional(get_dataclass_field(second_type, "nested"))
+ assert second_nested is not first_nested
+
+ validator: TypeAdapter[Any] = TypeAdapter(second_type)
+ node = validator.validate_python(
+ {"value": "v", "nested": {"root_ref": {"value": "x", "nested": None}}}
+ )
+ assert isinstance(node.nested.root_ref, second_type)
+
+ def test_untitled_nullable_object_root_self_reference(self):
+ # A type-list root narrows through a copy of the schema; the object
+ # member must still build the root class that "#" references.
+ root_type = json_schema_to_type(
+ {
+ "type": ["object", "null"],
+ "properties": {
+ "name": {"type": "string"},
+ "next": {"anyOf": [{"$ref": "#"}, {"type": "null"}]},
+ },
+ }
+ )
+ validator: TypeAdapter[Any] = TypeAdapter(root_type)
+ assert validator.validate_python(None) is None
+ node = validator.validate_python(
+ {"name": "a", "next": {"name": "b", "next": None}}
+ )
+ assert type(node).__name__ == "Root"
+ assert node.next.name == "b"
+
+ def test_titled_nullable_object_root_self_reference(self):
+ root_type = json_schema_to_type(
+ {
+ "type": ["object", "null"],
+ "title": "Node",
+ "properties": {
+ "name": {"type": "string"},
+ "next": {"anyOf": [{"$ref": "#"}, {"type": "null"}]},
+ },
+ }
+ )
+ validator: TypeAdapter[Any] = TypeAdapter(root_type)
+ node = validator.validate_python({"name": "a", "next": {"name": "b"}})
+ assert type(node).__name__ == "Node"
+ assert node.next.name == "b"
+
+ @pytest.mark.parametrize(
+ "schema,valid_value",
+ [
+ ({"type": "string", "title": None}, "x"),
+ ({"type": "string", "title": 5}, "x"),
+ ({"type": "object", "title": 5}, {}),
+ ],
+ )
+ def test_non_string_title_does_not_crash(self, schema, valid_value):
+ # `title` may hold any JSON value in a malformed schema; the
+ # conversion must handle the schemas it otherwise would.
+ root_type = json_schema_to_type(schema)
+ assert TypeAdapter(root_type).validate_python(valid_value) == valid_value
+
+ def test_nested_direct_root_reference_points_at_root(self):
+ # A direct `"root": {"$ref": "#"}` property on a nested class must
+ # reference the conversion root, not the nested class itself.
+ root_type = json_schema_to_type(
+ {
+ "type": "object",
+ "title": "Doc",
+ "required": ["value"],
+ "properties": {
+ "value": {"type": "string"},
+ "child": {
+ "type": "object",
+ "title": "Child",
+ "required": ["tag"],
+ "properties": {
+ "tag": {"type": "string"},
+ "root": {"$ref": "#"},
+ },
+ },
+ },
+ }
+ )
+ validator: TypeAdapter[Any] = TypeAdapter(root_type)
+ doc = validator.validate_python(
+ {"value": "v", "child": {"tag": "t", "root": {"value": "r"}}}
+ )
+ assert doc.child.root.value == "r"
+ with pytest.raises(ValidationError):
+ # A Child-shaped object is not a valid root value.
+ validator.validate_python(
+ {"value": "v", "child": {"tag": "t", "root": {"tag": "x"}}}
+ )
+
class TestIdentifierNormalization:
"""Test suite for handling non-standard property names."""