Skip to content

The agent that grows with you

fix(tools): map sanitized argument keys back through a $ref

emozilla8f817911723e
diff --git a/tests/agent/test_tool_arg_coercion.py b/tests/agent/test_tool_arg_coercion.py
index 58afeea3e21..e88608679c4 100644
--- a/tests/agent/test_tool_arg_coercion.py
+++ b/tests/agent/test_tool_arg_coercion.py
@@ -318,6 +318,21 @@ class TestCoerceToolArgsNested:
with patch("tools.arg_coercion.registry.get_schema", return_value=schema):
assert coerce_tool_args("test_tool", {"count": "5"}) == {"count": "5"}
+ def test_sanitized_keys_behind_a_ref_map_back_to_wire_names(self):
+ # Providers reject keys like "first name"; the sanitizer renames them in $defs too.
+ schema = {
+ "name": "test_tool",
+ "description": "test",
+ "parameters": {
+ "type": "object",
+ "$defs": {"Person": {"type": "object", "properties": {"first name": {"type": "string"}}}},
+ "properties": {"person": {"$ref": "#/$defs/Person"}},
+ },
+ }
+ with patch("tools.arg_coercion.registry.get_schema", return_value=schema):
+ result = coerce_tool_args("test_tool", {"person": {"first_name": "Ada"}})
+ assert result == {"person": {"first name": "Ada"}}
+
def test_array_item_referenced_via_defs_is_parsed(self):
schema = {
"name": "test_tool",
diff --git a/tools/arg_coercion.py b/tools/arg_coercion.py
index def301b3d69..ab0934f43fd 100644
--- a/tools/arg_coercion.py
+++ b/tools/arg_coercion.py
@@ -8,11 +8,10 @@ conservative: originals are kept whenever a repair is not unambiguous.
import json
import logging
-import re
from typing import Any, Dict
-from urllib.parse import unquote
from tools.registry import registry
+from tools.schema_sanitizer import resolve_local_schema_ref
# Logger name kept as "model_tools": these messages were always emitted under
# that name and log-based tooling filters on it.
@@ -42,7 +41,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)
+ prop_schema = resolve_local_schema_ref(prop_schema, parameters)
expected = prop_schema.get("type")
is_container = isinstance(value, (list, tuple))
@@ -88,60 +87,6 @@ def coerce_tool_args(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
return args
-# RFC 6901: an array index is "0" or a number without leading zeros; "~" escapes only "~0" and "~1".
-_POINTER_INDEX = re.compile(r"0|[1-9][0-9]*")
-_BAD_POINTER_ESCAPE = re.compile(r"~(?![01])")
-
-
-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; leave remote,
- malformed or dangling refs as they are."""
- if not isinstance(schema, dict) or not isinstance(root_schema, dict):
- return schema
-
- ref = schema.get("$ref")
- if not isinstance(ref, str) or not ref.startswith("#"):
- return schema
- # A $ref is a URI reference: percent-decode the fragment, then read it as a JSON Pointer.
- pointer = unquote(ref[1:])
- if pointer and not pointer.startswith("/"):
- return schema # a plain-name anchor such as "#Address", not a pointer
- tokens = pointer.split("/")[1:]
-
- seen = seen_refs or set()
- if ref in seen:
- return schema
-
- target: Any = root_schema
- for raw_token in tokens:
- if _BAD_POINTER_ESCAPE.search(raw_token):
- return schema
- token = raw_token.replace("~1", "/").replace("~0", "~")
- if isinstance(target, dict) and token in target:
- target = target[token]
- elif isinstance(target, list) and _POINTER_INDEX.fullmatch(token) and int(token) < len(target):
- # Path refs can pass through arrays, e.g. zod-to-json-schema's "#/properties/a/anyOf/0".
- target = target[int(token)]
- else:
- return schema
- 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,
@@ -157,7 +102,7 @@ def _schema_accepts_kind(
seen_schema_ids = seen_schema_ids | {id(schema)}
if root_schema is None:
root_schema = schema
- schema = _resolve_local_schema_ref(schema, root_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
@@ -182,7 +127,7 @@ def _normalize_json_strings_for_schema(
return value
if root_schema is None:
root_schema = schema
- schema = _resolve_local_schema_ref(schema, root_schema)
+ schema = resolve_local_schema_ref(schema, root_schema)
if isinstance(value, str):
trimmed = value.strip()
diff --git a/tools/schema_sanitizer.py b/tools/schema_sanitizer.py
index 9df3c4ef687..d000fa5ba03 100644
--- a/tools/schema_sanitizer.py
+++ b/tools/schema_sanitizer.py
@@ -11,6 +11,7 @@ import copy
import logging
import re
from typing import Any, Callable
+from urllib.parse import unquote
logger = logging.getLogger(__name__)
@@ -58,9 +59,60 @@ def _rename_property_keys(props: dict, path: str) -> dict[str, str]:
return renames
-def unrename_tool_args(params_schema: Any, args: Any) -> Any:
+# RFC 6901: an array index is "0" or a number without leading zeros; "~" escapes only "~0" and "~1".
+_POINTER_INDEX = re.compile(r"0|[1-9][0-9]*")
+_BAD_POINTER_ESCAPE = re.compile(r"~(?![01])")
+
+
+def resolve_local_schema_ref(schema: Any, root_schema: Any, seen_refs: set[str] | None = None) -> Any:
+ """Follow a document-local ``$ref`` in *schema* against *root_schema*, for dispatch-time
+ decisions (argument coercion, key unrenaming). Remote, malformed or dangling refs come back
+ unchanged; sibling keywords are kept, and the referenced schema wins where they conflict."""
+ if not isinstance(schema, dict) or not isinstance(root_schema, dict):
+ return schema
+
+ ref = schema.get("$ref")
+ if not isinstance(ref, str) or not ref.startswith("#"):
+ return schema
+ # A $ref is a URI reference: percent-decode the fragment, then read it as a JSON Pointer.
+ pointer = unquote(ref[1:])
+ if pointer and not pointer.startswith("/"):
+ return schema # a plain-name anchor such as "#Address", not a pointer
+ seen = seen_refs or set()
+ if ref in seen:
+ return schema
+
+ target: Any = root_schema
+ for raw_token in pointer.split("/")[1:]:
+ if _BAD_POINTER_ESCAPE.search(raw_token):
+ return schema
+ token = raw_token.replace("~1", "/").replace("~0", "~")
+ if isinstance(target, dict) and token in target:
+ target = target[token]
+ elif isinstance(target, list) and _POINTER_INDEX.fullmatch(token) and int(token) < len(target):
+ # Path refs can pass through arrays, e.g. zod-to-json-schema's "#/properties/a/anyOf/0".
+ target = target[int(token)]
+ else:
+ return schema
+ 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 unrename_tool_args(params_schema: Any, args: Any, root_schema: Any = None) -> Any:
"""Map sanitized keys in model-emitted args back to wire names. ``params_schema`` is the
- ORIGINAL registry schema; recurses into objects/array items; unknown keys pass through."""
+ ORIGINAL registry schema; recurses into objects/array items, following local ``$ref``s
+ (the sanitizer renames keys inside ``$defs`` too); unknown keys pass through."""
+ root = params_schema if root_schema is None else root_schema
+ params_schema = resolve_local_schema_ref(params_schema, root)
props = params_schema.get("properties") if isinstance(params_schema, dict) else None
if not isinstance(props, dict) or not isinstance(args, dict):
return args
@@ -68,11 +120,11 @@ def unrename_tool_args(params_schema: Any, args: Any) -> Any:
out = {}
for key, value in args.items():
orig = reverse.get(key, key)
- sub = props.get(orig) if isinstance(props.get(orig), dict) else {}
+ sub = resolve_local_schema_ref(props[orig], root) if isinstance(props.get(orig), dict) else {}
if isinstance(value, dict) and sub:
- value = unrename_tool_args(sub, value)
+ value = unrename_tool_args(sub, value, root)
elif isinstance(value, list) and isinstance(sub.get("items"), dict):
- value = [unrename_tool_args(sub["items"], item) if isinstance(item, dict) else item
+ value = [unrename_tool_args(sub["items"], item, root) if isinstance(item, dict) else item
for item in value]
out[orig] = value
return out