@devries-cameron20 / composio Mirror · read-only / commits / e6fb9f9d3
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 14:45 UTC

feat(core): keep $defs recursion under strict mode

OpenAI structured outputs support local $ref pointers, including recursive definitions, so toStrictJsonSchema no longer inlines them: $defs and definitions are normalized where they are declared, an optional $ref property is widened with an anyOf null branch, and external or dangling $refs are reported as unsupported. omitNullToolArguments follows local $refs when deciding whether a null is accepted. The Vercel provider still inlines definitions before converting to Zod, which does not follow $ref. Co-authored-by: AseemPrasad <aseemprasad0520@gmail.com> Claude-Session: https://claude.ai/code/session_01TDrxCHn2hg51HmxVstSUgs

jkomyno committed Aug 26, 2026 at 17:28 UTC e6fb9f9d325c673a683e471a823e2386b09fb405
6 files changed +248 -119
python/composio/utils/strict_schema.py
+60 -31
@@ -11,23 +11,26 @@ is dropped, so the model keeps every parameter it could pass before; the strict
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
@@ -90,7 +93,7 @@ class StrictJsonSchemaResult(t.NamedTuple):
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]
@@ -121,8 +124,22 @@ def _widen_to_nullable(node: dict[str, t.Any]) -> dict[str, t.Any]:
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")
@@ -137,7 +154,7 @@ def _schema_accepts_null(node: t.Any) -> bool:
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
@@ -162,7 +179,8 @@ def _dedupe_required(value: t.Any, is_schema: bool = True, depth: int = 0) -> t.
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] = []
@@ -238,6 +256,14 @@ class _Walker:
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
@@ -294,20 +320,14 @@ def to_strict_json_schema(schema: t.Any) -> StrictJsonSchemaResult:
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,
@@ -324,17 +344,26 @@ def omit_null_tool_arguments(
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")
@@ -343,8 +372,8 @@ def _omit_nulls(value: t.Any, schema: t.Any) -> t.Any:
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
python/tests/test_strict_schema.py
+64 -31
@@ -270,15 +270,20 @@ class TestToStrictJsonSchema:
270 ("properties.all", "allOf"),
271 ]
272
273 - def test_inlines_refs_dedupes_required_and_reports_dangling_refs(self):
273 + def test_keeps_defs_and_refs_and_reports_dangling_refs(self):
274 result = to_strict_json_schema(
275 {
276 "type": "object",
277 "properties": {
278 "cfg": {"$ref": "#/$defs/Config"},
279 + "optionalCfg": {
280 + "$ref": "#/$defs/Config",
281 + "description": "optional",
282 + },
283 "missing": {"$ref": "#/$defs/Nope"},
284 + "external": {"$ref": "https://example.com/schema.json"},
285 },
281 - "required": ["cfg", "cfg", "missing"],
286 + "required": ["cfg", "cfg", "missing", "external"],
287 "$defs": {
288 "Config": {
289 "type": "object",
@@ -292,23 +297,33 @@ class TestToStrictJsonSchema:
297 }
298 )
299
295 - assert "$ref" not in json.dumps(result.schema)
296 - assert "$defs" not in result.schema
297 - assert result.schema["properties"]["cfg"] == {
298 - "type": "object",
299 - "properties": {
300 - "url": {"type": "string"},
301 - "note": {"type": ["string", "null"]},
302 - },
303 - "required": ["url", "note"],
304 - "additionalProperties": False,
300 + assert result.schema["properties"]["cfg"] == {"$ref": "#/$defs/Config"}
301 + assert result.schema["properties"]["optionalCfg"] == {
302 + "description": "optional",
303 + "anyOf": [{"$ref": "#/$defs/Config"}, {"type": "null"}],
304 }
306 - assert result.schema["required"] == ["cfg", "missing"]
305 + assert result.schema["$defs"] == {
306 + "Config": {
307 + "type": "object",
308 + "properties": {
309 + "url": {"type": "string"},
310 + "note": {"type": ["string", "null"]},
311 + },
312 + "required": ["url", "note"],
313 + "additionalProperties": False,
314 + }
315 + }
316 + assert result.schema["required"] == [
317 + "cfg",
318 + "optionalCfg",
319 + "missing",
320 + "external",
321 + ]
322 assert [(e.path, e.keyword) for e in result.unsupported] == [
308 - ("", "$ref"),
309 - ("properties.missing", "additionalProperties"),
323 + ("properties.missing", "$ref"),
324 + ("properties.external", "$ref"),
325 ]
311 - assert ("properties.cfg.properties.note", "optional-property-nullable") in [
326 + assert ("$defs.Config.properties.note", "optional-property-nullable") in [
327 (c.path, c.reason) for c in result.changes
328 ]
329
@@ -367,7 +382,7 @@ class TestToStrictJsonSchema:
382 assert twice.changes == []
383 assert twice.unsupported == []
384
370 - def test_reports_non_object_and_cyclic_roots_as_unsupported(self):
385 + def test_reports_non_object_roots_as_unsupported_and_keeps_recursive_defs(self):
386 assert [
387 (e.path, e.keyword)
388 for e in to_strict_json_schema({"type": "string"}).unsupported
@@ -385,14 +400,26 @@ class TestToStrictJsonSchema:
400 "$defs": {
401 "Node": {
402 "type": "object",
388 - "properties": {"child": {"$ref": "#/$defs/Node"}},
389 - "required": ["child"],
403 + "properties": {
404 + "child": {"$ref": "#/$defs/Node"},
405 + "label": {"type": "string"},
406 + },
407 + "required": ["label"],
408 }
409 },
410 }
411 )
394 - # The cycle-break sentinel is a free-form object strict mode cannot express.
395 - assert "additionalProperties" in {e.keyword for e in cyclic.unsupported}
412 + # Recursion through $defs is representable in strict mode.
413 + assert cyclic.unsupported == []
414 + assert cyclic.schema["$defs"]["Node"] == {
415 + "type": "object",
416 + "properties": {
417 + "child": {"anyOf": [{"$ref": "#/$defs/Node"}, {"type": "null"}]},
418 + "label": {"type": "string"},
419 + },
420 + "required": ["child", "label"],
421 + "additionalProperties": False,
422 + }
423
424 def test_raises_past_maximum_depth(self):
425 deep = {"type": "string"}
@@ -425,7 +452,10 @@ _OMIT_SCHEMA = {
452 "properties": {"id": {"type": "string"}, "tag": {"type": "string"}},
453 },
454 },
455 + "refd": {"$ref": "#/$defs/Str"},
456 + "refdNullable": {"$ref": "#/$defs/NullableStr"},
457 },
458 + "$defs": {"Str": {"type": "string"}, "NullableStr": {"type": ["string", "null"]}},
459 }
460
461
@@ -438,6 +468,8 @@ class TestOmitNullToolArguments:
468 "choice": None,
469 "unknown": None,
470 "rows": [{"id": "1", "tag": None}, None],
471 + "refd": None,
472 + "refdNullable": None,
473 }
474 snapshot = copy.deepcopy(arguments)
475
@@ -447,6 +479,7 @@ class TestOmitNullToolArguments:
479 "choice": None,
480 "unknown": None,
481 "rows": [{"id": "1"}, None],
482 + "refdNullable": None,
483 }
484 assert arguments == snapshot
485
@@ -487,9 +520,7 @@ class TestOpenAIResponsesProviderStrict:
520 {
521 "type": "object",
522 "properties": {
490 - "cfg": {
491 - "$ref": "#/$defs/Config",
492 - },
523 + "cfg": {"$ref": "#/$defs/Config"},
524 "id": {"type": ["string", "null"]},
525 "label": {"type": "string"},
526 },
@@ -509,11 +540,17 @@ class TestOpenAIResponsesProviderStrict:
540 )
541
542 assert wrapped["strict"] is True
512 - assert "$ref" not in json.dumps(wrapped)
543 assert wrapped["parameters"] == {
544 "type": "object",
545 "properties": {
516 - "cfg": {
546 + "cfg": {"$ref": "#/$defs/Config"},
547 + "id": {"type": ["string", "null"]},
548 + "label": {"type": ["string", "null"]},
549 + },
550 + "required": ["cfg", "id", "label"],
551 + "additionalProperties": False,
552 + "$defs": {
553 + "Config": {
554 "type": "object",
555 "properties": {
556 "url": {"type": "string"},
@@ -521,12 +558,8 @@ class TestOpenAIResponsesProviderStrict:
558 },
559 "required": ["url", "note"],
560 "additionalProperties": False,
524 - },
525 - "id": {"type": ["string", "null"]},
526 - "label": {"type": ["string", "null"]},
561 + }
562 },
528 - "required": ["cfg", "id", "label"],
529 - "additionalProperties": False,
563 }
564
565 def test_wrap_tool_sends_unsupported_schemas_without_strict(self):
ts/packages/core/src/utils/jsonSchema.ts
+69 -29
@@ -545,8 +545,8 @@ export interface StrictJsonSchemaResult {
545 */
546 schema: Record<string, unknown>;
547 /**
548 - * The dereferenced input the rewrite was computed from. Optionality is
549 - * decided against this schema, so it is what `omitNullToolArguments` needs.
548 + * The input schema the rewrite was computed from. Optionality is decided
549 + * against this schema, so it is what `omitNullToolArguments` needs.
550 */
551 source: Record<string, unknown>;
552 /** Lossless rewrites, capped at 50 entries; see `totalChanges`. */
@@ -596,8 +596,24 @@ function widenToNullable(node: Record<string, unknown>): Record<string, unknown>
596 };
597 }
598
599 -/** Whether a (dereferenced) schema node accepts `null` as an instance. */
600 -function schemaAcceptsNull(node: unknown): boolean {
599 +/**
600 + * Follows local `$ref` pointers from `node` until a concrete schema node is
601 + * reached. Unresolvable or over-long chains return the last node seen.
602 + */
603 +function resolveLocalRefs(node: unknown, root: Record<string, unknown>): unknown {
604 + let current = node;
605 + for (let hops = 0; hops < MAX_REF_CHAIN_DEPTH; hops++) {
606 + if (!isPlainObject(current) || typeof current.$ref !== 'string') return current;
607 + const resolution = tryResolvePointer(root, current.$ref);
608 + if (resolution.kind === 'unresolved') return current;
609 + current = resolution.value;
610 + }
611 + return current;
612 +}
613 +
614 +/** Whether a schema node accepts `null` as an instance. */
615 +function schemaAcceptsNull(schema: unknown, root: Record<string, unknown>): boolean {
616 + const node = resolveLocalRefs(schema, root);
617 if (!isPlainObject(node)) return true;
618 if (typeof node.type === 'string') return node.type === 'null';
619 if (Array.isArray(node.type)) return node.type.includes('null');
@@ -605,7 +621,7 @@ function schemaAcceptsNull(node: unknown): boolean {
621 if ('const' in node) return node.const === null;
622 for (const keyword of ['anyOf', 'oneOf']) {
623 const branches = node[keyword];
608 - if (Array.isArray(branches)) return branches.some(schemaAcceptsNull);
624 + if (Array.isArray(branches)) return branches.some(branch => schemaAcceptsNull(branch, root));
625 }
626 return true;
627 }
@@ -624,17 +640,20 @@ function schemaAcceptsNull(node: unknown): boolean {
640 * before executing the tool (see {@link omitNullToolArguments});
641 * - `type` arrays are kept as-is (the API accepts them); `oneOf` becomes
642 * `anyOf`; `default` and `examples` are stripped;
643 + * - local `$ref`s into `$defs`/`definitions` are kept (the API supports
644 + * them, including recursion) and the definitions themselves are
645 + * normalized; an optional `$ref` property is widened with an `anyOf`
646 + * null branch;
647 * - constructs strict mode cannot express — objects that accept arbitrary
648 * keys (schema-valued or `true` `additionalProperties`, `patternProperties`,
629 - * property-less free-form objects), `allOf`, `prefixItems`, dangling or
630 - * cyclic `$ref`s, and a non-object root — are reported in `unsupported`
649 + * property-less free-form objects), `allOf`, `prefixItems`, external or
650 + * dangling `$ref`s, and a non-object root — are reported in `unsupported`
651 * rather than rewritten into something narrower. Callers send such a tool
652 * without strict mode.
653 *
634 - * The pipeline is `dereferenceJsonSchema` (lenient) → strict rewrite →
635 - * `deduplicateJsonSchemaRequiredArrays`, the same shape the Anthropic
636 - * provider uses. The input is never mutated. Every rewrite is recorded in
637 - * `changes` (capped at 50 entries; `totalChanges` carries the real count).
654 + * The input is never mutated. Every rewrite is recorded in `changes` (capped
655 + * at 50 entries; `totalChanges` carries the real count), and `required`
656 + * arrays are de-duplicated at the end.
657 */
658 export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
659 const changes: StrictSchemaChange[] = [];
@@ -645,15 +664,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
664 if (changes.length < MAX_STRICT_CHANGES) changes.push(change);
665 };
666
648 - const dereferenced = dereferenceJsonSchema(schema, {
649 - onUnresolved: 'sentinel',
650 - onReplace: ref =>
651 - unsupported.push({
652 - path: '',
653 - keyword: '$ref',
654 - detail: `unresolved $ref "${ref}"`,
655 - }),
656 - });
667 + const root: Record<string, unknown> = isPlainObject(schema) ? schema : {};
668
669 function walkChildren(
670 node: Record<string, unknown>,
@@ -733,6 +744,21 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
744
745 const out = walkChildren(node, mode, depth, path);
746
747 + if (typeof node.$ref === 'string') {
748 + const resolution = node.$ref.startsWith('#/')
749 + ? tryResolvePointer(root, node.$ref)
750 + : ({ kind: 'unresolved', reason: 'malformed-pointer' } as const);
751 + if (resolution.kind === 'unresolved') {
752 + unsupported.push({
753 + path,
754 + keyword: '$ref',
755 + detail: `unresolved $ref "${node.$ref}"`,
756 + });
757 + }
758 + // The referenced definition is normalized where it is declared.
759 + return out;
760 + }
761 +
762 const declaresObjectType =
763 out.type === 'object' || (Array.isArray(out.type) && out.type.includes('object'));
764 if (!declaresObjectType && !isPlainObject(out.properties)) return out;
@@ -784,7 +810,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
810 };
811 }
812
787 - const normalized = walk(dereferenced, 'schema', 0, '');
813 + const normalized = walk(root, 'schema', 0, '');
814 if (!isPlainObject(normalized) || normalized.type !== 'object') {
815 unsupported.push({
816 path: '',
@@ -795,7 +821,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
821
822 return {
823 schema: deduplicateJsonSchemaRequiredArrays(normalized) as Record<string, unknown>,
798 - source: dereferenced as Record<string, unknown>,
824 + source: root,
825 changes,
826 totalChanges,
827 unsupported,
@@ -822,26 +848,40 @@ export function omitNullToolArguments(
848 args: Record<string, unknown>,
849 schema: unknown
850 ): Record<string, unknown> {
825 - return omitNulls(args, schema) as Record<string, unknown>;
851 + const root: Record<string, unknown> = isPlainObject(schema) ? schema : {};
852 + return omitNulls(args, root, root, 0) as Record<string, unknown>;
853 }
854
828 -function omitNulls(value: unknown, schema: unknown): unknown {
829 - const node = isPlainObject(schema) ? schema : undefined;
855 +function omitNulls(
856 + value: unknown,
857 + schema: unknown,
858 + root: Record<string, unknown>,
859 + depth: number
860 +): unknown {
861 + if (depth > MAX_NODE_DEPTH) {
862 + throw new RangeError(`Tool arguments exceed maximum nesting depth of ${MAX_NODE_DEPTH}`);
863 + }
864 + const resolved = resolveLocalRefs(schema, root);
865 + const node = isPlainObject(resolved) ? resolved : undefined;
866 if (Array.isArray(value)) {
867 const items = node && isPlainObject(node.items) ? node.items : undefined;
832 - return value.map(item => omitNulls(item, items));
868 + return value.map(item => omitNulls(item, items, root, depth + 1));
869 }
870 if (!isPlainObject(value)) return value;
871
872 const properties = node && isPlainObject(node.properties) ? node.properties : {};
873 const clone: Record<string, unknown> = {};
874 for (const [key, child] of Object.entries(value)) {
839 - const propertySchema = properties[key];
875 + const propertySchema = Object.prototype.hasOwnProperty.call(properties, key)
876 + ? properties[key]
877 + : undefined;
878 if (child === null) {
841 - if (propertySchema === undefined || schemaAcceptsNull(propertySchema)) clone[key] = child;
879 + if (propertySchema === undefined || schemaAcceptsNull(propertySchema, root)) {
880 + clone[key] = child;
881 + }
882 continue;
883 }
844 - clone[key] = omitNulls(child, propertySchema);
884 + clone[key] = omitNulls(child, propertySchema, root, depth + 1);
885 }
886 return clone;
887 }
ts/packages/core/test/utils/jsonSchema.strict.test.ts
+42 -22
@@ -276,14 +276,16 @@ describe('toStrictJsonSchema', () => {
276 ]);
277 });
278
279 - it('inlines $ref/$defs, dedupes required and reports dangling refs', () => {
279 + it('keeps $defs and $ref, normalizes the definitions and reports dangling refs', () => {
280 const { schema, changes, unsupported } = toStrictJsonSchema({
281 type: 'object',
282 properties: {
283 cfg: { $ref: '#/$defs/Config' },
284 + optionalCfg: { $ref: '#/$defs/Config', description: 'optional' },
285 missing: { $ref: '#/$defs/Nope' },
286 + external: { $ref: 'https://example.com/schema.json' },
287 },
286 - required: ['cfg', 'cfg', 'missing'],
288 + required: ['cfg', 'cfg', 'missing', 'external'],
289 $defs: {
290 Config: {
291 type: 'object',
@@ -293,26 +295,31 @@ describe('toStrictJsonSchema', () => {
295 },
296 });
297
296 - expect(JSON.stringify(schema)).not.toContain('$ref');
297 - expect(schema.$defs).toBeUndefined();
298 - expect(propertyOf(schema, 'cfg')).toEqual({
299 - type: 'object',
300 - properties: { url: { type: 'string' }, note: { type: ['string', 'null'] } },
301 - required: ['url', 'note'],
302 - additionalProperties: false,
298 + expect(propertyOf(schema, 'cfg')).toEqual({ $ref: '#/$defs/Config' });
299 + expect(propertyOf(schema, 'optionalCfg')).toEqual({
300 + description: 'optional',
301 + anyOf: [{ $ref: '#/$defs/Config' }, { type: 'null' }],
302 });
304 - expect(schema.required).toEqual(['cfg', 'missing']);
303 + expect(schema.$defs).toEqual({
304 + Config: {
305 + type: 'object',
306 + properties: { url: { type: 'string' }, note: { type: ['string', 'null'] } },
307 + required: ['url', 'note'],
308 + additionalProperties: false,
309 + },
310 + });
311 + expect(schema.required).toEqual(['cfg', 'optionalCfg', 'missing', 'external']);
312 expect(unsupported).toEqual([
306 - { path: '', keyword: '$ref', detail: 'unresolved $ref "#/$defs/Nope"' },
313 + { path: 'properties.missing', keyword: '$ref', detail: 'unresolved $ref "#/$defs/Nope"' },
314 {
308 - path: 'properties.missing',
309 - keyword: 'additionalProperties',
310 - detail: 'object accepts arbitrary keys',
315 + path: 'properties.external',
316 + keyword: '$ref',
317 + detail: 'unresolved $ref "https://example.com/schema.json"',
318 },
319 ]);
320 expect(changes).toContainEqual(
321 expect.objectContaining({
315 - path: 'properties.cfg.properties.note',
322 + path: '$defs.Config.properties.note',
323 reason: 'optional-property-nullable',
324 })
325 );
@@ -373,7 +380,7 @@ describe('toStrictJsonSchema', () => {
380 expect(twice.unsupported).toEqual([]);
381 });
382
376 - it('reports non-object and cyclic roots as unsupported', () => {
383 + it('reports non-object roots as unsupported and keeps recursive $defs', () => {
384 expect(toStrictJsonSchema({ type: 'string' }).unsupported).toEqual([
385 { path: '', keyword: 'type', detail: 'root must be a non-nullable object' },
386 ]);
@@ -389,15 +396,22 @@ describe('toStrictJsonSchema', () => {
396 $defs: {
397 Node: {
398 type: 'object',
392 - properties: { child: { $ref: '#/$defs/Node' } },
393 - required: ['child'],
399 + properties: { child: { $ref: '#/$defs/Node' }, label: { type: 'string' } },
400 + required: ['label'],
401 },
402 },
403 });
397 - // The cycle-break sentinel is a free-form object, which strict mode cannot express.
398 - expect(cyclic.unsupported).toContainEqual(
399 - expect.objectContaining({ keyword: 'additionalProperties' })
400 - );
404 + // Recursion through $defs is representable in strict mode.
405 + expect(cyclic.unsupported).toEqual([]);
406 + expect((cyclic.schema.$defs as Record<string, unknown>).Node).toEqual({
407 + type: 'object',
408 + properties: {
409 + child: { anyOf: [{ $ref: '#/$defs/Node' }, { type: 'null' }] },
410 + label: { type: 'string' },
411 + },
412 + required: ['child', 'label'],
413 + additionalProperties: false,
414 + });
415 });
416
417 it('throws past the maximum nesting depth', () => {
@@ -426,7 +440,10 @@ describe('omitNullToolArguments', () => {
440 type: 'array',
441 items: { type: 'object', properties: { id: { type: 'string' }, tag: { type: 'string' } } },
442 },
443 + refd: { $ref: '#/$defs/Str' },
444 + refdNullable: { $ref: '#/$defs/NullableStr' },
445 },
446 + $defs: { Str: { type: 'string' }, NullableStr: { type: ['string', 'null'] } },
447 };
448
449 it('drops nulls the schema does not accept and keeps the ones it does', () => {
@@ -437,6 +454,8 @@ describe('omitNullToolArguments', () => {
454 choice: null,
455 unknown: null,
456 rows: [{ id: '1', tag: null }, null],
457 + refd: null,
458 + refdNullable: null,
459 };
460 const snapshot = JSON.parse(JSON.stringify(input));
461
@@ -446,6 +465,7 @@ describe('omitNullToolArguments', () => {
465 choice: null,
466 unknown: null,
467 rows: [{ id: '1' }, null],
468 + refdNullable: null,
469 });
470 expect(input).toEqual(snapshot);
471 });
ts/packages/providers/openai/test/opeanai-responses.test.ts
+7 -5
@@ -191,7 +191,7 @@ describe('OpenAIResponsesProvider', () => {
191 });
192 });
193
194 - it('keeps nullable nested objects nullable and inlines $defs under strict mode', () => {
194 + it('keeps nullable nested objects nullable and $defs referenced under strict mode', () => {
195 const strictProvider = new OpenAIResponsesProvider({ strict: true });
196 const wrapped = strictProvider.wrapTool({
197 ...mockTool,
@@ -211,20 +211,22 @@ describe('OpenAIResponsesProvider', () => {
211 },
212 }) as MockedOpenAITool;
213
214 - expect(JSON.stringify(wrapped.parameters)).not.toContain('$ref');
214 expect(wrapped.strict).toBe(true);
215 expect(wrapped.parameters).toEqual({
216 type: 'object',
217 properties: {
219 - cfg: {
218 + cfg: { $ref: '#/$defs/Config' },
219 + },
220 + required: ['cfg'],
221 + additionalProperties: false,
222 + $defs: {
223 + Config: {
224 type: ['object', 'null'],
225 properties: { url: { type: 'string' }, opt: { type: ['string', 'null'] } },
226 required: ['url', 'opt'],
227 additionalProperties: false,
228 },
229 },
226 - required: ['cfg'],
227 - additionalProperties: false,
230 });
231 });
232
ts/packages/providers/vercel/src/index.ts
+6 -1
@@ -17,6 +17,7 @@ import {
17 McpUrlResponse,
18 McpServerGetResponse,
19 deduplicateJsonSchemaRequiredArrays,
20 + dereferenceJsonSchema,
21 toStrictJsonSchema,
22 jsonSchemaToZodSchema,
23 logger,
@@ -146,7 +147,11 @@ export class VercelProvider extends BaseAgenticProvider<
147 }
148 }
149
149 - const inputParametersSchema = jsonSchemaToZodSchema(parameters);
150 + // The Zod converter does not follow $ref, so inline the definitions the
151 + // strict rewrite keeps (cycles fall back to the permissive sentinel).
152 + const inputParametersSchema = jsonSchemaToZodSchema(
153 + strictSource ? dereferenceJsonSchema(parameters, { onUnresolved: 'sentinel' }) : parameters
154 + );
155
156 return tool({
157 description: composioTool.description,