Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(py): preserve nested provider argument presence

jkomyno64fbc4ee0393
diff --git a/python/composio/utils/schema_converter.py b/python/composio/utils/schema_converter.py
index 21c669aa2..85ab1b71f 100644
--- a/python/composio/utils/schema_converter.py
+++ b/python/composio/utils/schema_converter.py
@@ -10,6 +10,7 @@ We handle those by pre-filtering them before passing to the library.
"""
import re
+import types
import typing as t
from functools import reduce
from urllib.parse import unquote
@@ -40,6 +41,7 @@ from composio.utils.logging import get as get_logger
logger = get_logger(__name__)
_MISSING = object()
+_EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE = "__composio_explicit_default_fields__"
class _UnsatisfiableSchema:
@@ -253,8 +255,8 @@ class _DynamicKeyValidator(t.NamedTuple):
if self.materializer is None:
return value
try:
- return self.materializer.dump_python(
- self.materializer.validate_python(value)
+ return _materialized_value_to_python(
+ self.materializer.validate_python(_materialized_value_to_python(value))
)
except (TypeError, ValueError):
# JSON Schema alone decides acceptance. Pydantic is only retained
@@ -264,6 +266,30 @@ class _DynamicKeyValidator(t.NamedTuple):
return value
+def _materialized_value_to_python(value: t.Any) -> t.Any:
+ """Convert a previous materializer result back into validation input."""
+ if isinstance(value, BaseModel):
+ included_fields = set(value.model_fields_set)
+ included_fields.update(
+ getattr(type(value), _EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE, ())
+ )
+ result = {}
+ for name, field in type(value).model_fields.items():
+ if name not in included_fields:
+ continue
+ alias = field.serialization_alias or field.alias
+ output_name = alias if isinstance(alias, str) else name
+ result[output_name] = _materialized_value_to_python(getattr(value, name))
+ for name, item in (value.model_extra or {}).items():
+ result[name] = _materialized_value_to_python(item)
+ return result
+ if isinstance(value, dict):
+ return {key: _materialized_value_to_python(item) for key, item in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [_materialized_value_to_python(item) for item in value]
+ return value
+
+
class _ObjectPolicy(t.NamedTuple):
"""Compiled dynamic-key policy for one JSON Schema object node.
@@ -335,6 +361,210 @@ def _resolve_local_json_pointer(
return current
+def _resolve_default_metadata_schema(
+ schema: t.Any,
+ root_schema: t.Dict[str, t.Any],
+ visited_refs: t.Optional[t.Set[str]] = None,
+) -> t.Any:
+ """Resolve a schema node without traversing instance-valued annotations."""
+ if not isinstance(schema, dict):
+ return schema
+ reference = schema.get("$ref")
+ if not isinstance(reference, str) or not reference.startswith("#/"):
+ return schema
+ if visited_refs is None:
+ visited_refs = set()
+ if reference in visited_refs:
+ return {key: value for key, value in schema.items() if key != "$ref"}
+ visited_refs.add(reference)
+
+ target = _resolve_local_json_pointer(reference, root_schema)
+ if not isinstance(target, dict):
+ return schema
+ resolved = _resolve_default_metadata_schema(target, root_schema, visited_refs)
+ if not isinstance(resolved, dict):
+ return schema
+ return {
+ **resolved,
+ **{key: value for key, value in schema.items() if key != "$ref"},
+ }
+
+
+def _default_metadata_properties(
+ schema: t.Any,
+ root_schema: t.Dict[str, t.Any],
+) -> t.Dict[str, t.Any]:
+ schema = _resolve_default_metadata_schema(schema, root_schema)
+ if not isinstance(schema, dict) or "anyOf" in schema or "oneOf" in schema:
+ return {}
+ properties = schema.get("properties")
+ result = dict(properties) if isinstance(properties, dict) else {}
+ for option in schema.get("allOf", []):
+ result.update(_default_metadata_properties(option, root_schema))
+ return result
+
+
+def _default_metadata_schema_for_model(
+ schema: t.Any,
+ model: t.Type[BaseModel],
+ root_schema: t.Dict[str, t.Any],
+) -> t.Any:
+ schema = _resolve_default_metadata_schema(schema, root_schema)
+ if not isinstance(schema, dict):
+ return None
+ for combiner in ("anyOf", "oneOf"):
+ titled = [
+ option
+ for option in schema.get(combiner, [])
+ if isinstance(option, dict) and option.get("title") == model.__name__
+ ]
+ if len(titled) == 1:
+ return titled[0]
+ return schema if "anyOf" not in schema and "oneOf" not in schema else None
+
+
+def _default_metadata_field_aliases(
+ model: t.Type[BaseModel],
+) -> t.Dict[str, t.Tuple[str, t.Any]]:
+ fields = {}
+ for name, field in model.model_fields.items():
+ alias = field.serialization_alias or field.alias
+ fields[alias if isinstance(alias, str) else name] = (name, field)
+ return fields
+
+
+def _mark_explicit_default_fields(
+ annotation: t.Any,
+ schema: t.Any,
+ root_schema: t.Dict[str, t.Any],
+ visiting: t.Optional[t.Set[t.Type[BaseModel]]] = None,
+) -> None:
+ """Attach recursive default-presence metadata to generated model classes."""
+ origin = t.get_origin(annotation)
+ arguments = t.get_args(annotation)
+ if origin in (t.Union, types.UnionType):
+ options: t.List[t.Dict[str, t.Any]] = []
+ resolved_schema = _resolve_default_metadata_schema(schema, root_schema)
+ if isinstance(resolved_schema, dict):
+ for combiner in ("anyOf", "oneOf"):
+ options.extend(
+ option
+ for option in resolved_schema.get(combiner, [])
+ if isinstance(option, dict)
+ )
+ for index, argument in enumerate(arguments):
+ argument_schema = None
+ if isinstance(argument, type) and issubclass(argument, BaseModel):
+ titled = [
+ option
+ for option in options
+ if option.get("title") == argument.__name__
+ ]
+ if len(titled) == 1:
+ argument_schema = titled[0]
+ if argument_schema is None and index < len(options):
+ argument_schema = options[index]
+ _mark_explicit_default_fields(
+ argument,
+ argument_schema,
+ root_schema,
+ visiting,
+ )
+ return
+
+ if origin in (list, set, frozenset):
+ resolved_schema = _resolve_default_metadata_schema(schema, root_schema)
+ item_schema = (
+ resolved_schema.get("items") if isinstance(resolved_schema, dict) else None
+ )
+ if arguments:
+ _mark_explicit_default_fields(
+ arguments[0],
+ item_schema,
+ root_schema,
+ visiting,
+ )
+ return
+
+ if origin is tuple:
+ resolved_schema = _resolve_default_metadata_schema(schema, root_schema)
+ items = (
+ resolved_schema.get("items") if isinstance(resolved_schema, dict) else None
+ )
+ for index, argument in enumerate(arguments):
+ item_schema = (
+ items[index]
+ if isinstance(items, list) and index < len(items)
+ else items
+ if isinstance(items, dict)
+ else None
+ )
+ _mark_explicit_default_fields(
+ argument,
+ item_schema,
+ root_schema,
+ visiting,
+ )
+ return
+
+ if origin is dict:
+ resolved_schema = _resolve_default_metadata_schema(schema, root_schema)
+ additional = (
+ resolved_schema.get("additionalProperties")
+ if isinstance(resolved_schema, dict)
+ else None
+ )
+ if len(arguments) == 2:
+ _mark_explicit_default_fields(
+ arguments[1],
+ additional,
+ root_schema,
+ visiting,
+ )
+ return
+
+ if not isinstance(annotation, type) or not issubclass(annotation, BaseModel):
+ return
+
+ model_schema = _default_metadata_schema_for_model(
+ schema,
+ annotation,
+ root_schema,
+ )
+ properties = _default_metadata_properties(model_schema, root_schema)
+ fields = _default_metadata_field_aliases(annotation)
+ explicit_defaults = {
+ internal_name
+ for alias, (internal_name, field) in fields.items()
+ if (not field.is_required() and field.default is not None)
+ or (isinstance(properties.get(alias), dict) and "default" in properties[alias])
+ }
+ explicit_defaults.update(
+ getattr(annotation, _EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE, ())
+ )
+ setattr(
+ annotation,
+ _EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE,
+ frozenset(explicit_defaults),
+ )
+
+ if visiting is None:
+ visiting = set()
+ if annotation in visiting:
+ return
+ visiting.add(annotation)
+ try:
+ for alias, (_, field) in fields.items():
+ _mark_explicit_default_fields(
+ field.annotation,
+ properties.get(alias),
+ root_schema,
+ visiting,
+ )
+ finally:
+ visiting.remove(annotation)
+
+
# Draft 7 keywords whose value is itself a schema. `items` and `dependencies`
# are handled separately because they also accept non-schema forms.
_SCHEMA_VALUED_KEYWORDS = frozenset(
@@ -434,6 +664,7 @@ def _dynamic_key_validator(
materializer = None
if _contains_default(schema):
annotation = json_schema_to_pydantic_type(schema, root_schema=root_schema)
+ _mark_explicit_default_fields(annotation, schema, root_schema)
materializer = TypeAdapter(annotation)
return _DynamicKeyValidator(
diff --git a/python/composio/utils/shared.py b/python/composio/utils/shared.py
index 7faa3e8be..37512dfca 100644
--- a/python/composio/utils/shared.py
+++ b/python/composio/utils/shared.py
@@ -22,6 +22,8 @@ from composio.utils.schema_converter import (
CONTAINER_TYPE,
FALLBACK_VALUES,
PYDANTIC_TYPE_TO_PYTHON_TYPE,
+ _EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE,
+ _mark_explicit_default_fields,
apply_object_policy,
json_schema_to_pydantic_type,
)
@@ -55,7 +57,7 @@ reserved_names = ["validate"]
_OBJ_MARKER = "-_object_-"
_ARR_MARKER = "-_array_-"
_MAX_PROVIDER_ALIAS_LENGTH = 64
-_EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE = "__composio_explicit_default_fields__"
+_MISSING_ARGUMENT = object()
def normalize_tool_arguments(arguments: t.Any) -> t.Dict[str, t.Any]:
@@ -113,25 +115,108 @@ def validate_and_serialize_tool_arguments(
Pydantic models use ``None`` for optional fields that were not supplied, so a
plain ``model_dump()`` changes omission into an explicit null. Conversely,
``exclude_unset=True`` also drops defaults declared by the source JSON Schema.
- Track those defaults on the generated model and combine them with
- ``model_fields_set`` so aliases, explicit nulls, defaults, and dynamic extras
- all survive without padding the payload.
+ Generated models track fields with declared defaults. Combining that metadata
+ recursively with each selected model's ``model_fields_set`` preserves aliases,
+ explicit nulls, defaults, and validated dynamic extras without replaying the
+ source schema during execution.
"""
validated = args_schema.model_validate(arguments)
- included_fields = set(validated.model_fields_set)
- included_fields.update(
- getattr(type(validated), _EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE, ())
- )
return t.cast(
t.Dict[str, t.Any],
- validated.model_dump(
- mode="python",
- by_alias=True,
- include=included_fields,
+ _serialize_present_arguments(
+ validated,
+ validated.model_dump(mode="python", by_alias=True),
+ arguments,
),
)
+def _model_field_aliases(
+ model: t.Type[BaseModel],
+) -> t.Dict[str, t.Tuple[str, FieldInfo]]:
+ fields = {}
+ for name, field in model.model_fields.items():
+ alias = field.serialization_alias or field.alias
+ fields[alias if isinstance(alias, str) else name] = (name, field)
+ return fields
+
+
+def _serialize_present_arguments(
+ validated: t.Any,
+ serialized: t.Any,
+ supplied: t.Any,
+) -> t.Any:
+ """Recursively remove values Pydantic added for omitted optional fields."""
+ if supplied is _MISSING_ARGUMENT:
+ return serialized
+
+ if isinstance(validated, BaseModel) and isinstance(serialized, dict):
+ fields = _model_field_aliases(type(validated))
+ included_fields = set(validated.model_fields_set)
+ included_fields.update(
+ getattr(type(validated), _EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE, ())
+ )
+ supplied_values = supplied if isinstance(supplied, dict) else {}
+ result: t.Dict[str, t.Any] = {}
+ for key, value in serialized.items():
+ field = fields.get(key)
+ if field is not None:
+ name, _ = field
+ if name not in included_fields:
+ continue
+ child_validated = getattr(validated, name)
+ if key in supplied_values:
+ child_supplied = supplied_values[key]
+ elif name in supplied_values:
+ child_supplied = supplied_values[name]
+ else:
+ child_supplied = _MISSING_ARGUMENT
+ else:
+ extra = validated.model_extra
+ if extra is None or key not in extra:
+ continue
+ child_validated = extra[key]
+ child_supplied = supplied_values.get(key, _MISSING_ARGUMENT)
+ result[key] = _serialize_present_arguments(
+ child_validated,
+ value,
+ child_supplied,
+ )
+ return result
+
+ if isinstance(serialized, dict):
+ supplied_values = supplied if isinstance(supplied, dict) else {}
+ validated_values = validated if isinstance(validated, dict) else {}
+ return {
+ key: _serialize_present_arguments(
+ validated_values.get(key, _MISSING_ARGUMENT),
+ value,
+ supplied_values.get(key, _MISSING_ARGUMENT),
+ )
+ for key, value in serialized.items()
+ if key in supplied_values or key in validated_values
+ }
+
+ if isinstance(serialized, (list, tuple)):
+ supplied_items = supplied if isinstance(supplied, (list, tuple)) else ()
+ validated_items = validated if isinstance(validated, (list, tuple)) else ()
+ items = [
+ _serialize_present_arguments(
+ validated_items[index]
+ if index < len(validated_items)
+ else _MISSING_ARGUMENT,
+ value,
+ supplied_items[index]
+ if index < len(supplied_items)
+ else _MISSING_ARGUMENT,
+ )
+ for index, value in enumerate(serialized)
+ ]
+ return tuple(items) if isinstance(serialized, tuple) else items
+
+ return serialized
+
+
def _make_safe_name(name: str) -> str:
"""Append ``_rs`` to a Python keyword so it can be used as a parameter name."""
return f"{name}_rs"
@@ -487,7 +572,6 @@ def json_schema_to_model(
if model_name is None:
model_name = "GeneratedModel"
field_definitions = {}
- explicit_default_fields: t.Set[str] = set()
for name, prop in json_schema.get("properties", {}).items():
updated_name, pydantic_type, pydantic_field = json_schema_to_pydantic_field(
name,
@@ -497,16 +581,13 @@ def json_schema_to_model(
root_schema=json_schema,
)
field_definitions[updated_name] = (pydantic_type, pydantic_field)
- if not skip_default and "default" in prop:
- explicit_default_fields.add(updated_name)
# The dynamic-key policy is shared with `json_schema_to_pydantic_type` so the
# two entry points cannot disagree about which arguments survive conversion.
base_model = create_model(model_name, **field_definitions) # type: ignore
- setattr(
- base_model,
- _EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE,
- frozenset(explicit_default_fields),
- )
+ if skip_default:
+ setattr(base_model, _EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE, frozenset())
+ else:
+ _mark_explicit_default_fields(base_model, json_schema, json_schema)
return apply_object_policy(
json_schema,
base_model,
diff --git a/python/tests/test_provider_argument_serialization.py b/python/tests/test_provider_argument_serialization.py
index 794a7e9f1..d4e988f2a 100644
--- a/python/tests/test_provider_argument_serialization.py
+++ b/python/tests/test_provider_argument_serialization.py
@@ -5,6 +5,10 @@ import typing as t
import pytest
from composio.client.types import Tool, tool_list_response
+from composio.utils.shared import (
+ json_schema_to_model,
+ validate_and_serialize_tool_arguments,
+)
PROVIDERS = ("crewai", "langchain", "langgraph")
@@ -98,6 +102,383 @@ def test_provider_serialization_preserves_argument_presence_and_aliases(name: st
]
[email protected]("name", PROVIDERS)
+def test_provider_serialization_preserves_nested_argument_presence(name: str):
+ wrapped, received = _wrap(
+ name,
+ {
+ "type": "object",
+ "title": "NestedArguments",
+ "properties": {
+ "payload": {
+ "type": "object",
+ "title": "Payload",
+ "properties": {
+ "query": {"type": "string"},
+ "note": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "explicit_null": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "null_default": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "default": None,
+ },
+ "page": {"type": "integer", "default": 5},
+ "items": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "title": "Item",
+ "properties": {
+ "name": {"type": "string"},
+ "label": {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "null"},
+ ],
+ },
+ "enabled": {
+ "type": "boolean",
+ "default": True,
+ },
+ },
+ "required": ["name"],
+ },
+ },
+ "mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "object",
+ "title": "Entry",
+ "properties": {
+ "name": {"type": "string"},
+ "label": {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "null"},
+ ],
+ },
+ "null_default": {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "null"},
+ ],
+ "default": None,
+ },
+ "config": {
+ "type": "object",
+ "properties": {
+ "implicit": {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "null"},
+ ],
+ },
+ "null_default": {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "null"},
+ ],
+ "default": None,
+ },
+ },
+ },
+ "score": {"type": "integer", "default": 2},
+ },
+ "required": ["name", "config"],
+ },
+ },
+ },
+ "required": ["query", "items", "mapping"],
+ },
+ },
+ "required": ["payload"],
+ },
+ )
+
+ _run(
+ name,
+ wrapped,
+ {
+ "payload": {
+ "query": "agents",
+ "explicit_null": None,
+ "items": [
+ {"name": "first"},
+ {"name": "second", "label": None},
+ ],
+ "mapping": {
+ "one": {"name": "one", "config": {}},
+ "two": {"name": "two", "label": None, "config": {}},
+ },
+ },
+ },
+ )
+
+ assert received == [
+ {
+ "payload": {
+ "query": "agents",
+ "explicit_null": None,
+ "null_default": None,
+ "page": 5,
+ "items": [
+ {"name": "first", "enabled": True},
+ {"name": "second", "label": None, "enabled": True},
+ ],
+ "mapping": {
+ "one": {
+ "name": "one",
+ "null_default": None,
+ "config": {"null_default": None},
+ "score": 2,
+ },
+ "two": {
+ "name": "two",
+ "label": None,
+ "null_default": None,
+ "config": {"null_default": None},
+ "score": 2,
+ },
+ },
+ },
+ }
+ ]
+
+
[email protected]("name", PROVIDERS)
+def test_provider_serialization_preserves_dynamic_array_item_defaults(name: str):
+ wrapped, received = _wrap(
+ name,
+ {
+ "type": "object",
+ "title": "DynamicArrayArguments",
+ "patternProperties": {
+ "^items_": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "implicit": {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "null"},
+ ],
+ },
+ "null_default": {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "null"},
+ ],
+ "default": None,
+ },
+ },
+ },
+ },
+ },
+ "additionalProperties": False,
+ },
+ )
+
+ _run(name, wrapped, {"items_a": [{}, {"implicit": None}]})
+
+ assert received == [
+ {
+ "items_a": [
+ {"null_default": None},
+ {"implicit": None, "null_default": None},
+ ]
+ }
+ ]
+
+
[email protected]("name", PROVIDERS)
+def test_provider_serialization_preserves_presence_across_overlapping_patterns(
+ name: str,
+):
+ object_schema = {
+ "type": "object",
+ "properties": {
+ "implicit": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "defaulted": {"type": "integer", "default": 1},
+ },
+ }
+ wrapped, received = _wrap(
+ name,
+ {
+ "type": "object",
+ "title": "OverlappingPatternArguments",
+ "patternProperties": {
+ "^x": {**object_schema, "title": "First"},
+ "x$": {**object_schema, "title": "Second"},
+ },
+ "additionalProperties": False,
+ },
+ )
+
+ _run(name, wrapped, {"x": {}})
+
+ assert received == [{"x": {"defaulted": 1}}]
+
+
[email protected]("name", PROVIDERS)
[email protected]("combiner", ("anyOf", "oneOf"))
+def test_provider_serialization_uses_selected_composed_object_defaults(
+ name: str,
+ combiner: str,
+):
+ wrapped, received = _wrap(
+ name,
+ {
+ "type": "object",
+ "title": "ComposedArguments",
+ "properties": {
+ "payload": {
+ combiner: [
+ {
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "enum": ["defaulted"]},
+ "value": {"type": "integer", "default": 5},
+ "config": {
+ "type": "object",
+ "properties": {
+ "nested": {
+ "type": "integer",
+ "default": 7,
+ },
+ },
+ },
+ },
+ "required": ["kind", "config"],
+ },
+ {
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "enum": ["plain"]},
+ "value": {
+ "anyOf": [
+ {"type": "integer"},
+ {"type": "null"},
+ ],
+ },
+ "config": {
+ "type": "object",
+ "properties": {
+ "nested": {
+ "anyOf": [
+ {"type": "integer"},
+ {"type": "null"},
+ ],
+ },
+ },
+ },
+ },
+ "required": ["kind", "config"],
+ },
+ ],
+ },
+ },
+ "required": ["payload"],
+ },
+ )
+
+ _run(name, wrapped, {"payload": {"kind": "plain", "config": {}}})
+ _run(name, wrapped, {"payload": {"kind": "defaulted", "config": {}}})
+
+ assert received == [
+ {"payload": {"kind": "plain", "config": {}}},
+ {
+ "payload": {
+ "kind": "defaulted",
+ "value": 5,
+ "config": {"nested": 7},
+ }
+ },
+ ]
+
+
[email protected]("name", PROVIDERS)
[email protected]("combiner", ("anyOf", "oneOf"))
+def test_provider_serialization_preserves_selected_composed_null_defaults(
+ name: str,
+ combiner: str,
+):
+ nullable_string = {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ }
+ wrapped, received = _wrap(
+ name,
+ {
+ "type": "object",
+ "title": "ComposedNullDefaultArguments",
+ "properties": {
+ "payload": {
+ combiner: [
+ {
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "enum": ["defaulted"]},
+ "value": {**nullable_string, "default": None},
+ },
+ "required": ["kind"],
+ },
+ {
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "enum": ["plain"]},
+ "value": nullable_string,
+ },
+ "required": ["kind"],
+ },
+ ],
+ },
+ },
+ "required": ["payload"],
+ },
+ )
+
+ _run(name, wrapped, {"payload": {"kind": "plain"}})
+ _run(name, wrapped, {"payload": {"kind": "defaulted"}})
+
+ assert received == [
+ {"payload": {"kind": "plain"}},
+ {"payload": {"kind": "defaulted", "value": None}},
+ ]
+
+
+def test_provider_serialization_preserves_ref_shaped_object_defaults():
+ schema = {
+ "$defs": {
+ "RefTarget": {
+ "type": "object",
+ "properties": {"value": {"type": "string"}},
+ },
+ },
+ "type": "object",
+ "title": "RefShapedDefaultArguments",
+ "properties": {
+ "payload": {
+ "type": "object",
+ "additionalProperties": True,
+ "default": {"$ref": "#/$defs/RefTarget"},
+ },
+ },
+ }
+ model = json_schema_to_model(schema)
+
+ assert model.model_validate({}).model_dump(mode="python", by_alias=True) == {
+ "payload": {"$ref": "#/$defs/RefTarget"}
+ }
+ assert validate_and_serialize_tool_arguments(model, {}) == {
+ "payload": {"$ref": "#/$defs/RefTarget"}
+ }
+
+
@pytest.mark.parametrize("name", PROVIDERS)
def test_provider_serialization_preserves_free_form_objects(name: str):
wrapped, received = _wrap(
diff --git a/python/tests/test_schema_converter.py b/python/tests/test_schema_converter.py
index 167636c51..7944bcb74 100644
--- a/python/tests/test_schema_converter.py
+++ b/python/tests/test_schema_converter.py
@@ -225,6 +225,32 @@ def test_unsatisfiable_declared_property_keeps_root_dynamic_policy(converter):
adapter.validate_python({"impossible": None})
+def test_dynamic_default_materialization_preserves_plain_python_values():
+ model = json_schema_to_model(
+ {
+ "type": "object",
+ "patternProperties": {
+ "^item_": {
+ "type": "object",
+ "properties": {
+ "implicit": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ },
+ "defaulted": {"type": "integer", "default": 1},
+ },
+ },
+ },
+ "additionalProperties": False,
+ }
+ )
+
+ result = model.model_validate({"item_a": {}})
+
+ assert result.model_extra == {"item_a": {"defaulted": 1}}
+ assert isinstance(result.model_extra["item_a"], dict)
+ assert getattr(result, "item_a") == {"defaulted": 1}
+
+
@pytest.mark.parametrize(
"invalid_object_schema,error_type,error_match",
[