@devries-cameron20 / composio Mirror · read-only / commits / 04817cb20
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

fix(openai): recursive strict-mode schema normalization for structured outputs (+ Python parity)

AseemPrasad committed Aug 23, 2026 at 00:17 UTC 04817cb20dd3190b0c001657c7f9ba315fa2fadf
11 files changed +1247 -32
.changeset/strict-schema-normalization.md new
+7
@@ -0,0 +1,7 @@
1 +---
2 +'@composio/core': patch
3 +'@composio/openai': patch
4 +'@composio/vercel': patch
5 +---
6 +
7 +Fix strict-mode tool schemas for OpenAI structured outputs. Strict normalization now recurses into nested objects, nullable types (`type: ['string', 'null']`) and `anyOf`/`allOf`/`oneOf` branches, inlines `$defs`/`$ref`, and marks every object with `additionalProperties: false` plus a complete `required` array — so tools with complex parameters no longer produce schemas the API rejects with a 400. The new `toStrictJsonSchema()` core util returns a change log instead of failing silently; `removeNonRequiredProperties` behavior is unchanged for non-strict callers. The Python `OpenAIResponsesProvider` gains a matching opt-in `strict=True` constructor flag.
python/composio/core/provider/_openai_responses.py
+32 -7
@@ -11,11 +11,13 @@ from openai.types.responses.response_output_item import ResponseFunctionToolCall
11
12 from composio.core.provider import NonAgenticProvider
13 from composio.types import Modifiers, Tool, ToolExecutionResponse
14 +from composio.utils.json_schema import dereference_json_schema
15 from composio.utils.shared import normalize_tool_arguments
16 +from composio.utils.strict_schema import to_strict_json_schema
17
18 # Responses API uses a flattened tool structure
17 -ResponsesTool = t.Dict[str, t.Any]
18 -ResponsesToolCollection = t.List[ResponsesTool]
19 +ResponsesTool = dict[str, t.Any]
20 +ResponsesToolCollection = list[ResponsesTool]
21
22
23 class OpenAIResponsesProvider(
@@ -23,13 +25,36 @@ class OpenAIResponsesProvider(
25 ):
26 """OpenAI Responses API Provider class definition."""
27
28 + def __init__(self, strict: bool = False) -> None:
29 + """
30 + :param strict: Normalize wrapped tool parameter schemas for OpenAI
31 + structured outputs (every object fully required and closed,
32 + nullable types via ``anyOf``, ``$ref``/``$defs`` inlined).
33 + Mirrors the TypeScript ``OpenAIResponsesProvider({ strict })``
34 + option. Defaults to ``False``.
35 + """
36 + self.strict = strict
37 +
38 def wrap_tool(self, tool: Tool) -> ResponsesTool:
39 """Wrap a tool for the Responses API format."""
40 + parameters: t.Any = tool.input_parameters or {}
41 + if (
42 + self.strict
43 + and isinstance(parameters, dict)
44 + and parameters.get("type") == "object"
45 + ):
46 + # Structured outputs reject schemas whose nested objects keep
47 + # optional properties or their own additionalProperties, so the
48 + # strict contract must be applied at every depth. Inline $refs
49 + # first; lenient mode keeps upstream schemas with dangling refs
50 + # usable.
51 + dereferenced = dereference_json_schema(parameters, on_unresolved="sentinel")
52 + parameters = to_strict_json_schema(dereferenced).schema
53 return {
54 "type": "function",
55 "name": tool.slug,
56 "description": tool.description,
32 - "parameters": tool.input_parameters,
57 + "parameters": parameters,
58 }
59
60 def wrap_tools(self, tools: t.Sequence[Tool]) -> ResponsesToolCollection:
@@ -39,8 +64,8 @@ class OpenAIResponsesProvider(
64 def execute_tool_call(
65 self,
66 user_id: str,
42 - tool_call: t.Union[ResponseFunctionToolCall],
43 - modifiers: t.Optional[Modifiers] = None,
67 + tool_call: ResponseFunctionToolCall,
68 + modifiers: Modifiers | None = None,
69 ) -> ToolExecutionResponse:
70 """Execute a tool call from the Responses API.
71
@@ -65,8 +90,8 @@ class OpenAIResponsesProvider(
90 self,
91 user_id: str,
92 response: Response,
68 - modifiers: t.Optional[Modifiers] = None,
69 - ) -> t.List[ToolExecutionResponse]:
93 + modifiers: Modifiers | None = None,
94 + ) -> list[ToolExecutionResponse]:
95 """
96 Handle tool calls from OpenAI Responses API.
97
python/composio/utils/strict_schema.py new
+231
@@ -0,0 +1,231 @@
1 +"""Normalize JSON Schemas for OpenAI structured outputs (``strict`` mode).
2 +
3 +Python counterpart of the TypeScript SDK's ``toStrictJsonSchema``
4 +(``ts/packages/core/src/utils/jsonSchema.ts``). OpenAI's structured-output
5 +contract requires *every* object node — not just the root — to list all of its
6 +properties in ``required``, set ``additionalProperties: False``, avoid
7 +annotation-only keywords, and express nullable / multi-typed fields via
8 +``anyOf``. Tool parameter schemas that nest objects or use ``type`` arrays are
9 +otherwise rejected by the API with a 400.
10 +
11 +Every structural change is recorded so callers can surface diagnostics instead
12 +of failing silently. The input is never mutated. Dereference ``$ref`` pointers
13 +first (see :func:`composio.utils.json_schema.dereference_json_schema`) so
14 +definitions under ``$defs`` are normalized too.
15 +"""
16 +
17 +from __future__ import annotations
18 +
19 +import typing as t
20 +
21 +MAX_NODE_DEPTH = 512
22 +MAX_CHANGES = 50
23 +
24 +# Annotation-only keywords OpenAI structured outputs rejects; safe to strip.
25 +STRICT_STRIP_KEYWORDS = frozenset({"examples", "default"})
26 +
27 +# Keywords whose values are literal data, not schemas - never recursed as schemas.
28 +STRICT_INSTANCE_VALUE_KEYWORDS = frozenset({"const", "enum"})
29 +
30 +STRICT_SCHEMA_SINGLE_KEYS = frozenset(
31 + {
32 + "additionalItems",
33 + "additionalProperties",
34 + "contains",
35 + "contentSchema",
36 + "else",
37 + "if",
38 + "not",
39 + "propertyNames",
40 + "then",
41 + "unevaluatedItems",
42 + "unevaluatedProperties",
43 + }
44 +)
45 +STRICT_SCHEMA_ARRAY_KEYS = frozenset({"allOf", "anyOf", "oneOf", "prefixItems"})
46 +STRICT_SCHEMA_MAP_KEYS = frozenset(
47 + {"$defs", "definitions", "dependentSchemas", "patternProperties", "properties"}
48 +)
49 +
50 +
51 +class StrictSchemaChange(t.NamedTuple):
52 + """A single structural change applied by :func:`to_strict_json_schema`."""
53 +
54 + path: str
55 + reason: str
56 + detail: str = ""
57 +
58 +
59 +class StrictJsonSchemaResult(t.NamedTuple):
60 + """Normalized schema plus a change log."""
61 +
62 + schema: t.Any
63 + changes: list[StrictSchemaChange]
64 +
65 +
66 +def _join_path(parent: str, key: str) -> str:
67 + return f"{parent}.{key}" if parent else key
68 +
69 +
70 +def _split_type_array(
71 + node: dict[str, t.Any], path: str, changes: list[StrictSchemaChange]
72 +) -> dict[str, t.Any]:
73 + type_values = node["type"]
74 + branches = [
75 + {"type": "null"} if value == "null" else {**node, "type": value}
76 + for value in type_values
77 + ]
78 + rest = {key: value for key, value in node.items() if key != "type"}
79 + reason = (
80 + "nullable-type-converted" if "null" in type_values else "multi-type-converted"
81 + )
82 + if len(changes) < MAX_CHANGES:
83 + changes.append(
84 + StrictSchemaChange(
85 + path=path,
86 + reason=reason,
87 + detail=f"type [{', '.join(str(value) for value in type_values)}] converted to anyOf",
88 + )
89 + )
90 + return {**rest, "anyOf": branches}
91 +
92 +
93 +def _walk(
94 + value: t.Any,
95 + mode: str,
96 + depth: int,
97 + path: str,
98 + changes: list[StrictSchemaChange],
99 +) -> t.Any:
100 + if depth > MAX_NODE_DEPTH:
101 + raise ValueError(
102 + f"JSON Schema exceeds maximum nesting depth of {MAX_NODE_DEPTH}"
103 + )
104 +
105 + if isinstance(value, list):
106 + item_mode = "schema" if mode == "schema-array" else "value"
107 + return [
108 + _walk(item, item_mode, depth + 1, f"{path}[{index}]", changes)
109 + for index, item in enumerate(value)
110 + ]
111 +
112 + if not isinstance(value, dict) or mode == "value":
113 + return value
114 +
115 + node: dict[str, t.Any] = value
116 +
117 + # Nullable / multi-type arrays must become anyOf before anything else so
118 + # the generated branches flow through the normal recursion below.
119 + if isinstance(node.get("type"), list):
120 + node = _split_type_array(node, path, changes)
121 +
122 + stripped: dict[str, t.Any] = {}
123 + for key, child in node.items():
124 + if key in STRICT_STRIP_KEYWORDS:
125 + if len(changes) < MAX_CHANGES:
126 + changes.append(
127 + StrictSchemaChange(
128 + path=path,
129 + reason="annotation-keyword-stripped",
130 + detail=f'keyword "{key}" removed',
131 + )
132 + )
133 + continue
134 + stripped[key] = child
135 + node = stripped
136 +
137 + has_properties_keyword = isinstance(node.get("properties"), dict)
138 + if not (has_properties_keyword or node.get("type") == "object"):
139 + return _walk_children(node, mode, depth, path, changes)
140 +
141 + properties = node["properties"] if has_properties_keyword else {}
142 + declared_required = [
143 + entry for entry in node.get("required", []) if isinstance(entry, str)
144 + ]
145 + keep_only_required = len(declared_required) > 0
146 + kept = set(declared_required if keep_only_required else properties.keys())
147 +
148 + next_properties: dict[str, t.Any] = {}
149 + for name, property_schema in properties.items():
150 + child_path = _join_path(path, f"properties.{name}")
151 + if name in kept:
152 + next_properties[name] = _walk(
153 + property_schema, "schema", depth + 1, child_path, changes
154 + )
155 + elif len(changes) < MAX_CHANGES:
156 + changes.append(
157 + StrictSchemaChange(
158 + path=child_path,
159 + reason="non-required-property-dropped",
160 + detail=f'property "{name}" is not listed in "required"',
161 + )
162 + )
163 +
164 + managed = ("type", "properties", "required", "additionalProperties")
165 + rest = {key: child for key, child in node.items() if key not in managed}
166 +
167 + return {
168 + **_walk_children(rest, "schema", depth, path, changes),
169 + "type": "object",
170 + "properties": next_properties,
171 + "required": list(next_properties.keys()),
172 + "additionalProperties": False,
173 + }
174 +
175 +
176 +def _walk_children(
177 + node: dict[str, t.Any],
178 + mode: str,
179 + depth: int,
180 + path: str,
181 + changes: list[StrictSchemaChange],
182 +) -> dict[str, t.Any]:
183 + clone: dict[str, t.Any] = {}
184 + for key, child in node.items():
185 + child_mode = "value"
186 + if mode == "schema-map":
187 + child_mode = "schema"
188 + elif mode == "schema" and key not in STRICT_INSTANCE_VALUE_KEYWORDS:
189 + if key in STRICT_SCHEMA_MAP_KEYS:
190 + child_mode = "schema-map"
191 + elif key in STRICT_SCHEMA_ARRAY_KEYS or (
192 + key == "items" and isinstance(child, list)
193 + ):
194 + child_mode = "schema-array"
195 + elif key in STRICT_SCHEMA_SINGLE_KEYS or key == "items":
196 + child_mode = "schema"
197 +
198 + if child_mode == "schema-map" and isinstance(child, dict):
199 + map_clone: dict[str, t.Any] = {}
200 + for name, sub_schema in child.items():
201 + map_clone[name] = _walk(
202 + sub_schema,
203 + "schema",
204 + depth + 1,
205 + _join_path(_join_path(path, key), name),
206 + changes,
207 + )
208 + clone[key] = map_clone
209 + continue
210 + clone[key] = _walk(child, child_mode, depth + 1, _join_path(path, key), changes)
211 + return clone
212 +
213 +
214 +def to_strict_json_schema(schema: t.Any) -> StrictJsonSchemaResult:
215 + """Normalize a JSON Schema for OpenAI structured outputs.
216 +
217 + Applies the strict contract at every depth:
218 +
219 + - Objects with a non-empty ``required`` keep only those properties;
220 + objects without one keep every property but require them all.
221 + - ``type`` arrays become ``anyOf`` branches with an explicit null variant.
222 + - Annotation keywords (``examples``, ``default``) are stripped.
223 + - Composition keywords, array items and property maps normalize recursively.
224 +
225 + :param schema: The JSON schema to normalize; never mutated.
226 + :return: A :class:`StrictJsonSchemaResult` with the normalized schema and
227 + a change log capped at 50 entries.
228 + """
229 + changes: list[StrictSchemaChange] = []
230 + normalized = _walk(schema, "schema", 0, "", changes)
231 + return StrictJsonSchemaResult(schema=normalized, changes=changes)
python/tests/test_strict_schema.py new
+284
@@ -0,0 +1,284 @@
1 +"""Tests for composio.utils.strict_schema and its use by OpenAIResponsesProvider."""
2 +
3 +import pytest
4 +
5 +from composio.utils.strict_schema import to_strict_json_schema
6 +
7 +
8 +class TestToStrictJsonSchema:
9 + def test_keeps_flat_all_required_object_valid(self):
10 + schema = {
11 + "type": "object",
12 + "properties": {"query": {"type": "string"}},
13 + "required": ["query"],
14 + "additionalProperties": False,
15 + }
16 +
17 + result = to_strict_json_schema(schema)
18 +
19 + assert result.schema == schema
20 + assert result.changes == []
21 +
22 + def test_drops_nested_non_required_properties_and_closes_every_object(self):
23 + result = to_strict_json_schema(
24 + {
25 + "type": "object",
26 + "properties": {
27 + "cfg": {
28 + "type": "object",
29 + "properties": {
30 + "url": {"type": "string"},
31 + "note": {"type": "string"},
32 + },
33 + "required": ["url"],
34 + }
35 + },
36 + "required": ["cfg"],
37 + }
38 + )
39 +
40 + assert result.schema == {
41 + "type": "object",
42 + "properties": {
43 + "cfg": {
44 + "type": "object",
45 + "properties": {"url": {"type": "string"}},
46 + "required": ["url"],
47 + "additionalProperties": False,
48 + }
49 + },
50 + "required": ["cfg"],
51 + "additionalProperties": False,
52 + }
53 + dropped = [
54 + change
55 + for change in result.changes
56 + if change.reason == "non-required-property-dropped"
57 + ]
58 + assert len(dropped) == 1
59 + assert "note" in dropped[0].detail
60 +
61 + def test_requires_every_property_when_required_is_missing(self):
62 + result = to_strict_json_schema(
63 + {
64 + "type": "object",
65 + "properties": {"a": {"type": "string"}, "b": {"type": "number"}},
66 + }
67 + )
68 +
69 + assert result.schema["required"] == ["a", "b"]
70 + assert result.schema["additionalProperties"] is False
71 +
72 + def test_converts_nullable_type_arrays_into_any_of(self):
73 + result = to_strict_json_schema(
74 + {
75 + "type": "object",
76 + "properties": {
77 + "id": {"type": ["string", "null"], "description": "identifier"}
78 + },
79 + "required": ["id"],
80 + }
81 + )
82 +
83 + assert result.schema["properties"]["id"] == {
84 + "anyOf": [
85 + {"type": "string", "description": "identifier"},
86 + {"type": "null"},
87 + ],
88 + "description": "identifier",
89 + }
90 + reasons = {change.reason for change in result.changes}
91 + assert "nullable-type-converted" in reasons
92 +
93 + def test_normalizes_composition_branches_recursively(self):
94 + result = to_strict_json_schema(
95 + {
96 + "type": "object",
97 + "properties": {
98 + "payload": {
99 + "anyOf": [
100 + {
101 + "type": "object",
102 + "properties": {
103 + "inner": {"type": "string"},
104 + "extra": {"type": "string"},
105 + },
106 + "required": ["inner"],
107 + },
108 + {"type": "null"},
109 + ]
110 + }
111 + },
112 + "required": ["payload"],
113 + }
114 + )
115 +
116 + branch = result.schema["properties"]["payload"]["anyOf"][0]
117 + assert branch == {
118 + "type": "object",
119 + "properties": {"inner": {"type": "string"}},
120 + "required": ["inner"],
121 + "additionalProperties": False,
122 + }
123 +
124 + def test_normalizes_array_items(self):
125 + result = to_strict_json_schema(
126 + {
127 + "type": "object",
128 + "properties": {
129 + "rows": {
130 + "type": "array",
131 + "items": {
132 + "type": "object",
133 + "properties": {
134 + "id": {"type": "string"},
135 + "tag": {"type": "string"},
136 + },
137 + "required": ["id"],
138 + },
139 + }
140 + },
141 + "required": ["rows"],
142 + }
143 + )
144 +
145 + assert result.schema["properties"]["rows"]["items"] == {
146 + "type": "object",
147 + "properties": {"id": {"type": "string"}},
148 + "required": ["id"],
149 + "additionalProperties": False,
150 + }
151 +
152 + def test_strips_annotation_keywords_and_reports_them(self):
153 + result = to_strict_json_schema(
154 + {
155 + "type": "object",
156 + "properties": {
157 + "name": {"type": "string", "examples": ["a"], "default": "x"}
158 + },
159 + "required": ["name"],
160 + }
161 + )
162 +
163 + assert result.schema["properties"]["name"] == {"type": "string"}
164 + stripped = [
165 + change
166 + for change in result.changes
167 + if change.reason == "annotation-keyword-stripped"
168 + ]
169 + assert len(stripped) == 2
170 +
171 + def test_does_not_mutate_input(self):
172 + schema = {
173 + "type": "object",
174 + "properties": {
175 + "cfg": {"type": "object", "properties": {"opt": {"type": "string"}}}
176 + },
177 + "required": ["cfg"],
178 + }
179 + import copy
180 +
181 + snapshot = copy.deepcopy(schema)
182 +
183 + to_strict_json_schema(schema)
184 +
185 + assert schema == snapshot
186 +
187 + def test_raises_past_maximum_depth(self):
188 + deep = {"type": "string"}
189 + for _ in range(600):
190 + deep = {
191 + "type": "object",
192 + "properties": {"nest": deep},
193 + "required": ["nest"],
194 + }
195 +
196 + with pytest.raises(ValueError, match="maximum nesting depth"):
197 + to_strict_json_schema(deep)
198 +
199 +
200 +class TestOpenAIResponsesProviderStrict:
201 + def _tool(self, input_parameters):
202 + from tests.test_provider import create_mock_tool
203 +
204 + tool = create_mock_tool("TEST_TOOL", "composio")
205 + tool.input_parameters = input_parameters
206 + return tool
207 +
208 + def test_wrap_tool_passes_parameters_through_by_default(self):
209 + from composio.core.provider._openai_responses import OpenAIResponsesProvider
210 +
211 + provider = OpenAIResponsesProvider()
212 + wrapped = provider.wrap_tool(self._tool({"type": "object", "properties": {}}))
213 +
214 + assert wrapped["parameters"] == {"type": "object", "properties": {}}
215 +
216 + def test_wrap_tool_normalizes_complex_schemas_in_strict_mode(self):
217 + from composio.core.provider._openai_responses import OpenAIResponsesProvider
218 +
219 + provider = OpenAIResponsesProvider(strict=True)
220 + wrapped = provider.wrap_tool(
221 + self._tool(
222 + {
223 + "type": "object",
224 + "properties": {
225 + "cfg": {
226 + "type": "object",
227 + "properties": {
228 + "url": {"type": "string"},
229 + "note": {"type": "string"},
230 + },
231 + "required": ["url"],
232 + },
233 + "id": {"type": ["string", "null"]},
234 + },
235 + "required": ["cfg", "id"],
236 + }
237 + )
238 + )
239 +
240 + import json
241 +
242 + assert "$ref" not in json.dumps(wrapped)
243 + assert wrapped["parameters"] == {
244 + "type": "object",
245 + "properties": {
246 + "cfg": {
247 + "type": "object",
248 + "properties": {"url": {"type": "string"}},
249 + "required": ["url"],
250 + "additionalProperties": False,
251 + },
252 + "id": {"anyOf": [{"type": "string"}, {"type": "null"}]},
253 + },
254 + "required": ["cfg", "id"],
255 + "additionalProperties": False,
256 + }
257 +
258 + def test_wrap_tool_inlines_defs_in_strict_mode(self):
259 + from composio.core.provider._openai_responses import OpenAIResponsesProvider
260 +
261 + provider = OpenAIResponsesProvider(strict=True)
262 + wrapped = provider.wrap_tool(
263 + self._tool(
264 + {
265 + "type": "object",
266 + "properties": {"cfg": {"$ref": "#/$defs/Config"}},
267 + "required": ["cfg"],
268 + "$defs": {
269 + "Config": {
270 + "type": "object",
271 + "properties": {"url": {"type": "string"}},
272 + "required": ["url"],
273 + }
274 + },
275 + }
276 + )
277 + )
278 +
279 + assert wrapped["parameters"]["properties"]["cfg"] == {
280 + "type": "object",
281 + "properties": {"url": {"type": "string"}},
282 + "required": ["url"],
283 + "additionalProperties": False,
284 + }
ts/packages/core/src/index.ts
+4
@@ -10,11 +10,15 @@ export {
10 ensureObjectTypeOnProperties,
11 jsonSchemaToZodSchema,
12 removeNonRequiredProperties,
13 + toStrictJsonSchema,
14 } from './utils/jsonSchema';
15 export type {
16 DereferenceJsonSchemaOptions,
17 UnresolvedRefReason,
18 UnresolvedRefStrategy,
19 + StrictSchemaChange,
20 + StrictSchemaChangeReason,
21 + StrictJsonSchemaResult,
22 } from './utils/jsonSchema';
23 export { getExtensionFromMimeType } from './utils/mime';
24 export { normalizeToolArguments } from './utils/toolArguments';
ts/packages/core/src/utils/jsonSchema.ts
+243
@@ -496,3 +496,246 @@ export function jsonSchemaToZodSchema<T extends z.ZodTypeAny>(
496 });
497 }
498 }
499 +
500 +/**
501 + * Reason recorded when strict normalization changes a schema node.
502 + *
503 + * - `nullable-type-converted` — a `type` array containing `'null'` became an
504 + * `anyOf` with an explicit `{ type: 'null' }` branch.
505 + * - `multi-type-converted` — a `type` array without `'null'` (e.g.
506 + * `['string', 'number']`) became equivalent `anyOf` branches.
507 + * - `annotation-keyword-stripped` — an annotation-only keyword (`examples`,
508 + * `default`) that strict mode rejects was removed.
509 + * - `non-required-property-dropped` — a property not listed in `required`
510 + * was removed from its parent object.
511 + */
512 +export type StrictSchemaChangeReason =
513 + | 'nullable-type-converted'
514 + | 'multi-type-converted'
515 + | 'annotation-keyword-stripped'
516 + | 'non-required-property-dropped';
517 +
518 +/** A single structural change applied by {@link toStrictJsonSchema}. */
519 +export interface StrictSchemaChange {
520 + /** Path to the changed node relative to the root, e.g. `properties.cfg.items`. */
521 + path: string;
522 + reason: StrictSchemaChangeReason;
523 + /** Human-readable detail about what specifically changed. */
524 + detail?: string;
525 +}
526 +
527 +/** Result of {@link toStrictJsonSchema}: the normalized schema plus a change log. */
528 +export interface StrictJsonSchemaResult<T = unknown> {
529 + schema: T;
530 + changes: StrictSchemaChange[];
531 +}
532 +
533 +const MAX_STRICT_CHANGES = 50;
534 +
535 +/** Annotation-only keywords OpenAI structured outputs rejects; safe to strip. */
536 +const STRICT_STRIP_KEYWORDS = new Set(['examples', 'default']);
537 +
538 +/** Keywords whose values are literal data, not schemas — never recursed as schemas. */
539 +const STRICT_INSTANCE_VALUE_KEYWORDS = new Set(['const', 'enum']);
540 +
541 +const STRICT_SCHEMA_SINGLE_KEYS = new Set([
542 + 'additionalItems',
543 + 'additionalProperties',
544 + 'contains',
545 + 'contentSchema',
546 + 'else',
547 + 'if',
548 + 'not',
549 + 'propertyNames',
550 + 'then',
551 + 'unevaluatedItems',
552 + 'unevaluatedProperties',
553 +]);
554 +const STRICT_SCHEMA_ARRAY_KEYS = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems']);
555 +const STRICT_SCHEMA_MAP_KEYS = new Set([
556 + '$defs',
557 + 'definitions',
558 + 'dependentSchemas',
559 + 'patternProperties',
560 + 'properties',
561 +]);
562 +
563 +type StrictWalkMode = 'schema' | 'schema-array' | 'schema-map' | 'value';
564 +
565 +/**
566 + * Normalizes a JSON Schema for OpenAI structured outputs (`strict: true`),
567 + * which requires every object node to declare all of its properties in
568 + * `required`, set `additionalProperties: false`, use only supported keywords,
569 + * and express nullable / multi-typed fields via `anyOf`.
570 + *
571 + * The top-level `removeNonRequiredProperties` only handled the root object,
572 + * so nested objects, composition branches and array items passed through
573 + * untouched and the API rejected the whole request. This function applies the
574 + * same contract at every depth:
575 + *
576 + * - Objects with a non-empty `required` keep only those properties
577 + * (matching the established top-level behavior); objects without one keep
578 + * every property but are forced to require them all — dropping everything
579 + * would gut the tool, and leaving optional properties would be rejected.
580 + * - `type` arrays become `anyOf` branches with an explicit `{type:'null'}`
581 + * variant where applicable.
582 + * - Annotation keywords (`examples`, `default`) are stripped.
583 + * - Composition keywords (`anyOf`/`oneOf`/`allOf`), array `items`/
584 + * `prefixItems` and property maps are normalized recursively.
585 + *
586 + * Every structural change is recorded so callers can surface diagnostics
587 + * instead of failing silently. The input is never mutated. Dereference
588 + * `$ref`s first (see {@link dereferenceJsonSchema}) so definitions referenced
589 + * under `$defs` are normalized too, then run
590 + * {@link deduplicateJsonSchemaRequiredArrays} on the result before emitting.
591 + */
592 +export function toStrictJsonSchema<T = unknown>(schema: T): StrictJsonSchemaResult<T> {
593 + const changes: StrictSchemaChange[] = [];
594 + const recordChange = (change: StrictSchemaChange): void => {
595 + if (changes.length < MAX_STRICT_CHANGES) {
596 + changes.push(change);
597 + }
598 + };
599 +
600 + const joinPath = (parent: string, key: string): string =>
601 + parent ? `${parent}.${key}` : key;
602 +
603 + const splitTypeArray = (node: Record<string, unknown>, path: string): Record<string, unknown> => {
604 + const typeValues = node.type as unknown[];
605 + const branches = typeValues.map(typeValue =>
606 + typeValue === 'null' ? { type: 'null' } : { ...node, type: typeValue }
607 + );
608 + const { type: _droppedType, ...rest } = node;
609 + recordChange({
610 + path,
611 + reason: typeValues.includes('null') ? 'nullable-type-converted' : 'multi-type-converted',
612 + detail: `type [${typeValues.map(String).join(', ')}] converted to anyOf`,
613 + });
614 + return { ...rest, anyOf: branches };
615 + };
616 +
617 + function walkChildren(
618 + node: Record<string, unknown>,
619 + mode: StrictWalkMode,
620 + depth: number,
621 + path: string
622 + ): Record<string, unknown> {
623 + const clone: Record<string, unknown> = {};
624 + for (const [key, child] of Object.entries(node)) {
625 + let childMode: StrictWalkMode = 'value';
626 + if (mode === 'schema-map') {
627 + childMode = 'schema';
628 + } else if (mode === 'schema') {
629 + if (!STRICT_INSTANCE_VALUE_KEYWORDS.has(key)) {
630 + if (STRICT_SCHEMA_MAP_KEYS.has(key)) {
631 + childMode = 'schema-map';
632 + } else if (STRICT_SCHEMA_ARRAY_KEYS.has(key) || (key === 'items' && Array.isArray(child))) {
633 + childMode = 'schema-array';
634 + } else if (STRICT_SCHEMA_SINGLE_KEYS.has(key) || key === 'items') {
635 + childMode = 'schema';
636 + }
637 + }
638 + }
639 +
640 + if (childMode === 'schema-map' && isPlainObject(child)) {
641 + const mapClone: Record<string, unknown> = {};
642 + for (const [name, subSchema] of Object.entries(child)) {
643 + mapClone[name] = walk(subSchema, 'schema', depth + 1, joinPath(joinPath(path, key), name));
644 + }
645 + clone[key] = mapClone;
646 + continue;
647 + }
648 + clone[key] = walk(child, childMode, depth + 1, joinPath(path, key));
649 + }
650 + return clone;
651 + }
652 +
653 + function walk(value: unknown, mode: StrictWalkMode, depth: number, path: string): unknown {
654 + if (depth > MAX_NODE_DEPTH) {
655 + throw new RangeError(`JSON Schema exceeds maximum nesting depth of ${MAX_NODE_DEPTH}`);
656 + }
657 + if (Array.isArray(value)) {
658 + const itemMode = mode === 'schema-array' ? 'schema' : 'value';
659 + return value.map((item, index) => walk(item, itemMode, depth + 1, `${path}[${index}]`));
660 + }
661 + if (!isPlainObject(value)) return value;
662 + if (mode === 'value') return value;
663 +
664 + let node: Record<string, unknown> = value;
665 +
666 + // Nullable / multi-type arrays must become anyOf before anything else so
667 + // the generated branches flow through the normal recursion below.
668 + if (Array.isArray(node.type)) {
669 + node = splitTypeArray(node, path);
670 + }
671 +
672 + const strippedNode: Record<string, unknown> = {};
673 + for (const [key, child] of Object.entries(node)) {
674 + if (STRICT_STRIP_KEYWORDS.has(key)) {
675 + recordChange({
676 + path,
677 + reason: 'annotation-keyword-stripped',
678 + detail: `keyword "${key}" removed`,
679 + });
680 + continue;
681 + }
682 + strippedNode[key] = child;
683 + }
684 + node = strippedNode;
685 +
686 + // Object strictening: complete required, closed additionalProperties.
687 + const hasPropertiesKeyword = isPlainObject(node.properties);
688 + const isObjectNode = hasPropertiesKeyword || node.type === 'object';
689 + if (isObjectNode) {
690 + const properties = hasPropertiesKeyword
691 + ? (node.properties as Record<string, unknown>)
692 + : {};
693 + const declaredRequired = Array.isArray(node.required)
694 + ? node.required.filter((entry): entry is string => typeof entry === 'string')
695 + : [];
696 + const keepOnlyRequired = declaredRequired.length > 0;
697 + const keptKeys = new Set(
698 + keepOnlyRequired ? declaredRequired.filter(key => key in properties) : Object.keys(properties)
699 + );
700 +
701 + const nextProperties: Record<string, unknown> = {};
702 + for (const [name, propertySchema] of Object.entries(properties)) {
703 + if (keptKeys.has(name)) {
704 + nextProperties[name] = walk(
705 + propertySchema,
706 + 'schema',
707 + depth + 1,
708 + joinPath(path, `properties.${name}`)
709 + );
710 + } else {
711 + recordChange({
712 + path: joinPath(path, `properties.${name}`),
713 + reason: 'non-required-property-dropped',
714 + detail: `property "${name}" is not listed in "required"`,
715 + });
716 + }
717 + }
718 +
719 + // Recurse into any remaining schema-bearing siblings (e.g. `allOf`,
720 + // `description`) while keeping the four managed keywords authoritative.
721 + const managedKeys = new Set(['type', 'properties', 'required', 'additionalProperties']);
722 + const restNode: Record<string, unknown> = {};
723 + for (const [key, child] of Object.entries(node)) {
724 + if (!managedKeys.has(key)) restNode[key] = child;
725 + }
726 +
727 + return {
728 + ...walkChildren(restNode, 'schema', depth, path),
729 + type: 'object',
730 + properties: nextProperties,
731 + required: Object.keys(nextProperties),
732 + additionalProperties: false,
733 + };
734 + }
735 +
736 + return walkChildren(node, mode, depth, path);
737 + }
738 +
739 + const normalized = walk(schema, 'schema', 0, '');
740 + return { schema: normalized as T, changes };
741 +}
ts/packages/core/test/utils/jsonSchema.strict.test.ts new
+262
@@ -0,0 +1,262 @@
1 +import { describe, it, expect } from 'vitest';
2 +import {
3 + deduplicateJsonSchemaRequiredArrays,
4 + dereferenceJsonSchema,
5 + toStrictJsonSchema,
6 +} from '../../src/utils/jsonSchema';
7 +
8 +const propertyOf = (schema: unknown, name: string): Record<string, unknown> =>
9 + ((schema as Record<string, unknown>).properties as Record<string, string>)[
10 + name
11 + ] as unknown as Record<string, unknown>;
12 +
13 +describe('toStrictJsonSchema', () => {
14 + it('keeps an already-flat all-required object valid', () => {
15 + const input = {
16 + type: 'object',
17 + properties: { query: { type: 'string' } },
18 + required: ['query'],
19 + additionalProperties: false,
20 + };
21 +
22 + const { schema, changes } = toStrictJsonSchema(input);
23 +
24 + expect(schema).toEqual(input);
25 + expect(changes).toEqual([]);
26 + });
27 +
28 + it('drops nested non-required properties and closes every object', () => {
29 + const { schema } = toStrictJsonSchema({
30 + type: 'object',
31 + properties: {
32 + cfg: {
33 + type: 'object',
34 + properties: {
35 + url: { type: 'string' },
36 + note: { type: 'string' },
37 + },
38 + required: ['url'],
39 + },
40 + },
41 + required: ['cfg'],
42 + });
43 +
44 + expect(schema).toEqual({
45 + type: 'object',
46 + properties: {
47 + cfg: {
48 + type: 'object',
49 + properties: {
50 + url: { type: 'string' },
51 + },
52 + required: ['url'],
53 + additionalProperties: false,
54 + },
55 + },
56 + required: ['cfg'],
57 + additionalProperties: false,
58 + });
59 + });
60 +
61 + it('requires every property when the object has no required array', () => {
62 + const { schema } = toStrictJsonSchema({
63 + type: 'object',
64 + properties: {
65 + a: { type: 'string' },
66 + b: { type: 'number' },
67 + },
68 + });
69 +
70 + expect(schema).toEqual({
71 + type: 'object',
72 + properties: {
73 + a: { type: 'string' },
74 + b: { type: 'number' },
75 + },
76 + required: ['a', 'b'],
77 + additionalProperties: false,
78 + });
79 + });
80 +
81 + it('converts nullable type arrays into anyOf with an explicit null branch', () => {
82 + const { schema } = toStrictJsonSchema({
83 + type: 'object',
84 + properties: {
85 + id: { type: ['string', 'null'], description: 'identifier' },
86 + },
87 + required: ['id'],
88 + });
89 +
90 + expect(schema).toEqual({
91 + type: 'object',
92 + properties: {
93 + id: {
94 + anyOf: [{ type: 'string', description: 'identifier' }, { type: 'null' }],
95 + description: 'identifier',
96 + },
97 + },
98 + required: ['id'],
99 + additionalProperties: false,
100 + });
101 + });
102 +
103 + it('converts multi-type arrays into anyOf branches', () => {
104 + const { schema } = toStrictJsonSchema({
105 + type: 'object',
106 + properties: {
107 + value: { type: ['string', 'number'] },
108 + },
109 + required: ['value'],
110 + });
111 +
112 + const property = propertyOf(schema, 'value');
113 + expect(property.anyOf).toEqual([{ type: 'string' }, { type: 'number' }]);
114 + });
115 +
116 + it('normalizes composition branches recursively', () => {
117 + const { schema } = toStrictJsonSchema({
118 + type: 'object',
119 + properties: {
120 + payload: {
121 + anyOf: [
122 + {
123 + type: 'object',
124 + properties: { inner: { type: 'string' }, extra: { type: 'string' } },
125 + required: ['inner'],
126 + },
127 + { type: 'null' },
128 + ],
129 + },
130 + },
131 + required: ['payload'],
132 + });
133 +
134 + const payload = propertyOf(schema, 'payload');
135 + expect(payload.anyOf[0]).toEqual({
136 + type: 'object',
137 + properties: { inner: { type: 'string' } },
138 + required: ['inner'],
139 + additionalProperties: false,
140 + });
141 + });
142 +
143 + it('normalizes array item schemas including tuples', () => {
144 + const { schema } = toStrictJsonSchema({
145 + type: 'object',
146 + properties: {
147 + rows: {
148 + type: 'array',
149 + items: {
150 + type: 'object',
151 + properties: { id: { type: 'string' }, tag: { type: 'string' } },
152 + required: ['id'],
153 + },
154 + },
155 + pair: {
156 + type: 'array',
157 + prefixItems: [
158 + { type: 'object', properties: { x: { type: 'number' }, y: { type: 'number' } } },
159 + ],
160 + },
161 + },
162 + required: ['rows', 'pair'],
163 + });
164 +
165 + const props = (schema as Record<string, unknown>).properties as Record<
166 + string,
167 + Record<string, unknown>
168 + >;
169 + expect(props.rows.items).toEqual({
170 + type: 'object',
171 + properties: { id: { type: 'string' } },
172 + required: ['id'],
173 + additionalProperties: false,
174 + });
175 + expect(props.pair.prefixItems[0]).toEqual({
176 + type: 'object',
177 + properties: { x: { type: 'number' }, y: { type: 'number' } },
178 + required: ['x', 'y'],
179 + additionalProperties: false,
180 + });
181 + });
182 +
183 + it('strips annotation keywords and reports them', () => {
184 + const { schema, changes } = toStrictJsonSchema({
185 + type: 'object',
186 + properties: { name: { type: 'string', examples: ['a'], default: 'x' } },
187 + required: ['name'],
188 + });
189 +
190 + expect(propertyOf(schema, 'name')).toEqual({ type: 'string' });
191 + expect(changes.filter(change => change.reason === 'annotation-keyword-stripped')).toHaveLength(
192 + 2
193 + );
194 + });
195 +
196 + it('reports dropped properties as changes without exceeding the cap', () => {
197 + const properties: Record<string, unknown> = {};
198 + for (let i = 0; i < 60; i++) properties[`p${i}`] = { type: 'string' };
199 +
200 + const { schema, changes } = toStrictJsonSchema({
201 + type: 'object',
202 + properties,
203 + required: ['p0'],
204 + });
205 +
206 + expect(Object.keys((schema as Record<string, unknown>).properties as object)).toEqual(['p0']);
207 + expect(changes.length).toBeLessThanOrEqual(50);
208 + });
209 +
210 + it('does not mutate the input schema', () => {
211 + const input = {
212 + type: 'object',
213 + properties: {
214 + cfg: {
215 + type: 'object',
216 + properties: { opt: { type: 'string' } },
217 + },
218 + },
219 + required: ['cfg'],
220 + };
221 + const snapshot = JSON.parse(JSON.stringify(input));
222 +
223 + toStrictJsonSchema(input);
224 +
225 + expect(input).toEqual(snapshot);
226 + });
227 +
228 + it('is idempotent for composed pipelines', () => {
229 + const pipeline = (input: unknown): unknown =>
230 + deduplicateJsonSchemaRequiredArrays(
231 + toStrictJsonSchema(dereferenceJsonSchema(input, { onUnresolved: 'sentinel' })).schema
232 + );
233 +
234 + const once = pipeline({
235 + type: 'object',
236 + properties: {
237 + cfg: {
238 + $ref: '#/$defs/Config',
239 + },
240 + },
241 + required: ['cfg'],
242 + $defs: {
243 + Config: {
244 + type: 'object',
245 + properties: { url: { type: 'string' }, note: { type: 'string' } },
246 + required: ['url'],
247 + },
248 + },
249 + });
250 +
251 + expect(pipeline(once)).toEqual(once);
252 + });
253 +
254 + it('throws past the maximum nesting depth', () => {
255 + let deep: Record<string, unknown> = { type: 'string' };
256 + for (let i = 0; i < 600; i++) {
257 + deep = { type: 'object', properties: { nest: deep }, required: ['nest'] };
258 + }
259 +
260 + expect(() => toStrictJsonSchema(deep)).toThrow(RangeError);
261 + });
262 +});
ts/packages/providers/openai/src/OpenAIResponsesProvider.ts
+24 -13
@@ -16,10 +16,12 @@ import {
16 ToolExecuteParams,
17 ExecuteToolModifiers,
18 ExecuteToolFnOptions,
19 - removeNonRequiredProperties,
19 McpUrlResponse,
20 normalizeToolArguments,
21 deduplicateJsonSchemaRequiredArrays,
22 + dereferenceJsonSchema,
23 + toStrictJsonSchema,
24 + logger,
25 } from '@composio/core';
26
27 export type OpenAiTool = OpenAI.Responses.FunctionTool;
@@ -120,23 +122,32 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
122 * ```
123 */
124 override wrapTool(tool: Tool): OpenAiTool {
123 - const inputParams = deduplicateJsonSchemaRequiredArrays(tool.inputParameters);
125 + const inputParams = tool.inputParameters;
126
125 - const parameters =
126 - this.strict && inputParams?.type === 'object'
127 - ? removeNonRequiredProperties(
128 - inputParams as {
129 - type: 'object';
130 - properties: Record<string, unknown>;
131 - required?: string[];
132 - }
133 - )
134 - : (inputParams ?? {});
127 + let parameters: Record<string, unknown> = (inputParams ?? {}) as Record<string, unknown>;
128 + if (this.strict && inputParams?.type === 'object') {
129 + // Structured outputs reject schemas whose nested objects keep optional
130 + // properties or their own additionalProperties, so the strict contract
131 + // must be applied at every depth. Inline $ref/$defs first (lenient mode
132 + // keeps upstream schemas with dangling refs usable), then normalize.
133 + const dereferenced = dereferenceJsonSchema(parameters, {
134 + onUnresolved: 'sentinel',
135 + onReplace: ref =>
136 + logger.debug(
137 + `OpenAIResponsesProvider: unresolved $ref "${ref}" in tool "${tool.slug}" replaced with a permissive schema`
138 + ),
139 + });
140 + parameters = toStrictJsonSchema<Record<string, unknown>>(dereferenced).schema;
141 + }
142 +
143 + // Canonicalize required arrays at the vendor-schema emission boundary,
144 + // after any provider-specific schema transformations.
145 + const wrappedParameters = deduplicateJsonSchemaRequiredArrays(parameters);
146
147 return {
148 name: tool.slug,
149 description: tool.description,
139 - parameters,
150 + parameters: wrappedParameters,
151 strict: this.strict,
152 type: 'function',
153 };
ts/packages/providers/openai/test/opeanai-responses.test.ts
+104
@@ -129,6 +129,110 @@ describe('OpenAIResponsesProvider', () => {
129
130 expect(wrapped.parameters.required).toEqual(['input']);
131 });
132 +
133 + it('normalizes nested objects, nullable types and anyOf under strict mode', () => {
134 + const strictProvider = new OpenAIResponsesProvider({ strict: true });
135 + const wrapped = strictProvider.wrapTool({
136 + ...mockTool,
137 + inputParameters: {
138 + type: 'object',
139 + properties: {
140 + cfg: {
141 + type: 'object',
142 + properties: {
143 + url: { type: 'string' },
144 + note: { type: 'string' },
145 + },
146 + required: ['url'],
147 + },
148 + id: { type: ['string', 'null'] },
149 + payload: {
150 + anyOf: [
151 + {
152 + type: 'object',
153 + properties: { inner: { type: 'string' }, extra: { type: 'string' } },
154 + required: ['inner'],
155 + },
156 + { type: 'null' },
157 + ],
158 + },
159 + },
160 + required: ['cfg', 'id', 'payload'],
161 + },
162 + }) as MockedOpenAITool;
163 +
164 + expect(wrapped.parameters).toEqual({
165 + type: 'object',
166 + properties: {
167 + cfg: {
168 + type: 'object',
169 + properties: { url: { type: 'string' } },
170 + required: ['url'],
171 + additionalProperties: false,
172 + },
173 + id: { anyOf: [{ type: 'string' }, { type: 'null' }] },
174 + payload: {
175 + anyOf: [
176 + {
177 + type: 'object',
178 + properties: { inner: { type: 'string' } },
179 + required: ['inner'],
180 + additionalProperties: false,
181 + },
182 + { type: 'null' },
183 + ],
184 + },
185 + },
186 + required: ['cfg', 'id', 'payload'],
187 + additionalProperties: false,
188 + });
189 + });
190 +
191 + it('dereferences $defs before normalizing under strict mode', () => {
192 + const strictProvider = new OpenAIResponsesProvider({ strict: true });
193 + const wrapped = strictProvider.wrapTool({
194 + ...mockTool,
195 + inputParameters: {
196 + type: 'object',
197 + properties: {
198 + cfg: { $ref: '#/$defs/Config' },
199 + },
200 + required: ['cfg'],
201 + $defs: {
202 + Config: {
203 + type: 'object',
204 + properties: { url: { type: 'string' }, opt: { type: 'string' } },
205 + required: ['url'],
206 + },
207 + },
208 + },
209 + }) as MockedOpenAITool;
210 +
211 + expect(JSON.stringify(wrapped.parameters)).not.toContain('$ref');
212 + expect(wrapped.parameters).toEqual({
213 + type: 'object',
214 + properties: {
215 + cfg: {
216 + type: 'object',
217 + properties: { url: { type: 'string' } },
218 + required: ['url'],
219 + additionalProperties: false,
220 + },
221 + },
222 + required: ['cfg'],
223 + additionalProperties: false,
224 + });
225 + });
226 +
227 + it('leaves non-object schemas untouched in strict mode apart from required dedup', () => {
228 + const strictProvider = new OpenAIResponsesProvider({ strict: true });
229 + const wrapped = strictProvider.wrapTool({
230 + ...mockTool,
231 + inputParameters: undefined,
232 + }) as MockedOpenAITool;
233 +
234 + expect(wrapped.parameters).toEqual({});
235 + });
236 });
237
238 describe('wrapTools', () => {
ts/packages/providers/vercel/src/index.ts
+24 -12
@@ -16,8 +16,11 @@ import {
16 ExecuteToolFn,
17 McpUrlResponse,
18 McpServerGetResponse,
19 - removeNonRequiredProperties,
19 + deduplicateJsonSchemaRequiredArrays,
20 + dereferenceJsonSchema,
21 + toStrictJsonSchema,
22 jsonSchemaToZodSchema,
23 + logger,
24 normalizeToolArguments,
25 } from '@composio/core';
26 import type { ToolSet as VercelToolSet, Tool as VercelTool } from 'ai';
@@ -109,18 +112,27 @@ export class VercelProvider extends BaseAgenticProvider<
112 wrapTool(composioTool: Tool, executeTool: ExecuteToolFn): VercelTool {
113 const inputParams = composioTool.inputParameters;
114
112 - const parameters =
113 - this.strict && inputParams?.type === 'object'
114 - ? removeNonRequiredProperties(
115 - inputParams as {
116 - type: 'object';
117 - properties: Record<string, unknown>;
118 - required?: string[];
119 - }
120 - )
121 - : (inputParams ?? {});
115 + let parameters: Record<string, unknown> = (inputParams ?? {}) as Record<string, unknown>;
116 + if (this.strict && inputParams?.type === 'object') {
117 + // Structured outputs reject schemas whose nested objects keep optional
118 + // properties or their own additionalProperties, so the strict contract
119 + // must be applied at every depth. Inline $ref/$defs first (lenient mode
120 + // keeps upstream schemas with dangling refs usable), then normalize.
121 + const dereferenced = dereferenceJsonSchema(parameters, {
122 + onUnresolved: 'sentinel',
123 + onReplace: ref =>
124 + logger.debug(
125 + `VercelProvider: unresolved $ref "${ref}" in tool "${composioTool.slug}" replaced with a permissive schema`
126 + ),
127 + });
128 + parameters = toStrictJsonSchema<Record<string, unknown>>(dereferenced).schema;
129 + }
130
123 - const inputParametersSchema = jsonSchemaToZodSchema(parameters);
131 + // Canonicalize required arrays at the vendor-schema emission boundary,
132 + // after any provider-specific schema transformations.
133 + const inputParametersSchema = jsonSchemaToZodSchema(
134 + deduplicateJsonSchemaRequiredArrays(parameters)
135 + );
136
137 return tool({
138 description: composioTool.description,
ts/packages/providers/vercel/test/vercel.test.ts
+32
@@ -133,6 +133,38 @@ describe('VercelProvider', () => {
133
134 expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
135 });
136 +
137 + it('enforces the strict contract on complex schemas when strict mode is enabled', () => {
138 + const strictProvider = new VercelProvider({ strict: true });
139 + const wrapped = strictProvider.wrapTool(
140 + {
141 + ...mockTool,
142 + inputParameters: {
143 + type: 'object',
144 + properties: {
145 + cfg: {
146 + type: 'object',
147 + properties: { url: { type: 'string' }, note: { type: 'string' } },
148 + required: ['url'],
149 + },
150 + id: { type: ['string', 'null'] },
151 + },
152 + required: ['cfg', 'id'],
153 + },
154 + },
155 + mockExecuteToolFn
156 + ) as unknown as MockedVercelTool;
157 +
158 + const schema = wrapped.inputSchema as { safeParse: (value: unknown) => { success: boolean } };
159 +
160 + // Nested required key present, nullable field null — valid.
161 + expect(schema.safeParse({ cfg: { url: 'https://example.com' }, id: null }).success).toBe(
162 + true
163 + );
164 + // Nested optional property was dropped under strict mode, so a value for
165 + // it no longer parses.
166 + expect(schema.safeParse({ cfg: { note: 'x' }, id: 'a' }).success).toBe(false);
167 + });
168 });
169
170 describe('wrapTools', () => {