11
provider drops a ``null`` the tool's own schema does not accept before
12
executing the tool (see :func:`omit_null_tool_arguments`).
13
14
-Constructs strict mode cannot express — objects that accept arbitrary keys
15
-(schema-valued or ``True`` ``additionalProperties``, ``patternProperties``,
16
-property-less free-form objects), ``allOf``, ``prefixItems``, dangling or
17
-cyclic ``$ref`` pointers and a non-object root — are reported in
14
+Local ``$ref`` pointers into ``$defs``/``definitions`` are kept (the API
15
+supports them, including recursion) and the definitions themselves are
16
+normalized; an optional ``$ref`` property is widened with an ``anyOf`` null
17
+branch. Constructs strict mode cannot express — objects that accept arbitrary
18
+keys (schema-valued or ``True`` ``additionalProperties``, ``patternProperties``,
19
+property-less free-form objects), ``allOf``, ``prefixItems``, external or
20
+dangling ``$ref`` pointers and a non-object root — are reported in
21
``unsupported`` instead of being rewritten into something narrower; the
22
provider sends such a tool without strict mode.
23
21
-The pipeline is ``dereference_json_schema`` (lenient) → strict rewrite →
22
-``required`` de-duplication. The input is never mutated and every rewrite is
23
-recorded (capped at 50 entries; ``total_changes`` carries the real count).
24
+The input is never mutated, every rewrite is recorded (capped at 50 entries;
25
+``total_changes`` carries the real count) and ``required`` arrays are
26
+de-duplicated at the end.
27
"""
28
29
from __future__ import annotations
30
31
import typing as t
32
30
-from composio.utils.json_schema import dereference_json_schema
33
+from composio.utils.json_schema import MAX_REF_CHAIN_DEPTH, _try_resolve_pointer
34
35
MAX_NODE_DEPTH = 512
36
MAX_CHANGES = 50
93
schema: dict[str, t.Any]
94
"""The strict schema; only usable when ``unsupported`` is empty."""
95
source: dict[str, t.Any]
93
- """The dereferenced input optionality was decided against."""
96
+ """The input schema optionality was decided against."""
97
changes: list[StrictSchemaChange]
98
total_changes: int
99
unsupported: list[StrictSchemaIncompatibility]
124
return {**annotations, "anyOf": [rest, {"type": "null"}]}
125
126
124
-def _schema_accepts_null(node: t.Any) -> bool:
125
- """Whether a (dereferenced) schema node accepts ``null`` as an instance."""
127
+def _resolve_local_refs(node: t.Any, root: dict[str, t.Any]) -> t.Any:
128
+ """Follow local ``$ref`` pointers until a concrete node is reached."""
129
+ current = node
130
+ for _ in range(MAX_REF_CHAIN_DEPTH):
131
+ if not isinstance(current, dict) or not isinstance(current.get("$ref"), str):
132
+ return current
133
+ resolution = _try_resolve_pointer(root, current["$ref"])
134
+ if not resolution.ok:
135
+ return current
136
+ current = resolution.value
137
+ return current
138
+
139
+
140
+def _schema_accepts_null(schema: t.Any, root: dict[str, t.Any]) -> bool:
141
+ """Whether a schema node accepts ``null`` as an instance."""
142
+ node = _resolve_local_refs(schema, root)
143
if not isinstance(node, dict):
144
return True
145
node_type = node.get("type")
154
for keyword in ("anyOf", "oneOf"):
155
branches = node.get(keyword)
156
if isinstance(branches, list):
140
- return any(_schema_accepts_null(b) for b in branches)
157
+ return any(_schema_accepts_null(b, root) for b in branches)
158
return True
159
160
179
180
181
class _Walker:
165
- def __init__(self) -> None:
182
+ def __init__(self, root: dict[str, t.Any]) -> None:
183
+ self.root = root
184
self.changes: list[StrictSchemaChange] = []
185
self.total_changes = 0
186
self.unsupported: list[StrictSchemaIncompatibility] = []
256
257
out = self.walk_children(node, mode, depth, path)
258
259
+ ref = node.get("$ref")
260
+ if isinstance(ref, str):
261
+ resolved = ref.startswith("#/") and _try_resolve_pointer(self.root, ref).ok
262
+ if not resolved:
263
+ self.reject(path, "$ref", f'unresolved $ref "{ref}"')
264
+ # The referenced definition is normalized where it is declared.
265
+ return out
266
+
267
node_type = out.get("type")
268
declares_object = node_type == "object" or (
269
isinstance(node_type, list) and "object" in node_type
320
:param schema: The JSON schema to normalize; never mutated.
321
:return: A :class:`StrictJsonSchemaResult`.
322
"""
297
- walker = _Walker()
298
- dereferenced = dereference_json_schema(
299
- schema,
300
- on_unresolved="sentinel",
301
- on_replace=lambda ref, _reason: walker.reject(
302
- "", "$ref", f'unresolved $ref "{ref}"'
303
- ),
304
- )
305
- normalized = _dedupe_required(walker.walk(dereferenced, "schema", 0, ""))
323
+ root: dict[str, t.Any] = schema if isinstance(schema, dict) else {}
324
+ walker = _Walker(root)
325
+ normalized = _dedupe_required(walker.walk(root, "schema", 0, ""))
326
if not isinstance(normalized, dict) or normalized.get("type") != "object":
327
walker.reject("", "type", "root must be a non-nullable object")
328
return StrictJsonSchemaResult(
329
schema=normalized,
310
- source=dereferenced,
330
+ source=root,
331
changes=walker.changes,
332
total_changes=walker.total_changes,
333
unsupported=walker.unsupported,
344
The model then sends ``null`` for a parameter it would otherwise have
345
omitted; forwarding it to the tool would fail validation against the
346
tool's real schema, so it is treated as "omitted". A ``null`` the original
327
- schema accepts is kept. ``schema`` is the dereferenced tool schema
328
- (``StrictJsonSchemaResult.source``). The input is not mutated.
347
+ schema accepts is kept. ``schema`` is the tool schema the strict rewrite
348
+ was computed from (``StrictJsonSchemaResult.source``). The input is not
349
+ mutated.
350
"""
330
- return t.cast(dict[str, t.Any], _omit_nulls(arguments, schema))
351
+ root: dict[str, t.Any] = schema if isinstance(schema, dict) else {}
352
+ return t.cast(dict[str, t.Any], _omit_nulls(arguments, root, root, 0))
353
354
333
-def _omit_nulls(value: t.Any, schema: t.Any) -> t.Any:
334
- node = schema if isinstance(schema, dict) else {}
355
+def _omit_nulls(
356
+ value: t.Any, schema: t.Any, root: dict[str, t.Any], depth: int
357
+) -> t.Any:
358
+ if depth > MAX_NODE_DEPTH:
359
+ raise ValueError(
360
+ f"Tool arguments exceed maximum nesting depth of {MAX_NODE_DEPTH}"
361
+ )
362
+ resolved = _resolve_local_refs(schema, root)
363
+ node = resolved if isinstance(resolved, dict) else {}
364
if isinstance(value, list):
365
items = node.get("items") if isinstance(node.get("items"), dict) else None
337
- return [_omit_nulls(item, items) for item in value]
366
+ return [_omit_nulls(item, items, root, depth + 1) for item in value]
367
if not isinstance(value, dict):
368
return value
369
declared = node.get("properties")
372
for key, child in value.items():
373
property_schema = properties.get(key)
374
if child is None:
346
- if property_schema is None or _schema_accepts_null(property_schema):
375
+ if property_schema is None or _schema_accepts_null(property_schema, root):
376
clone[key] = child
377
continue
349
- clone[key] = _omit_nulls(child, property_schema)
378
+ clone[key] = _omit_nulls(child, property_schema, root, depth + 1)
379
return clone