Skip to content

The agent that grows with you

fix(tools): resolve local schema refs during arg coercion

Yuchen Wang6512e72ef5e1
diff --git a/tests/agent/test_tool_arg_coercion.py b/tests/agent/test_tool_arg_coercion.py
index ef7a5423ea9..8d43829438a 100644
--- a/tests/agent/test_tool_arg_coercion.py
+++ b/tests/agent/test_tool_arg_coercion.py
@@ -230,6 +230,78 @@ class TestCoerceToolArgsNested:
result = coerce_tool_args("test_tool", args)
assert result["items"] == [{"id": "1", "content": "x"}]
+ def test_object_arg_referenced_via_defs_is_parsed(self):
+ schema = {
+ "name": "test_tool",
+ "description": "test",
+ "parameters": {
+ "type": "object",
+ "$defs": {
+ "Address": {
+ "type": "object",
+ "properties": {
+ "street": {"type": "string"},
+ "zip": {"type": "string"},
+ },
+ },
+ },
+ "properties": {
+ "address": {"$ref": "#/$defs/Address"},
+ },
+ },
+ }
+ with patch("tools.arg_coercion.registry.get_schema", return_value=schema):
+ args = {"address": '{"street": "Alpha Ave", "zip": "A-001"}'}
+ result = coerce_tool_args("test_tool", args)
+ assert result["address"] == {
+ "street": "Alpha Ave",
+ "zip": "A-001",
+ }
+
+ def test_array_item_referenced_via_defs_is_parsed(self):
+ schema = {
+ "name": "test_tool",
+ "description": "test",
+ "parameters": {
+ "type": "object",
+ "$defs": {
+ "Address": {
+ "type": "object",
+ "properties": {"street": {"type": "string"}},
+ },
+ },
+ "properties": {
+ "addresses": {
+ "type": "array",
+ "items": {"$ref": "#/$defs/Address"},
+ },
+ },
+ },
+ }
+ with patch("tools.arg_coercion.registry.get_schema", return_value=schema):
+ args = {"addresses": ['{"street": "Alpha Ave"}']}
+ result = coerce_tool_args("test_tool", args)
+ assert result["addresses"] == [{"street": "Alpha Ave"}]
+
+ def test_external_and_cyclic_refs_are_preserved(self):
+ for ref, definitions in (
+ ("https://example.com/address.json", {}),
+ ("#/$defs/Address", {"Address": {"$ref": "#/$defs/Address"}}),
+ ):
+ schema = {
+ "name": "test_tool",
+ "description": "test",
+ "parameters": {
+ "type": "object",
+ "$defs": definitions,
+ "properties": {"address": {"$ref": ref}},
+ },
+ }
+ with patch("tools.arg_coercion.registry.get_schema", return_value=schema):
+ raw = '{"street": "Alpha Ave"}'
+ result = coerce_tool_args("test_tool", {"address": raw})
+ assert result["address"] == raw
+
def test_string_subfield_with_json_content_preserved(self):
"""A string-typed sub-field whose value looks like JSON must NOT be parsed."""
diff --git a/tools/arg_coercion.py b/tools/arg_coercion.py
index 339f146fbe0..de781c5dc06 100644
--- a/tools/arg_coercion.py
+++ b/tools/arg_coercion.py
@@ -23,7 +23,8 @@ def coerce_tool_args(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
return args
schema = registry.get_schema(tool_name)
- properties = ((schema or {}).get("parameters") or {}).get("properties")
+ parameters = (schema or {}).get("parameters") or {}
+ properties = parameters.get("properties")
if not properties:
return args
@@ -31,7 +32,7 @@ def coerce_tool_args(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
# renamed); map those keys back to the registry's wire names first.
try:
from tools.schema_sanitizer import unrename_tool_args
- args = unrename_tool_args(schema.get("parameters"), args)
+ args = unrename_tool_args(parameters, args)
except Exception: # pragma: no cover — never break dispatch
pass
@@ -39,6 +40,7 @@ def coerce_tool_args(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
prop_schema = properties.get(key)
if not prop_schema:
continue
+ prop_schema = _resolve_local_schema_ref(prop_schema, parameters)
expected = prop_schema.get("type")
is_container = isinstance(value, (list, tuple))
@@ -67,7 +69,9 @@ def coerce_tool_args(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
if not isinstance(value, str):
# Native container: still normalize JSON-encoded elements/sub-fields.
if (expected == "array" and is_container) or (expected == "object" and isinstance(value, dict)):
- args[key] = _normalize_json_strings_for_schema(value, prop_schema)
+ args[key] = _normalize_json_strings_for_schema(
+ value, prop_schema, root_schema=parameters
+ )
continue
if not expected and not _schema_allows_null(prop_schema):
continue
@@ -75,23 +79,79 @@ def coerce_tool_args(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
if coerced is not value:
args[key] = coerced
if isinstance(coerced, (list, tuple, dict)):
- args[key] = _normalize_json_strings_for_schema(coerced, prop_schema)
+ args[key] = _normalize_json_strings_for_schema(
+ coerced, prop_schema, root_schema=parameters
+ )
return args
-def _schema_accepts_kind(schema: Any, kind: str) -> bool:
+def _resolve_local_schema_ref(
+ schema: Any,
+ root_schema: Any,
+ seen_refs: set[str] | None = None,
+) -> Any:
+ """Resolve document-local JSON Pointers for coercion decisions."""
+ if not isinstance(schema, dict) or not isinstance(root_schema, dict):
+ return schema
+
+ ref = schema.get("$ref")
+ if not isinstance(ref, str):
+ return schema
+ if ref == "#":
+ tokens = []
+ elif ref.startswith("#/"):
+ tokens = ref[2:].split("/")
+ else:
+ return schema
+
+ seen = seen_refs or set()
+ if ref in seen:
+ return schema
+
+ target: Any = root_schema
+ for raw_token in tokens:
+ token = raw_token.replace("~1", "/").replace("~0", "~")
+ if not isinstance(target, dict) or token not in target:
+ return schema
+ target = target[token]
+ if not isinstance(target, dict):
+ return schema
+
+ resolved = _resolve_local_schema_ref(target, root_schema, seen | {ref})
+ siblings = {key: value for key, value in schema.items() if key != "$ref"}
+ if not siblings or not isinstance(resolved, dict):
+ return resolved
+
+ combined = dict(resolved)
+ for key, value in siblings.items():
+ combined.setdefault(key, value)
+ return combined
+
+
+def _schema_accepts_kind(
+ schema: Any,
+ kind: str,
+ root_schema: Any = None,
+) -> bool:
"""True when *schema* permits JSON type *kind* via ``type`` or any anyOf/oneOf/allOf branch."""
if not isinstance(schema, dict):
return False
+ if root_schema is None:
+ root_schema = schema
+ schema = _resolve_local_schema_ref(schema, root_schema)
t = schema.get("type")
if t == kind or (isinstance(t, list) and kind in t):
return True
- return any(isinstance(branches := schema.get(union_key), list) and any(_schema_accepts_kind(b, kind) for b in branches)
+ return any(isinstance(branches := schema.get(union_key), list) and any(_schema_accepts_kind(b, kind, root_schema) for b in branches)
for union_key in ("anyOf", "oneOf", "allOf"))
-def _normalize_json_strings_for_schema(value: Any, schema: Any) -> Any:
+def _normalize_json_strings_for_schema(
+ value: Any,
+ schema: Any,
+ root_schema: Any = None,
+) -> Any:
"""Recursively parse JSON-encoded strings where the schema expects array/object.
Schema-guided: a string is only parsed when its schema position expects a
@@ -102,11 +162,14 @@ def _normalize_json_strings_for_schema(value: Any, schema: Any) -> Any:
"""
if not isinstance(schema, dict):
return value
+ if root_schema is None:
+ root_schema = schema
+ schema = _resolve_local_schema_ref(schema, root_schema)
if isinstance(value, str):
trimmed = value.strip()
- expects_array = _schema_accepts_kind(schema, "array")
- expects_object = _schema_accepts_kind(schema, "object")
+ expects_array = _schema_accepts_kind(schema, "array", root_schema)
+ expects_object = _schema_accepts_kind(schema, "object", root_schema)
if not ((expects_array and trimmed.startswith("[")) or (expects_object and trimmed.startswith("{"))):
return value
try:
@@ -121,7 +184,12 @@ def _normalize_json_strings_for_schema(value: Any, schema: Any) -> Any:
items_schema = schema.get("items")
if not isinstance(items_schema, dict):
return value
- out = [_normalize_json_strings_for_schema(item, items_schema) for item in value]
+ out = [
+ _normalize_json_strings_for_schema(
+ item, items_schema, root_schema=root_schema
+ )
+ for item in value
+ ]
return out if any(n is not o for n, o in zip(out, value)) else value
if isinstance(value, dict):
@@ -131,7 +199,9 @@ def _normalize_json_strings_for_schema(value: Any, schema: Any) -> Any:
out = dict(value)
for k, prop_schema in props.items():
if k in value and isinstance(prop_schema, dict):
- out[k] = _normalize_json_strings_for_schema(value[k], prop_schema)
+ out[k] = _normalize_json_strings_for_schema(
+ value[k], prop_schema, root_schema=root_schema
+ )
return out if any(out[k] is not v for k, v in value.items()) else value
return value