The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): resolve ref pointers through arrays and percent escapes
emozilla8f2c147c5718
diff --git a/tests/agent/test_tool_arg_coercion.py b/tests/agent/test_tool_arg_coercion.pyindex 611de0504a3..58afeea3e21 100644--- a/tests/agent/test_tool_arg_coercion.py+++ b/tests/agent/test_tool_arg_coercion.py@@ -286,6 +286,38 @@ class TestCoerceToolArgsNested:result = coerce_tool_args("test_tool", {"count": "5", "verbose": "true"})assert result == {"count": 5, "verbose": True}+ def test_ref_paths_through_arrays_and_percent_escapes_resolve(self):+ schema = {+ "name": "test_tool",+ "description": "test",+ "parameters": {+ "type": "object",+ "$defs": {"My Type": {"type": "integer"}},+ "properties": {+ "limit": {"anyOf": [{"type": "integer"}, {"type": "null"}]},+ # zod-to-json-schema points a reused schema at its first occurrence by path.+ "offset": {"$ref": "#/properties/limit/anyOf/0"},+ "page": {"$ref": "#/$defs/My%20Type"},+ },+ },+ }+ with patch("tools.arg_coercion.registry.get_schema", return_value=schema):+ result = coerce_tool_args("test_tool", {"offset": "7", "page": "3"})+ assert result == {"offset": 7, "page": 3}++ def test_malformed_pointer_escape_is_left_unresolved(self):+ schema = {+ "name": "test_tool",+ "description": "test",+ "parameters": {+ "type": "object",+ "$defs": {"a~2b": {"type": "integer"}},+ "properties": {"count": {"$ref": "#/$defs/a~2b"}},+ },+ }+ with patch("tools.arg_coercion.registry.get_schema", return_value=schema):+ assert coerce_tool_args("test_tool", {"count": "5"}) == {"count": "5"}+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.pyindex 3ff7a36f15c..def301b3d69 100644--- a/tools/arg_coercion.py+++ b/tools/arg_coercion.py@@ -8,7 +8,9 @@ conservative: originals are kept whenever a repair is not unambiguous.import jsonimport logging+import refrom typing import Any, Dict+from urllib.parse import unquotefrom tools.registry import registry@@ -86,24 +88,29 @@ 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."""+ """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 schemaref = schema.get("$ref")- if not isinstance(ref, str):- return schema- if ref == "#":- tokens = []- elif ref.startswith("#/"):- tokens = ref[2:].split("/")- else:+ 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:@@ -111,10 +118,16 @@ def _resolve_local_schema_ref(target: Any = root_schemafor raw_token in tokens:+ if _BAD_POINTER_ESCAPE.search(raw_token):+ return schematoken = raw_token.replace("~1", "/").replace("~0", "~")- if not isinstance(target, dict) or token not in target:+ 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- target = target[token]if not isinstance(target, dict):return schema