Skip to content

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

Preserve typed additional properties in hydrated tool results (#5779)

PrathmeshPawar9f5d434a853c
diff --git a/docs/clients/tools.mdx b/docs/clients/tools.mdx
index fa0199b90..faeda9633 100644
--- a/docs/clients/tools.mdx
+++ b/docs/clients/tools.mdx
@@ -81,6 +81,8 @@ async with client:
Tool execution returns a `CallToolResult` object. The `.data` property provides fully hydrated Python objects including complex types like datetimes and UUIDs, reconstructed from the server's output schema.
+Pydantic models can combine named fields with typed additional properties. The client retains those additional fields in `.data` and hydrates their values using the advertised schema, including inside nested objects and lists.
+
```python
from datetime import datetime
from uuid import UUID
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema_type.py b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
index 5f4b982e7..0a80d2273 100644
--- a/fastmcp_slim/fastmcp/utilities/json_schema_type.py
+++ b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
@@ -79,6 +79,7 @@ from typing import (
Union,
cast,
get_type_hints,
+ overload,
)
from uuid import UUID
@@ -243,8 +244,11 @@ 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
+ # resolves to that class. None when the root converts to something other
+ # than a class (a union, a `$ref`, a dict), where "#" binds to the enclosing
+ # class being built instead.
+ root_class_name: str | None
+ enclosing_class_name: str | None = None
resolved_refs: dict[str, Any] = field(default_factory=dict)
building: set[tuple[str, str]] = field(default_factory=set)
classes: dict[tuple[str, str], type] = field(default_factory=dict)
@@ -379,14 +383,10 @@ def json_schema_to_type(
def _convert_normalized(schema: dict[str, Any], name: str | None) -> type:
root_hash, root_size = _schema_digest(schema)
- # `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"
conversion = _Conversion(
root_hash=root_hash,
root_size=root_size,
- root_class_name=_sanitize_name(name or root_title),
+ root_class_name=_root_class_name(schema, name),
)
token = _conversion.set(conversion)
try:
@@ -407,6 +407,21 @@ def _convert_normalized(schema: dict[str, Any], name: str | None) -> type:
_conversion.reset(token)
+def _root_class_name(schema: Mapping[str, Any], name: str | None) -> str | None:
+ """Name of the class the root schema converts to, or None if it has none.
+
+ Only an object root with properties becomes a class (including the
+ object member of a type list such as `["object", "null"]`).
+ """
+ schema_type = schema.get("type")
+ is_object = schema_type == "object" or (
+ isinstance(schema_type, list) and "object" in schema_type
+ )
+ if not is_object or not schema.get("properties"):
+ return None
+ return _sanitize_name(name or _schema_title(schema, "Root"))
+
+
def _resolve_recursive_types(conversion: _Conversion) -> None:
"""Bind recursive fields after every class in the conversion has been built."""
if not conversion.recursive_refs and not conversion.unchecked_defaults:
@@ -416,9 +431,11 @@ def _resolve_recursive_types(conversion: _Conversion) -> None:
}
# Root references use the root's public name, including when a nested
# mutually recursive class also points back to the conversion root.
- for cls in conversion.classes.values():
- if cls.__name__ == conversion.root_class_name:
- namespace[conversion.root_class_name] = cls
+ root_class_name = conversion.root_class_name
+ if root_class_name is not None:
+ for cls in conversion.classes.values():
+ if cls.__name__ == root_class_name:
+ namespace[root_class_name] = cls
for cls in conversion.classes.values():
if conversion.recursive_refs and is_dataclass(cls):
hints = get_type_hints(
@@ -984,8 +1001,8 @@ def _object_schema_to_type(
1. No ``properties`` with ``additionalProperties`` truthy β€” ``dict[str, T]``
(``T = Any`` when ``additionalProperties is True``, else the value schema's type)
2. No ``properties`` and no ``additionalProperties`` β€” ``dict[str, Any]``
- 3. Has ``properties`` and ``additionalProperties is True`` β€” Pydantic model
- (so ``extra="allow"`` can preserve unknown keys)
+ 3. Has ``properties`` and ``additionalProperties`` is true or a schema β€”
+ Pydantic model (so extra keys can be preserved and hydrated)
4. Has ``properties`` otherwise β€” dataclass
``name`` is used as the generated class name for cases 3 and 4; it falls
@@ -993,7 +1010,7 @@ def _object_schema_to_type(
"""
has_properties = bool(schema.get("properties"))
additional_props = schema.get("additionalProperties")
- class_name = name if name is not None else schema.get("title")
+ class_name = name if name is not None else _schema_title(schema)
if not has_properties and additional_props:
if additional_props is True:
@@ -1004,7 +1021,9 @@ def _object_schema_to_type(
if not has_properties and not additional_props:
return dict[str, Any]
- if has_properties and additional_props is True:
+ if has_properties and (
+ additional_props is True or isinstance(additional_props, Mapping)
+ ):
return _create_pydantic_model(schema, class_name, schemas, resolving_refs)
return _create_dataclass(schema, class_name, schemas, resolving_refs)
@@ -1074,14 +1093,19 @@ def _convert_schema(
return _object_schema_to_type(
schema, schemas, resolving_refs=resolving_refs
)
- return _create_dataclass(schema, schema.get("title", "<unknown>"), schemas)
+ return _create_dataclass(schema, _schema_title(schema, "<unknown>"), schemas)
# Handle references first
if "$ref" in schema:
ref = schema["$ref"]
# Handle self-reference
if ref == "#":
- return ForwardRef(_conversion.get().root_class_name)
+ conversion = _conversion.get()
+ return ForwardRef(
+ conversion.root_class_name
+ or conversion.enclosing_class_name
+ or _sanitize_name(_schema_title(schema, "Root"))
+ )
if ref in resolving_refs:
resolved = _resolve_ref(ref, schemas)
if isinstance(resolved, Mapping) and (
@@ -1219,6 +1243,20 @@ def _convert_schema(
return _get_from_type_handler(schema, schemas, resolving_refs)(schema)
+@overload
+def _schema_title(schema: Mapping[str, Any], default: str) -> str: ...
+@overload
+def _schema_title(schema: Mapping[str, Any], default: None = None) -> str | None: ...
+def _schema_title(schema: Mapping[str, Any], default: str | None = None) -> str | None:
+ """Return the schema's `title` when it can name a class, else `default`.
+
+ `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")
+ return title if isinstance(title, str) else default
+
+
def _sanitize_name(name: str) -> str:
"""Convert string to valid Python identifier."""
original_name = name
@@ -1260,6 +1298,7 @@ def safe_create_model(
field_definitions: Mapping[str, tuple[Any, Any]],
*,
config: ConfigDict | None = None,
+ extra_value_type: Any = None,
) -> type[BaseModel]:
"""Create a Pydantic model whose field names come from untrusted input.
@@ -1272,6 +1311,7 @@ def safe_create_model(
field_definitions: Maps each property name to `(annotation, default)`,
where `default` may be a `FieldInfo` or `...` for required fields.
config: Optional model configuration.
+ extra_value_type: Optional annotation for values of additional properties.
"""
fields: dict[str, Any] = {}
for prop_name, (annotation, default) in field_definitions.items():
@@ -1289,6 +1329,8 @@ def safe_create_model(
else:
default = Field(default=default, alias=prop_name)
fields[field_name] = (annotation, default)
+ if extra_value_type is not None:
+ fields["__pydantic_extra__"] = (dict[str, extra_value_type], Field(init=False))
return create_model(name, __config__=config, **fields)
@@ -1346,7 +1388,7 @@ def _create_pydantic_model(
resolving_refs: frozenset[str] = frozenset(),
) -> type:
"""Create Pydantic BaseModel from object schema with additionalProperties."""
- name = name or schema.get("title", "Root")
+ name = name or _schema_title(schema, "Root")
if name is None:
raise ValueError("Name is required")
sanitized_name = _sanitize_name(name)
@@ -1357,7 +1399,7 @@ def _create_pydantic_model(
# 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,
+ schema_hash + conversion.root_hash + (conversion.root_class_name or ""),
sanitized_name,
)
@@ -1370,11 +1412,14 @@ def _create_pydantic_model(
return conversion.reference(cache_key) # type: ignore[return-value] # ty:ignore[invalid-return-type]
conversion.building.add(cache_key)
+ enclosing_class_name = conversion.enclosing_class_name
+ conversion.enclosing_class_name = sanitized_name
try:
cls = _build_pydantic_model(
schema, sanitized_name, schemas or {}, resolving_refs
)
finally:
+ conversion.enclosing_class_name = enclosing_class_name
conversion.building.discard(cache_key)
conversion.classes[cache_key] = cls
return cls
@@ -1397,6 +1442,8 @@ def _build_pydantic_model(
if isinstance(prop_schema, bool):
field_type = _schema_to_type(prop_schema, schemas, resolving_refs)
prop_schema = {}
+ elif prop_schema.get("$ref") == "#":
+ field_type = ForwardRef(_conversion.get().root_class_name or name)
else:
field_type = _schema_to_type(prop_schema, schemas, resolving_refs)
@@ -1420,7 +1467,16 @@ def _build_pydantic_model(
else:
field_definitions[prop_name] = (Union[field_type, type(None)], None) # type: ignore[misc] # noqa: UP007 # ty:ignore[invalid-type-form]
- model = safe_create_model(name, field_definitions, config=ConfigDict(extra="allow"))
+ additional_props = schema.get("additionalProperties")
+ extra_value_type = None
+ if isinstance(additional_props, Mapping):
+ extra_value_type = _schema_to_type(additional_props, schemas, resolving_refs)
+ model = safe_create_model(
+ name,
+ field_definitions,
+ config=ConfigDict(extra="allow", validate_default=extra_value_type is not None),
+ extra_value_type=extra_value_type,
+ )
conversion = _conversion.get()
conversion.unchecked_defaults.extend((model, prop) for prop in unchecked)
return model
@@ -1433,7 +1489,7 @@ def _create_dataclass(
resolving_refs: frozenset[str] = frozenset(),
) -> type:
"""Create dataclass from object schema."""
- name = name or schema.get("title", "Root")
+ name = name or _schema_title(schema, "Root")
# Sanitize name for class creation
if name is None:
raise ValueError("Name is required")
@@ -1445,7 +1501,7 @@ def _create_dataclass(
# 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,
+ schema_hash + conversion.root_hash + (conversion.root_class_name or ""),
sanitized_name,
)
@@ -1458,9 +1514,12 @@ def _create_dataclass(
return conversion.reference(cache_key) # type: ignore[return-value] # ty:ignore[invalid-return-type]
conversion.building.add(cache_key)
+ enclosing_class_name = conversion.enclosing_class_name
+ conversion.enclosing_class_name = sanitized_name
try:
cls = _build_dataclass(schema, sanitized_name, schemas or {}, resolving_refs)
finally:
+ conversion.enclosing_class_name = enclosing_class_name
conversion.building.discard(cache_key)
if isinstance(cls, type):
conversion.classes[cache_key] = cls
@@ -1479,7 +1538,7 @@ def _build_dataclass(
ref = schema["$ref"]
if ref == "#":
# "#" resolves to the conversion root, not to this class.
- return ForwardRef(_conversion.get().root_class_name)
+ return ForwardRef(_conversion.get().root_class_name or sanitized_name)
if ref in resolving_refs:
return Any
schema = _resolve_ref(ref, schemas)
@@ -1510,7 +1569,7 @@ def _build_dataclass(
elif prop_schema.get("$ref") == "#":
# 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)
+ field_type = ForwardRef(_conversion.get().root_class_name or sanitized_name)
else:
field_type = _schema_to_type(prop_schema, schemas, resolving_refs)
diff --git a/tests/client/client/test_error_handling.py b/tests/client/client/test_error_handling.py
index 25bf4d5bb..ec484855f 100644
--- a/tests/client/client/test_error_handling.py
+++ b/tests/client/client/test_error_handling.py
@@ -25,6 +25,27 @@ from fastmcp.server.server import FastMCP
class TestErrorHandling:
+ async def test_invalid_typed_extra_leaves_parser_data_unset(self):
+ payload = {"name": "cache", "hits": "many"}
+ result = mcp_types.CallToolResult(content=[], structured_content=payload)
+ schema = {
+ "type": "object",
+ "properties": {"name": {"type": "string"}},
+ "required": ["name"],
+ "additionalProperties": {"type": "integer"},
+ }
+
+ parsed = await _parse_call_tool_result(
+ name="counters",
+ result=result,
+ tool_output_schemas={"counters": schema},
+ list_tools_fn=None,
+ )
+
+ assert parsed.structured_content == payload
+ assert parsed.data is None
+ assert not parsed.is_error
+
async def test_general_tool_exceptions_are_not_masked_by_default(self):
mcp = FastMCP("TestServer")
diff --git a/tests/client/test_result_hydration.py b/tests/client/test_result_hydration.py
index acb24ceb9..dd2389321 100644
--- a/tests/client/test_result_hydration.py
+++ b/tests/client/test_result_hydration.py
@@ -9,10 +9,10 @@ from typing import Any
from uuid import UUID
import pytest
-from pydantic import BaseModel
+from pydantic import BaseModel, ConfigDict, Field
from fastmcp import Client, FastMCP
-from fastmcp.tools import Tool
+from fastmcp.tools import Tool, ToolResult
class Reading(BaseModel):
@@ -23,6 +23,48 @@ class Reading(BaseModel):
ident: UUID
+class Counters(BaseModel):
+ model_config = ConfigDict(extra="allow")
+ __pydantic_extra__: dict[str, int] = Field(init=False) # ty:ignore[invalid-mutable-override]
+ name: str
+
+
+class CounterCollection(BaseModel):
+ counters: list[Counters]
+
+
[email protected]("shape", ["model", "list", "nested"])
+async def test_typed_extra_fields_survive_tool_result_hydration(shape: str) -> None:
+ mcp = FastMCP()
+ counters = Counters(name="cache", hits=12, misses=3)
+
+ @mcp.tool
+ def model_result() -> Counters:
+ return counters
+
+ @mcp.tool
+ def list_result() -> list[Counters]:
+ return [counters]
+
+ @mcp.tool
+ def nested_result() -> CounterCollection:
+ return CounterCollection(counters=[counters])
+
+ async with Client(mcp) as client:
+ result = await client.call_tool(f"{shape}_result")
+
+ data = result.data
+ if shape == "list":
+ data = data[0]
+ elif shape == "nested":
+ data = data.counters[0]
+
+ assert data.name == "cache"
+ assert data.hits == 12
+ assert type(data.hits) is int
+ assert data.misses == 3
+
+
class Item(BaseModel):
name: str
when: date
@@ -34,6 +76,57 @@ class TreeNode(BaseModel):
class TestStructuredResultHydration:
+ @pytest.mark.parametrize("title", ["Node", "Order Item (v2)"])
+ async def test_typed_extras_survive_titled_recursive_results(self, title: str):
+ mcp = FastMCP()
+ schema = {
+ "type": "object",
+ "title": title,
+ "properties": {
+ "day": {"type": "string", "format": "date"},
+ "children": {"type": "array", "items": {"$ref": "#"}},
+ },
+ "required": ["day"],
+ "additionalProperties": {"type": "integer"},
+ }
+ payload = {
+ "day": "2026-10-17",
+ "hits": 12,
+ "children": [{"day": "2026-10-18", "misses": 3}],
+ }
+
+ @mcp.tool(output_schema=schema)
+ def recursive_counters() -> ToolResult:
+ return ToolResult(content=[], structured_content=payload)
+
+ async with Client(mcp) as client:
+ result = await client.call_tool("recursive_counters")
+
+ assert result.structured_content == payload
+ assert result.data.day == date(2026, 10, 17)
+ assert result.data.hits == 12
+ assert type(result.data.hits) is int
+ child = result.data.children[0]
+ assert isinstance(child, type(result.data))
+ assert child.day == date(2026, 10, 18)
+ assert child.misses == 3
+ assert type(child.misses) is int
+
+ async def test_invalid_typed_extra_is_rejected_before_hydration(self):
+ mcp = FastMCP()
+ payload = {"name": "cache", "hits": "many"}
+
+ @mcp.tool(output_schema=Counters.model_json_schema())
+ def invalid_counters() -> ToolResult:
+ return ToolResult(content=[], structured_content=payload)
+
+ async with Client(mcp) as client:
+ with pytest.raises(
+ RuntimeError,
+ match="Invalid structured content returned by tool invalid_counters",
+ ):
+ await client.call_tool("invalid_counters")
+
@pytest.mark.parametrize(
("field_schema", "value", "expected"),
[
diff --git a/tests/utilities/json_schema_type/test_advanced.py b/tests/utilities/json_schema_type/test_advanced.py
index 27dbd302b..d687c7baf 100644
--- a/tests/utilities/json_schema_type/test_advanced.py
+++ b/tests/utilities/json_schema_type/test_advanced.py
@@ -547,6 +547,126 @@ class TestCircularReferences:
root_type = json_schema_to_type(schema)
assert TypeAdapter(root_type).validate_python(valid_value) == valid_value
+ @pytest.mark.parametrize(
+ "additional_properties",
+ [{}, {"additionalProperties": True}, {"additionalProperties": {}}],
+ ids=["dataclass", "extras-allowed", "typed-extras"],
+ )
+ def test_non_string_title_names_generated_classes_root(self, additional_properties):
+ # Generated classes fall back to "Root" for a non-string title, the
+ # same name `"$ref": "#"` resolves to.
+ root_type = json_schema_to_type(
+ {
+ "type": "object",
+ "title": 5,
+ "properties": {
+ "name": {"type": "string"},
+ "next": {"anyOf": [{"$ref": "#"}, {"type": "null"}]},
+ "child": {
+ "type": "object",
+ "title": ["not", "a", "name"],
+ "properties": {"tag": {"type": "string"}},
+ },
+ },
+ **additional_properties,
+ }
+ )
+ assert root_type.__name__ == "Root"
+
+ validator: TypeAdapter[Any] = TypeAdapter(root_type)
+ node = validator.validate_python(
+ {"name": "a", "next": {"name": "b"}, "child": {"tag": "t"}}
+ )
+ assert isinstance(node.next, root_type)
+ assert node.next.name == "b"
+ assert node.child.tag == "t"
+
+ @pytest.mark.parametrize(
+ "root",
+ [
+ pytest.param(
+ {"anyOf": [{"$ref": "#/$defs/Node"}, {"type": "null"}]},
+ id="nullable-union",
+ ),
+ pytest.param(
+ {"title": "Wrapper", "anyOf": [{"$ref": "#/$defs/Node"}]},
+ id="titled-union",
+ ),
+ pytest.param({"$ref": "#/$defs/Node"}, id="ref"),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "next_schema",
+ [
+ pytest.param({"anyOf": [{"$ref": "#"}, {"type": "null"}]}, id="union"),
+ pytest.param({"$ref": "#"}, id="direct"),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "extras",
+ [{}, {"additionalProperties": {"type": "integer"}}],
+ ids=["dataclass", "typed-extras"],
+ )
+ @pytest.mark.parametrize("title", [None, "Node"])
+ def test_wrapper_root_self_reference_resolves(
+ self, root, next_schema, extras, title
+ ):
+ # A root that is not itself an object generates no root class, so
+ # "#" binds to the object it wraps rather than to a missing class.
+ node = {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "child": {
+ "type": "object",
+ "title": "Child",
+ "properties": {"tag": {"type": "string"}},
+ },
+ "next": next_schema,
+ },
+ "required": ["name"],
+ **extras,
+ }
+ if title is not None:
+ node["title"] = title
+ root_type = json_schema_to_type({**root, "$defs": {"Node": node}})
+
+ validator: TypeAdapter[Any] = TypeAdapter(root_type)
+ result = validator.validate_python({"name": "a", "next": {"name": "b"}})
+ assert result.next.name == "b"
+ assert type(result.next) is type(result)
+ assert type(result).__name__ == (title or "Root")
+ assert result.next.next is None
+ with pytest.raises(ValidationError):
+ validator.validate_python({"name": "a", "next": {"name": []}})
+
+ @pytest.mark.parametrize("wrapper", ["ref", "union"])
+ def test_titled_wrapper_root_recursive_extras(self, wrapper):
+ root = {"$ref": "#/$defs/Node"}
+ if wrapper == "union":
+ root = {"anyOf": [root, {"type": "null"}]}
+ root_type = json_schema_to_type(
+ {
+ **root,
+ "$defs": {
+ "Node": {
+ "type": "object",
+ "title": "Node",
+ "properties": {"name": {"type": "string"}},
+ "required": ["name"],
+ "additionalProperties": {"$ref": "#"},
+ }
+ },
+ }
+ )
+ validator: TypeAdapter[Any] = TypeAdapter(root_type)
+ result = validator.validate_python({"name": "a", "extra": {"name": "b"}})
+ assert type(result).__name__ == "Node"
+ assert type(result.extra) is type(result)
+ assert result.extra.name == "b"
+ with pytest.raises(ValidationError):
+ validator.validate_python({"name": "a", "extra": {"name": []}})
+
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.
diff --git a/tests/utilities/json_schema_type/test_typed_extra_fields.py b/tests/utilities/json_schema_type/test_typed_extra_fields.py
new file mode 100644
index 000000000..e87087855
--- /dev/null
+++ b/tests/utilities/json_schema_type/test_typed_extra_fields.py
@@ -0,0 +1,146 @@
+from datetime import date
+from typing import Any
+
+import pytest
+from pydantic import TypeAdapter, ValidationError
+
+from fastmcp.utilities.json_schema_type import json_schema_to_type
+
+
+ ("extra_schema", "value", "expected"),
+ [
+ ({"type": "integer"}, 12, 12),
+ ({"type": "boolean"}, True, True),
+ ({"type": "string", "format": "date"}, "2026-10-10", date(2026, 10, 10)),
+ ({}, {"arbitrary": [1, "two"]}, {"arbitrary": [1, "two"]}),
+ ],
+)
+def test_typed_extra_fields_are_preserved_and_hydrated(
+ extra_schema: dict[str, Any], value: Any, expected: Any
+) -> None:
+ schema = {
+ "type": "object",
+ "properties": {"name": {"type": "string"}},
+ "required": ["name"],
+ "additionalProperties": extra_schema,
+ }
+ result: Any = TypeAdapter(json_schema_to_type(schema)).validate_python(
+ {"name": "cache", "extra": value}
+ )
+ assert result.name == "cache"
+ assert result.extra == expected
+ assert type(result.extra) is type(expected)
+
+
+def test_typed_extra_fields_validate_their_schema() -> None:
+ schema = {
+ "type": "object",
+ "properties": {"name": {"type": "string"}},
+ "additionalProperties": {"type": "integer", "minimum": 0},
+ }
+ adapter = TypeAdapter(json_schema_to_type(schema))
+ with pytest.raises(ValidationError):
+ adapter.validate_python({"name": "cache", "hits": -1})
+
+
+def test_typed_extra_fields_resolve_references() -> None:
+ schema = {
+ "type": "object",
+ "properties": {"name": {"type": "string"}},
+ "additionalProperties": {"$ref": "#/$defs/Reading"},
+ "$defs": {
+ "Reading": {
+ "type": "object",
+ "properties": {"day": {"type": "string", "format": "date"}},
+ "required": ["day"],
+ }
+ },
+ }
+ result: Any = TypeAdapter(json_schema_to_type(schema)).validate_python(
+ {"name": "cache", "extra": {"day": "2026-10-10"}}
+ )
+ assert result.extra.day == date(2026, 10, 10)
+
+
+def test_declared_reserved_names_do_not_override_extra_field_validation() -> None:
+ schema = {
+ "type": "object",
+ "properties": {"__pydantic_extra__": {"type": "string"}},
+ "required": ["__pydantic_extra__"],
+ "additionalProperties": {"type": "integer"},
+ }
+ result: Any = TypeAdapter(json_schema_to_type(schema)).validate_python(
+ {"__pydantic_extra__": "declared", "hits": 12}
+ )
+ assert result.model_dump(by_alias=True) == {
+ "__pydantic_extra__": "declared",
+ "hits": 12,
+ }
+ assert result.hits == 12
+
+
+def test_typed_extra_fields_hydrate_declared_defaults() -> None:
+ schema = {
+ "type": "object",
+ "properties": {
+ "day": {"type": "string", "format": "date", "default": "2026-01-01"},
+ "reading": {
+ "type": "object",
+ "properties": {"day": {"type": "string", "format": "date"}},
+ "required": ["day"],
+ "default": {"day": "2026-01-02"},
+ },
+ },
+ "additionalProperties": {"type": "integer"},
+ }
+ result: Any = TypeAdapter(json_schema_to_type(schema)).validate_python({"hits": 12})
+ assert result.day == date(2026, 1, 1)
+ assert result.reading.day == date(2026, 1, 2)
+ assert result.hits == 12
+
+
[email protected]("title", ["Node", "Order Item (v2)"])
[email protected]("name", [None, "Named Node"])
+def test_typed_extra_fields_resolve_root_references(
+ title: str, name: str | None
+) -> None:
+ schema = {
+ "type": "object",
+ "title": title,
+ "properties": {"day": {"type": "string", "format": "date"}},
+ "required": ["day"],
+ "additionalProperties": {"$ref": "#"},
+ }
+ model = json_schema_to_type(schema, name=name)
+ result: Any = TypeAdapter(model).validate_python(
+ {"day": "2026-01-01", "child": {"day": "2026-01-02"}}
+ )
+ assert result.day == date(2026, 1, 1)
+ assert isinstance(result.child, model)
+ assert result.child.day == date(2026, 1, 2)
+
+
[email protected]("title", ["Node", "Order Item (v2)"])
[email protected]("name", [None, "Named Node"])
+def test_typed_extra_models_resolve_declared_root_references(
+ title: str, name: str | None
+) -> None:
+ schema = {
+ "type": "object",
+ "title": title,
+ "properties": {
+ "day": {"type": "string", "format": "date"},
+ "child": {"$ref": "#"},
+ },
+ "required": ["day"],
+ "additionalProperties": {"type": "integer"},
+ }
+ model = json_schema_to_type(schema, name=name)
+ result: Any = TypeAdapter(model).validate_python(
+ {"day": "2026-01-01", "child": {"day": "2026-01-02"}, "hits": 12}
+ )
+ assert result.day == date(2026, 1, 1)
+ assert isinstance(result.child, model)
+ assert result.child.day == date(2026, 1, 2)
+ assert result.hits == 12