Skip to content

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

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

jkomynoe6fb9f9d325c
diff --git a/python/composio/utils/strict_schema.py b/python/composio/utils/strict_schema.py
index c8ade6ea5..706c74794 100644
--- a/python/composio/utils/strict_schema.py
+++ b/python/composio/utils/strict_schema.py
@@ -11,23 +11,26 @@ is dropped, so the model keeps every parameter it could pass before; the strict
provider drops a ``null`` the tool's own schema does not accept before
executing the tool (see :func:`omit_null_tool_arguments`).
-Constructs strict mode cannot express — objects that accept arbitrary keys
-(schema-valued or ``True`` ``additionalProperties``, ``patternProperties``,
-property-less free-form objects), ``allOf``, ``prefixItems``, dangling or
-cyclic ``$ref`` pointers and a non-object root — are reported in
+Local ``$ref`` pointers into ``$defs``/``definitions`` are kept (the API
+supports them, including recursion) and the definitions themselves are
+normalized; an optional ``$ref`` property is widened with an ``anyOf`` null
+branch. Constructs strict mode cannot express — objects that accept arbitrary
+keys (schema-valued or ``True`` ``additionalProperties``, ``patternProperties``,
+property-less free-form objects), ``allOf``, ``prefixItems``, external or
+dangling ``$ref`` pointers and a non-object root — are reported in
``unsupported`` instead of being rewritten into something narrower; the
provider sends such a tool without strict mode.
-The pipeline is ``dereference_json_schema`` (lenient) → strict rewrite →
-``required`` de-duplication. The input is never mutated and every rewrite is
-recorded (capped at 50 entries; ``total_changes`` carries the real count).
+The input is never mutated, every rewrite is recorded (capped at 50 entries;
+``total_changes`` carries the real count) and ``required`` arrays are
+de-duplicated at the end.
"""
from __future__ import annotations
import typing as t
-from composio.utils.json_schema import dereference_json_schema
+from composio.utils.json_schema import MAX_REF_CHAIN_DEPTH, _try_resolve_pointer
MAX_NODE_DEPTH = 512
MAX_CHANGES = 50
@@ -90,7 +93,7 @@ class StrictJsonSchemaResult(t.NamedTuple):
schema: dict[str, t.Any]
"""The strict schema; only usable when ``unsupported`` is empty."""
source: dict[str, t.Any]
- """The dereferenced input optionality was decided against."""
+ """The input schema optionality was decided against."""
changes: list[StrictSchemaChange]
total_changes: int
unsupported: list[StrictSchemaIncompatibility]
@@ -121,8 +124,22 @@ def _widen_to_nullable(node: dict[str, t.Any]) -> dict[str, t.Any]:
return {**annotations, "anyOf": [rest, {"type": "null"}]}
-def _schema_accepts_null(node: t.Any) -> bool:
- """Whether a (dereferenced) schema node accepts ``null`` as an instance."""
+def _resolve_local_refs(node: t.Any, root: dict[str, t.Any]) -> t.Any:
+ """Follow local ``$ref`` pointers until a concrete node is reached."""
+ current = node
+ for _ in range(MAX_REF_CHAIN_DEPTH):
+ if not isinstance(current, dict) or not isinstance(current.get("$ref"), str):
+ return current
+ resolution = _try_resolve_pointer(root, current["$ref"])
+ if not resolution.ok:
+ return current
+ current = resolution.value
+ return current
+
+
+def _schema_accepts_null(schema: t.Any, root: dict[str, t.Any]) -> bool:
+ """Whether a schema node accepts ``null`` as an instance."""
+ node = _resolve_local_refs(schema, root)
if not isinstance(node, dict):
return True
node_type = node.get("type")
@@ -137,7 +154,7 @@ def _schema_accepts_null(node: t.Any) -> bool:
for keyword in ("anyOf", "oneOf"):
branches = node.get(keyword)
if isinstance(branches, list):
- return any(_schema_accepts_null(b) for b in branches)
+ return any(_schema_accepts_null(b, root) for b in branches)
return True
@@ -162,7 +179,8 @@ def _dedupe_required(value: t.Any, is_schema: bool = True, depth: int = 0) -> t.
class _Walker:
- def __init__(self) -> None:
+ def __init__(self, root: dict[str, t.Any]) -> None:
+ self.root = root
self.changes: list[StrictSchemaChange] = []
self.total_changes = 0
self.unsupported: list[StrictSchemaIncompatibility] = []
@@ -238,6 +256,14 @@ class _Walker:
out = self.walk_children(node, mode, depth, path)
+ ref = node.get("$ref")
+ if isinstance(ref, str):
+ resolved = ref.startswith("#/") and _try_resolve_pointer(self.root, ref).ok
+ if not resolved:
+ self.reject(path, "$ref", f'unresolved $ref "{ref}"')
+ # The referenced definition is normalized where it is declared.
+ return out
+
node_type = out.get("type")
declares_object = node_type == "object" or (
isinstance(node_type, list) and "object" in node_type
@@ -294,20 +320,14 @@ def to_strict_json_schema(schema: t.Any) -> StrictJsonSchemaResult:
:param schema: The JSON schema to normalize; never mutated.
:return: A :class:`StrictJsonSchemaResult`.
"""
- walker = _Walker()
- dereferenced = dereference_json_schema(
- schema,
- on_unresolved="sentinel",
- on_replace=lambda ref, _reason: walker.reject(
- "", "$ref", f'unresolved $ref "{ref}"'
- ),
- )
- normalized = _dedupe_required(walker.walk(dereferenced, "schema", 0, ""))
+ root: dict[str, t.Any] = schema if isinstance(schema, dict) else {}
+ walker = _Walker(root)
+ normalized = _dedupe_required(walker.walk(root, "schema", 0, ""))
if not isinstance(normalized, dict) or normalized.get("type") != "object":
walker.reject("", "type", "root must be a non-nullable object")
return StrictJsonSchemaResult(
schema=normalized,
- source=dereferenced,
+ source=root,
changes=walker.changes,
total_changes=walker.total_changes,
unsupported=walker.unsupported,
@@ -324,17 +344,26 @@ def omit_null_tool_arguments(
The model then sends ``null`` for a parameter it would otherwise have
omitted; forwarding it to the tool would fail validation against the
tool's real schema, so it is treated as "omitted". A ``null`` the original
- schema accepts is kept. ``schema`` is the dereferenced tool schema
- (``StrictJsonSchemaResult.source``). The input is not mutated.
+ schema accepts is kept. ``schema`` is the tool schema the strict rewrite
+ was computed from (``StrictJsonSchemaResult.source``). The input is not
+ mutated.
"""
- return t.cast(dict[str, t.Any], _omit_nulls(arguments, schema))
+ root: dict[str, t.Any] = schema if isinstance(schema, dict) else {}
+ return t.cast(dict[str, t.Any], _omit_nulls(arguments, root, root, 0))
-def _omit_nulls(value: t.Any, schema: t.Any) -> t.Any:
- node = schema if isinstance(schema, dict) else {}
+def _omit_nulls(
+ value: t.Any, schema: t.Any, root: dict[str, t.Any], depth: int
+) -> t.Any:
+ if depth > MAX_NODE_DEPTH:
+ raise ValueError(
+ f"Tool arguments exceed maximum nesting depth of {MAX_NODE_DEPTH}"
+ )
+ resolved = _resolve_local_refs(schema, root)
+ node = resolved if isinstance(resolved, dict) else {}
if isinstance(value, list):
items = node.get("items") if isinstance(node.get("items"), dict) else None
- return [_omit_nulls(item, items) for item in value]
+ return [_omit_nulls(item, items, root, depth + 1) for item in value]
if not isinstance(value, dict):
return value
declared = node.get("properties")
@@ -343,8 +372,8 @@ def _omit_nulls(value: t.Any, schema: t.Any) -> t.Any:
for key, child in value.items():
property_schema = properties.get(key)
if child is None:
- if property_schema is None or _schema_accepts_null(property_schema):
+ if property_schema is None or _schema_accepts_null(property_schema, root):
clone[key] = child
continue
- clone[key] = _omit_nulls(child, property_schema)
+ clone[key] = _omit_nulls(child, property_schema, root, depth + 1)
return clone
diff --git a/python/tests/test_strict_schema.py b/python/tests/test_strict_schema.py
index a1158f9fd..4dc7dcc3f 100644
--- a/python/tests/test_strict_schema.py
+++ b/python/tests/test_strict_schema.py
@@ -270,15 +270,20 @@ class TestToStrictJsonSchema:
("properties.all", "allOf"),
]
- def test_inlines_refs_dedupes_required_and_reports_dangling_refs(self):
+ def test_keeps_defs_and_refs_and_reports_dangling_refs(self):
result = to_strict_json_schema(
{
"type": "object",
"properties": {
"cfg": {"$ref": "#/$defs/Config"},
+ "optionalCfg": {
+ "$ref": "#/$defs/Config",
+ "description": "optional",
+ },
"missing": {"$ref": "#/$defs/Nope"},
+ "external": {"$ref": "https://example.com/schema.json"},
},
- "required": ["cfg", "cfg", "missing"],
+ "required": ["cfg", "cfg", "missing", "external"],
"$defs": {
"Config": {
"type": "object",
@@ -292,23 +297,33 @@ class TestToStrictJsonSchema:
}
)
- assert "$ref" not in json.dumps(result.schema)
- assert "$defs" not in result.schema
- assert result.schema["properties"]["cfg"] == {
- "type": "object",
- "properties": {
- "url": {"type": "string"},
- "note": {"type": ["string", "null"]},
- },
- "required": ["url", "note"],
- "additionalProperties": False,
+ assert result.schema["properties"]["cfg"] == {"$ref": "#/$defs/Config"}
+ assert result.schema["properties"]["optionalCfg"] == {
+ "description": "optional",
+ "anyOf": [{"$ref": "#/$defs/Config"}, {"type": "null"}],
}
- assert result.schema["required"] == ["cfg", "missing"]
+ assert result.schema["$defs"] == {
+ "Config": {
+ "type": "object",
+ "properties": {
+ "url": {"type": "string"},
+ "note": {"type": ["string", "null"]},
+ },
+ "required": ["url", "note"],
+ "additionalProperties": False,
+ }
+ }
+ assert result.schema["required"] == [
+ "cfg",
+ "optionalCfg",
+ "missing",
+ "external",
+ ]
assert [(e.path, e.keyword) for e in result.unsupported] == [
- ("", "$ref"),
- ("properties.missing", "additionalProperties"),
+ ("properties.missing", "$ref"),
+ ("properties.external", "$ref"),
]
- assert ("properties.cfg.properties.note", "optional-property-nullable") in [
+ assert ("$defs.Config.properties.note", "optional-property-nullable") in [
(c.path, c.reason) for c in result.changes
]
@@ -367,7 +382,7 @@ class TestToStrictJsonSchema:
assert twice.changes == []
assert twice.unsupported == []
- def test_reports_non_object_and_cyclic_roots_as_unsupported(self):
+ def test_reports_non_object_roots_as_unsupported_and_keeps_recursive_defs(self):
assert [
(e.path, e.keyword)
for e in to_strict_json_schema({"type": "string"}).unsupported
@@ -385,14 +400,26 @@ class TestToStrictJsonSchema:
"$defs": {
"Node": {
"type": "object",
- "properties": {"child": {"$ref": "#/$defs/Node"}},
- "required": ["child"],
+ "properties": {
+ "child": {"$ref": "#/$defs/Node"},
+ "label": {"type": "string"},
+ },
+ "required": ["label"],
}
},
}
)
- # The cycle-break sentinel is a free-form object strict mode cannot express.
- assert "additionalProperties" in {e.keyword for e in cyclic.unsupported}
+ # Recursion through $defs is representable in strict mode.
+ assert cyclic.unsupported == []
+ assert cyclic.schema["$defs"]["Node"] == {
+ "type": "object",
+ "properties": {
+ "child": {"anyOf": [{"$ref": "#/$defs/Node"}, {"type": "null"}]},
+ "label": {"type": "string"},
+ },
+ "required": ["child", "label"],
+ "additionalProperties": False,
+ }
def test_raises_past_maximum_depth(self):
deep = {"type": "string"}
@@ -425,7 +452,10 @@ _OMIT_SCHEMA = {
"properties": {"id": {"type": "string"}, "tag": {"type": "string"}},
},
},
+ "refd": {"$ref": "#/$defs/Str"},
+ "refdNullable": {"$ref": "#/$defs/NullableStr"},
},
+ "$defs": {"Str": {"type": "string"}, "NullableStr": {"type": ["string", "null"]}},
}
@@ -438,6 +468,8 @@ class TestOmitNullToolArguments:
"choice": None,
"unknown": None,
"rows": [{"id": "1", "tag": None}, None],
+ "refd": None,
+ "refdNullable": None,
}
snapshot = copy.deepcopy(arguments)
@@ -447,6 +479,7 @@ class TestOmitNullToolArguments:
"choice": None,
"unknown": None,
"rows": [{"id": "1"}, None],
+ "refdNullable": None,
}
assert arguments == snapshot
@@ -487,9 +520,7 @@ class TestOpenAIResponsesProviderStrict:
{
"type": "object",
"properties": {
- "cfg": {
- "$ref": "#/$defs/Config",
- },
+ "cfg": {"$ref": "#/$defs/Config"},
"id": {"type": ["string", "null"]},
"label": {"type": "string"},
},
@@ -509,11 +540,17 @@ class TestOpenAIResponsesProviderStrict:
)
assert wrapped["strict"] is True
- assert "$ref" not in json.dumps(wrapped)
assert wrapped["parameters"] == {
"type": "object",
"properties": {
- "cfg": {
+ "cfg": {"$ref": "#/$defs/Config"},
+ "id": {"type": ["string", "null"]},
+ "label": {"type": ["string", "null"]},
+ },
+ "required": ["cfg", "id", "label"],
+ "additionalProperties": False,
+ "$defs": {
+ "Config": {
"type": "object",
"properties": {
"url": {"type": "string"},
@@ -521,12 +558,8 @@ class TestOpenAIResponsesProviderStrict:
},
"required": ["url", "note"],
"additionalProperties": False,
- },
- "id": {"type": ["string", "null"]},
- "label": {"type": ["string", "null"]},
+ }
},
- "required": ["cfg", "id", "label"],
- "additionalProperties": False,
}
def test_wrap_tool_sends_unsupported_schemas_without_strict(self):
diff --git a/ts/packages/core/src/utils/jsonSchema.ts b/ts/packages/core/src/utils/jsonSchema.ts
index ff093d080..7f40d3fb0 100644
--- a/ts/packages/core/src/utils/jsonSchema.ts
+++ b/ts/packages/core/src/utils/jsonSchema.ts
@@ -545,8 +545,8 @@ export interface StrictJsonSchemaResult {
*/
schema: Record<string, unknown>;
/**
- * The dereferenced input the rewrite was computed from. Optionality is
- * decided against this schema, so it is what `omitNullToolArguments` needs.
+ * The input schema the rewrite was computed from. Optionality is decided
+ * against this schema, so it is what `omitNullToolArguments` needs.
*/
source: Record<string, unknown>;
/** Lossless rewrites, capped at 50 entries; see `totalChanges`. */
@@ -596,8 +596,24 @@ function widenToNullable(node: Record<string, unknown>): Record<string, unknown>
};
}
-/** Whether a (dereferenced) schema node accepts `null` as an instance. */
-function schemaAcceptsNull(node: unknown): boolean {
+/**
+ * Follows local `$ref` pointers from `node` until a concrete schema node is
+ * reached. Unresolvable or over-long chains return the last node seen.
+ */
+function resolveLocalRefs(node: unknown, root: Record<string, unknown>): unknown {
+ let current = node;
+ for (let hops = 0; hops < MAX_REF_CHAIN_DEPTH; hops++) {
+ if (!isPlainObject(current) || typeof current.$ref !== 'string') return current;
+ const resolution = tryResolvePointer(root, current.$ref);
+ if (resolution.kind === 'unresolved') return current;
+ current = resolution.value;
+ }
+ return current;
+}
+
+/** Whether a schema node accepts `null` as an instance. */
+function schemaAcceptsNull(schema: unknown, root: Record<string, unknown>): boolean {
+ const node = resolveLocalRefs(schema, root);
if (!isPlainObject(node)) return true;
if (typeof node.type === 'string') return node.type === 'null';
if (Array.isArray(node.type)) return node.type.includes('null');
@@ -605,7 +621,7 @@ function schemaAcceptsNull(node: unknown): boolean {
if ('const' in node) return node.const === null;
for (const keyword of ['anyOf', 'oneOf']) {
const branches = node[keyword];
- if (Array.isArray(branches)) return branches.some(schemaAcceptsNull);
+ if (Array.isArray(branches)) return branches.some(branch => schemaAcceptsNull(branch, root));
}
return true;
}
@@ -624,17 +640,20 @@ function schemaAcceptsNull(node: unknown): boolean {
* before executing the tool (see {@link omitNullToolArguments});
* - `type` arrays are kept as-is (the API accepts them); `oneOf` becomes
* `anyOf`; `default` and `examples` are stripped;
+ * - local `$ref`s into `$defs`/`definitions` are kept (the API supports
+ * them, including recursion) and the definitions themselves are
+ * normalized; an optional `$ref` property is widened with an `anyOf`
+ * null branch;
* - constructs strict mode cannot express — objects that accept arbitrary
* keys (schema-valued or `true` `additionalProperties`, `patternProperties`,
- * property-less free-form objects), `allOf`, `prefixItems`, dangling or
- * cyclic `$ref`s, and a non-object root — are reported in `unsupported`
+ * property-less free-form objects), `allOf`, `prefixItems`, external or
+ * dangling `$ref`s, and a non-object root — are reported in `unsupported`
* rather than rewritten into something narrower. Callers send such a tool
* without strict mode.
*
- * The pipeline is `dereferenceJsonSchema` (lenient) → strict rewrite →
- * `deduplicateJsonSchemaRequiredArrays`, the same shape the Anthropic
- * provider uses. The input is never mutated. Every rewrite is recorded in
- * `changes` (capped at 50 entries; `totalChanges` carries the real count).
+ * The input is never mutated. Every rewrite is recorded in `changes` (capped
+ * at 50 entries; `totalChanges` carries the real count), and `required`
+ * arrays are de-duplicated at the end.
*/
export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
const changes: StrictSchemaChange[] = [];
@@ -645,15 +664,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
if (changes.length < MAX_STRICT_CHANGES) changes.push(change);
};
- const dereferenced = dereferenceJsonSchema(schema, {
- onUnresolved: 'sentinel',
- onReplace: ref =>
- unsupported.push({
- path: '',
- keyword: '$ref',
- detail: `unresolved $ref "${ref}"`,
- }),
- });
+ const root: Record<string, unknown> = isPlainObject(schema) ? schema : {};
function walkChildren(
node: Record<string, unknown>,
@@ -733,6 +744,21 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
const out = walkChildren(node, mode, depth, path);
+ if (typeof node.$ref === 'string') {
+ const resolution = node.$ref.startsWith('#/')
+ ? tryResolvePointer(root, node.$ref)
+ : ({ kind: 'unresolved', reason: 'malformed-pointer' } as const);
+ if (resolution.kind === 'unresolved') {
+ unsupported.push({
+ path,
+ keyword: '$ref',
+ detail: `unresolved $ref "${node.$ref}"`,
+ });
+ }
+ // The referenced definition is normalized where it is declared.
+ return out;
+ }
+
const declaresObjectType =
out.type === 'object' || (Array.isArray(out.type) && out.type.includes('object'));
if (!declaresObjectType && !isPlainObject(out.properties)) return out;
@@ -784,7 +810,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
};
}
- const normalized = walk(dereferenced, 'schema', 0, '');
+ const normalized = walk(root, 'schema', 0, '');
if (!isPlainObject(normalized) || normalized.type !== 'object') {
unsupported.push({
path: '',
@@ -795,7 +821,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
return {
schema: deduplicateJsonSchemaRequiredArrays(normalized) as Record<string, unknown>,
- source: dereferenced as Record<string, unknown>,
+ source: root,
changes,
totalChanges,
unsupported,
@@ -822,26 +848,40 @@ export function omitNullToolArguments(
args: Record<string, unknown>,
schema: unknown
): Record<string, unknown> {
- return omitNulls(args, schema) as Record<string, unknown>;
+ const root: Record<string, unknown> = isPlainObject(schema) ? schema : {};
+ return omitNulls(args, root, root, 0) as Record<string, unknown>;
}
-function omitNulls(value: unknown, schema: unknown): unknown {
- const node = isPlainObject(schema) ? schema : undefined;
+function omitNulls(
+ value: unknown,
+ schema: unknown,
+ root: Record<string, unknown>,
+ depth: number
+): unknown {
+ if (depth > MAX_NODE_DEPTH) {
+ throw new RangeError(`Tool arguments exceed maximum nesting depth of ${MAX_NODE_DEPTH}`);
+ }
+ const resolved = resolveLocalRefs(schema, root);
+ const node = isPlainObject(resolved) ? resolved : undefined;
if (Array.isArray(value)) {
const items = node && isPlainObject(node.items) ? node.items : undefined;
- return value.map(item => omitNulls(item, items));
+ return value.map(item => omitNulls(item, items, root, depth + 1));
}
if (!isPlainObject(value)) return value;
const properties = node && isPlainObject(node.properties) ? node.properties : {};
const clone: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value)) {
- const propertySchema = properties[key];
+ const propertySchema = Object.prototype.hasOwnProperty.call(properties, key)
+ ? properties[key]
+ : undefined;
if (child === null) {
- if (propertySchema === undefined || schemaAcceptsNull(propertySchema)) clone[key] = child;
+ if (propertySchema === undefined || schemaAcceptsNull(propertySchema, root)) {
+ clone[key] = child;
+ }
continue;
}
- clone[key] = omitNulls(child, propertySchema);
+ clone[key] = omitNulls(child, propertySchema, root, depth + 1);
}
return clone;
}
diff --git a/ts/packages/core/test/utils/jsonSchema.strict.test.ts b/ts/packages/core/test/utils/jsonSchema.strict.test.ts
index 1b6732160..e1cd50e6c 100644
--- a/ts/packages/core/test/utils/jsonSchema.strict.test.ts
+++ b/ts/packages/core/test/utils/jsonSchema.strict.test.ts
@@ -276,14 +276,16 @@ describe('toStrictJsonSchema', () => {
]);
});
- it('inlines $ref/$defs, dedupes required and reports dangling refs', () => {
+ it('keeps $defs and $ref, normalizes the definitions and reports dangling refs', () => {
const { schema, changes, unsupported } = toStrictJsonSchema({
type: 'object',
properties: {
cfg: { $ref: '#/$defs/Config' },
+ optionalCfg: { $ref: '#/$defs/Config', description: 'optional' },
missing: { $ref: '#/$defs/Nope' },
+ external: { $ref: 'https://example.com/schema.json' },
},
- required: ['cfg', 'cfg', 'missing'],
+ required: ['cfg', 'cfg', 'missing', 'external'],
$defs: {
Config: {
type: 'object',
@@ -293,26 +295,31 @@ describe('toStrictJsonSchema', () => {
},
});
- expect(JSON.stringify(schema)).not.toContain('$ref');
- expect(schema.$defs).toBeUndefined();
- expect(propertyOf(schema, 'cfg')).toEqual({
- type: 'object',
- properties: { url: { type: 'string' }, note: { type: ['string', 'null'] } },
- required: ['url', 'note'],
- additionalProperties: false,
+ expect(propertyOf(schema, 'cfg')).toEqual({ $ref: '#/$defs/Config' });
+ expect(propertyOf(schema, 'optionalCfg')).toEqual({
+ description: 'optional',
+ anyOf: [{ $ref: '#/$defs/Config' }, { type: 'null' }],
});
- expect(schema.required).toEqual(['cfg', 'missing']);
+ expect(schema.$defs).toEqual({
+ Config: {
+ type: 'object',
+ properties: { url: { type: 'string' }, note: { type: ['string', 'null'] } },
+ required: ['url', 'note'],
+ additionalProperties: false,
+ },
+ });
+ expect(schema.required).toEqual(['cfg', 'optionalCfg', 'missing', 'external']);
expect(unsupported).toEqual([
- { path: '', keyword: '$ref', detail: 'unresolved $ref "#/$defs/Nope"' },
+ { path: 'properties.missing', keyword: '$ref', detail: 'unresolved $ref "#/$defs/Nope"' },
{
- path: 'properties.missing',
- keyword: 'additionalProperties',
- detail: 'object accepts arbitrary keys',
+ path: 'properties.external',
+ keyword: '$ref',
+ detail: 'unresolved $ref "https://example.com/schema.json"',
},
]);
expect(changes).toContainEqual(
expect.objectContaining({
- path: 'properties.cfg.properties.note',
+ path: '$defs.Config.properties.note',
reason: 'optional-property-nullable',
})
);
@@ -373,7 +380,7 @@ describe('toStrictJsonSchema', () => {
expect(twice.unsupported).toEqual([]);
});
- it('reports non-object and cyclic roots as unsupported', () => {
+ it('reports non-object roots as unsupported and keeps recursive $defs', () => {
expect(toStrictJsonSchema({ type: 'string' }).unsupported).toEqual([
{ path: '', keyword: 'type', detail: 'root must be a non-nullable object' },
]);
@@ -389,15 +396,22 @@ describe('toStrictJsonSchema', () => {
$defs: {
Node: {
type: 'object',
- properties: { child: { $ref: '#/$defs/Node' } },
- required: ['child'],
+ properties: { child: { $ref: '#/$defs/Node' }, label: { type: 'string' } },
+ required: ['label'],
},
},
});
- // The cycle-break sentinel is a free-form object, which strict mode cannot express.
- expect(cyclic.unsupported).toContainEqual(
- expect.objectContaining({ keyword: 'additionalProperties' })
- );
+ // Recursion through $defs is representable in strict mode.
+ expect(cyclic.unsupported).toEqual([]);
+ expect((cyclic.schema.$defs as Record<string, unknown>).Node).toEqual({
+ type: 'object',
+ properties: {
+ child: { anyOf: [{ $ref: '#/$defs/Node' }, { type: 'null' }] },
+ label: { type: 'string' },
+ },
+ required: ['child', 'label'],
+ additionalProperties: false,
+ });
});
it('throws past the maximum nesting depth', () => {
@@ -426,7 +440,10 @@ describe('omitNullToolArguments', () => {
type: 'array',
items: { type: 'object', properties: { id: { type: 'string' }, tag: { type: 'string' } } },
},
+ refd: { $ref: '#/$defs/Str' },
+ refdNullable: { $ref: '#/$defs/NullableStr' },
},
+ $defs: { Str: { type: 'string' }, NullableStr: { type: ['string', 'null'] } },
};
it('drops nulls the schema does not accept and keeps the ones it does', () => {
@@ -437,6 +454,8 @@ describe('omitNullToolArguments', () => {
choice: null,
unknown: null,
rows: [{ id: '1', tag: null }, null],
+ refd: null,
+ refdNullable: null,
};
const snapshot = JSON.parse(JSON.stringify(input));
@@ -446,6 +465,7 @@ describe('omitNullToolArguments', () => {
choice: null,
unknown: null,
rows: [{ id: '1' }, null],
+ refdNullable: null,
});
expect(input).toEqual(snapshot);
});
diff --git a/ts/packages/providers/openai/test/opeanai-responses.test.ts b/ts/packages/providers/openai/test/opeanai-responses.test.ts
index 0a9ee83d8..3950b5c82 100644
--- a/ts/packages/providers/openai/test/opeanai-responses.test.ts
+++ b/ts/packages/providers/openai/test/opeanai-responses.test.ts
@@ -191,7 +191,7 @@ describe('OpenAIResponsesProvider', () => {
});
});
- it('keeps nullable nested objects nullable and inlines $defs under strict mode', () => {
+ it('keeps nullable nested objects nullable and $defs referenced under strict mode', () => {
const strictProvider = new OpenAIResponsesProvider({ strict: true });
const wrapped = strictProvider.wrapTool({
...mockTool,
@@ -211,20 +211,22 @@ describe('OpenAIResponsesProvider', () => {
},
}) as MockedOpenAITool;
- expect(JSON.stringify(wrapped.parameters)).not.toContain('$ref');
expect(wrapped.strict).toBe(true);
expect(wrapped.parameters).toEqual({
type: 'object',
properties: {
- cfg: {
+ cfg: { $ref: '#/$defs/Config' },
+ },
+ required: ['cfg'],
+ additionalProperties: false,
+ $defs: {
+ Config: {
type: ['object', 'null'],
properties: { url: { type: 'string' }, opt: { type: ['string', 'null'] } },
required: ['url', 'opt'],
additionalProperties: false,
},
},
- required: ['cfg'],
- additionalProperties: false,
});
});
diff --git a/ts/packages/providers/vercel/src/index.ts b/ts/packages/providers/vercel/src/index.ts
index 47d9ce9e3..3acf22327 100644
--- a/ts/packages/providers/vercel/src/index.ts
+++ b/ts/packages/providers/vercel/src/index.ts
@@ -17,6 +17,7 @@ import {
McpUrlResponse,
McpServerGetResponse,
deduplicateJsonSchemaRequiredArrays,
+ dereferenceJsonSchema,
toStrictJsonSchema,
jsonSchemaToZodSchema,
logger,
@@ -146,7 +147,11 @@ export class VercelProvider extends BaseAgenticProvider<
}
}
- const inputParametersSchema = jsonSchemaToZodSchema(parameters);
+ // The Zod converter does not follow $ref, so inline the definitions the
+ // strict rewrite keeps (cycles fall back to the permissive sentinel).
+ const inputParametersSchema = jsonSchemaToZodSchema(
+ strictSource ? dereferenceJsonSchema(parameters, { onUnresolved: 'sentinel' }) : parameters
+ );
return tool({
description: composioTool.description,