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.

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

AseemPrasad04817cb20dd3
diff --git a/.changeset/strict-schema-normalization.md b/.changeset/strict-schema-normalization.md
new file mode 100644
index 000000000..2443bcda2
--- /dev/null
+++ b/.changeset/strict-schema-normalization.md
@@ -0,0 +1,7 @@
+---
+'@composio/core': patch
+'@composio/openai': patch
+'@composio/vercel': patch
+---
+
+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.
diff --git a/python/composio/core/provider/_openai_responses.py b/python/composio/core/provider/_openai_responses.py
index 2e3b72917..d735585e4 100644
--- a/python/composio/core/provider/_openai_responses.py
+++ b/python/composio/core/provider/_openai_responses.py
@@ -11,11 +11,13 @@ from openai.types.responses.response_output_item import ResponseFunctionToolCall
from composio.core.provider import NonAgenticProvider
from composio.types import Modifiers, Tool, ToolExecutionResponse
+from composio.utils.json_schema import dereference_json_schema
from composio.utils.shared import normalize_tool_arguments
+from composio.utils.strict_schema import to_strict_json_schema
# Responses API uses a flattened tool structure
-ResponsesTool = t.Dict[str, t.Any]
-ResponsesToolCollection = t.List[ResponsesTool]
+ResponsesTool = dict[str, t.Any]
+ResponsesToolCollection = list[ResponsesTool]
class OpenAIResponsesProvider(
@@ -23,13 +25,36 @@ class OpenAIResponsesProvider(
):
"""OpenAI Responses API Provider class definition."""
+ def __init__(self, strict: bool = False) -> None:
+ """
+ :param strict: Normalize wrapped tool parameter schemas for OpenAI
+ structured outputs (every object fully required and closed,
+ nullable types via ``anyOf``, ``$ref``/``$defs`` inlined).
+ Mirrors the TypeScript ``OpenAIResponsesProvider({ strict })``
+ option. Defaults to ``False``.
+ """
+ self.strict = strict
+
def wrap_tool(self, tool: Tool) -> ResponsesTool:
"""Wrap a tool for the Responses API format."""
+ parameters: t.Any = tool.input_parameters or {}
+ if (
+ self.strict
+ and isinstance(parameters, dict)
+ and parameters.get("type") == "object"
+ ):
+ # Structured outputs reject schemas whose nested objects keep
+ # optional properties or their own additionalProperties, so the
+ # strict contract must be applied at every depth. Inline $refs
+ # first; lenient mode keeps upstream schemas with dangling refs
+ # usable.
+ dereferenced = dereference_json_schema(parameters, on_unresolved="sentinel")
+ parameters = to_strict_json_schema(dereferenced).schema
return {
"type": "function",
"name": tool.slug,
"description": tool.description,
- "parameters": tool.input_parameters,
+ "parameters": parameters,
}
def wrap_tools(self, tools: t.Sequence[Tool]) -> ResponsesToolCollection:
@@ -39,8 +64,8 @@ class OpenAIResponsesProvider(
def execute_tool_call(
self,
user_id: str,
- tool_call: t.Union[ResponseFunctionToolCall],
- modifiers: t.Optional[Modifiers] = None,
+ tool_call: ResponseFunctionToolCall,
+ modifiers: Modifiers | None = None,
) -> ToolExecutionResponse:
"""Execute a tool call from the Responses API.
@@ -65,8 +90,8 @@ class OpenAIResponsesProvider(
self,
user_id: str,
response: Response,
- modifiers: t.Optional[Modifiers] = None,
- ) -> t.List[ToolExecutionResponse]:
+ modifiers: Modifiers | None = None,
+ ) -> list[ToolExecutionResponse]:
"""
Handle tool calls from OpenAI Responses API.
diff --git a/python/composio/utils/strict_schema.py b/python/composio/utils/strict_schema.py
new file mode 100644
index 000000000..5728ba3eb
--- /dev/null
+++ b/python/composio/utils/strict_schema.py
@@ -0,0 +1,231 @@
+"""Normalize JSON Schemas for OpenAI structured outputs (``strict`` mode).
+
+Python counterpart of the TypeScript SDK's ``toStrictJsonSchema``
+(``ts/packages/core/src/utils/jsonSchema.ts``). OpenAI's structured-output
+contract requires *every* object node — not just the root — to list all of its
+properties in ``required``, set ``additionalProperties: False``, avoid
+annotation-only keywords, and express nullable / multi-typed fields via
+``anyOf``. Tool parameter schemas that nest objects or use ``type`` arrays are
+otherwise rejected by the API with a 400.
+
+Every structural change is recorded so callers can surface diagnostics instead
+of failing silently. The input is never mutated. Dereference ``$ref`` pointers
+first (see :func:`composio.utils.json_schema.dereference_json_schema`) so
+definitions under ``$defs`` are normalized too.
+"""
+
+from __future__ import annotations
+
+import typing as t
+
+MAX_NODE_DEPTH = 512
+MAX_CHANGES = 50
+
+# Annotation-only keywords OpenAI structured outputs rejects; safe to strip.
+STRICT_STRIP_KEYWORDS = frozenset({"examples", "default"})
+
+# Keywords whose values are literal data, not schemas - never recursed as schemas.
+STRICT_INSTANCE_VALUE_KEYWORDS = frozenset({"const", "enum"})
+
+STRICT_SCHEMA_SINGLE_KEYS = frozenset(
+ {
+ "additionalItems",
+ "additionalProperties",
+ "contains",
+ "contentSchema",
+ "else",
+ "if",
+ "not",
+ "propertyNames",
+ "then",
+ "unevaluatedItems",
+ "unevaluatedProperties",
+ }
+)
+STRICT_SCHEMA_ARRAY_KEYS = frozenset({"allOf", "anyOf", "oneOf", "prefixItems"})
+STRICT_SCHEMA_MAP_KEYS = frozenset(
+ {"$defs", "definitions", "dependentSchemas", "patternProperties", "properties"}
+)
+
+
+class StrictSchemaChange(t.NamedTuple):
+ """A single structural change applied by :func:`to_strict_json_schema`."""
+
+ path: str
+ reason: str
+ detail: str = ""
+
+
+class StrictJsonSchemaResult(t.NamedTuple):
+ """Normalized schema plus a change log."""
+
+ schema: t.Any
+ changes: list[StrictSchemaChange]
+
+
+def _join_path(parent: str, key: str) -> str:
+ return f"{parent}.{key}" if parent else key
+
+
+def _split_type_array(
+ node: dict[str, t.Any], path: str, changes: list[StrictSchemaChange]
+) -> dict[str, t.Any]:
+ type_values = node["type"]
+ branches = [
+ {"type": "null"} if value == "null" else {**node, "type": value}
+ for value in type_values
+ ]
+ rest = {key: value for key, value in node.items() if key != "type"}
+ reason = (
+ "nullable-type-converted" if "null" in type_values else "multi-type-converted"
+ )
+ if len(changes) < MAX_CHANGES:
+ changes.append(
+ StrictSchemaChange(
+ path=path,
+ reason=reason,
+ detail=f"type [{', '.join(str(value) for value in type_values)}] converted to anyOf",
+ )
+ )
+ return {**rest, "anyOf": branches}
+
+
+def _walk(
+ value: t.Any,
+ mode: str,
+ depth: int,
+ path: str,
+ changes: list[StrictSchemaChange],
+) -> t.Any:
+ if depth > MAX_NODE_DEPTH:
+ raise ValueError(
+ f"JSON Schema exceeds maximum nesting depth of {MAX_NODE_DEPTH}"
+ )
+
+ if isinstance(value, list):
+ item_mode = "schema" if mode == "schema-array" else "value"
+ return [
+ _walk(item, item_mode, depth + 1, f"{path}[{index}]", changes)
+ for index, item in enumerate(value)
+ ]
+
+ if not isinstance(value, dict) or mode == "value":
+ return value
+
+ node: dict[str, t.Any] = value
+
+ # Nullable / multi-type arrays must become anyOf before anything else so
+ # the generated branches flow through the normal recursion below.
+ if isinstance(node.get("type"), list):
+ node = _split_type_array(node, path, changes)
+
+ stripped: dict[str, t.Any] = {}
+ for key, child in node.items():
+ if key in STRICT_STRIP_KEYWORDS:
+ if len(changes) < MAX_CHANGES:
+ changes.append(
+ StrictSchemaChange(
+ path=path,
+ reason="annotation-keyword-stripped",
+ detail=f'keyword "{key}" removed',
+ )
+ )
+ continue
+ stripped[key] = child
+ node = stripped
+
+ has_properties_keyword = isinstance(node.get("properties"), dict)
+ if not (has_properties_keyword or node.get("type") == "object"):
+ return _walk_children(node, mode, depth, path, changes)
+
+ properties = node["properties"] if has_properties_keyword else {}
+ declared_required = [
+ entry for entry in node.get("required", []) if isinstance(entry, str)
+ ]
+ keep_only_required = len(declared_required) > 0
+ kept = set(declared_required if keep_only_required else properties.keys())
+
+ next_properties: dict[str, t.Any] = {}
+ for name, property_schema in properties.items():
+ child_path = _join_path(path, f"properties.{name}")
+ if name in kept:
+ next_properties[name] = _walk(
+ property_schema, "schema", depth + 1, child_path, changes
+ )
+ elif len(changes) < MAX_CHANGES:
+ changes.append(
+ StrictSchemaChange(
+ path=child_path,
+ reason="non-required-property-dropped",
+ detail=f'property "{name}" is not listed in "required"',
+ )
+ )
+
+ managed = ("type", "properties", "required", "additionalProperties")
+ rest = {key: child for key, child in node.items() if key not in managed}
+
+ return {
+ **_walk_children(rest, "schema", depth, path, changes),
+ "type": "object",
+ "properties": next_properties,
+ "required": list(next_properties.keys()),
+ "additionalProperties": False,
+ }
+
+
+def _walk_children(
+ node: dict[str, t.Any],
+ mode: str,
+ depth: int,
+ path: str,
+ changes: list[StrictSchemaChange],
+) -> dict[str, t.Any]:
+ clone: dict[str, t.Any] = {}
+ for key, child in node.items():
+ child_mode = "value"
+ if mode == "schema-map":
+ child_mode = "schema"
+ elif mode == "schema" and key not in STRICT_INSTANCE_VALUE_KEYWORDS:
+ if key in STRICT_SCHEMA_MAP_KEYS:
+ child_mode = "schema-map"
+ elif key in STRICT_SCHEMA_ARRAY_KEYS or (
+ key == "items" and isinstance(child, list)
+ ):
+ child_mode = "schema-array"
+ elif key in STRICT_SCHEMA_SINGLE_KEYS or key == "items":
+ child_mode = "schema"
+
+ if child_mode == "schema-map" and isinstance(child, dict):
+ map_clone: dict[str, t.Any] = {}
+ for name, sub_schema in child.items():
+ map_clone[name] = _walk(
+ sub_schema,
+ "schema",
+ depth + 1,
+ _join_path(_join_path(path, key), name),
+ changes,
+ )
+ clone[key] = map_clone
+ continue
+ clone[key] = _walk(child, child_mode, depth + 1, _join_path(path, key), changes)
+ return clone
+
+
+def to_strict_json_schema(schema: t.Any) -> StrictJsonSchemaResult:
+ """Normalize a JSON Schema for OpenAI structured outputs.
+
+ Applies the strict contract at every depth:
+
+ - Objects with a non-empty ``required`` keep only those properties;
+ objects without one keep every property but require them all.
+ - ``type`` arrays become ``anyOf`` branches with an explicit null variant.
+ - Annotation keywords (``examples``, ``default``) are stripped.
+ - Composition keywords, array items and property maps normalize recursively.
+
+ :param schema: The JSON schema to normalize; never mutated.
+ :return: A :class:`StrictJsonSchemaResult` with the normalized schema and
+ a change log capped at 50 entries.
+ """
+ changes: list[StrictSchemaChange] = []
+ normalized = _walk(schema, "schema", 0, "", changes)
+ return StrictJsonSchemaResult(schema=normalized, changes=changes)
diff --git a/python/tests/test_strict_schema.py b/python/tests/test_strict_schema.py
new file mode 100644
index 000000000..df82910b6
--- /dev/null
+++ b/python/tests/test_strict_schema.py
@@ -0,0 +1,284 @@
+"""Tests for composio.utils.strict_schema and its use by OpenAIResponsesProvider."""
+
+import pytest
+
+from composio.utils.strict_schema import to_strict_json_schema
+
+
+class TestToStrictJsonSchema:
+ def test_keeps_flat_all_required_object_valid(self):
+ schema = {
+ "type": "object",
+ "properties": {"query": {"type": "string"}},
+ "required": ["query"],
+ "additionalProperties": False,
+ }
+
+ result = to_strict_json_schema(schema)
+
+ assert result.schema == schema
+ assert result.changes == []
+
+ def test_drops_nested_non_required_properties_and_closes_every_object(self):
+ result = to_strict_json_schema(
+ {
+ "type": "object",
+ "properties": {
+ "cfg": {
+ "type": "object",
+ "properties": {
+ "url": {"type": "string"},
+ "note": {"type": "string"},
+ },
+ "required": ["url"],
+ }
+ },
+ "required": ["cfg"],
+ }
+ )
+
+ assert result.schema == {
+ "type": "object",
+ "properties": {
+ "cfg": {
+ "type": "object",
+ "properties": {"url": {"type": "string"}},
+ "required": ["url"],
+ "additionalProperties": False,
+ }
+ },
+ "required": ["cfg"],
+ "additionalProperties": False,
+ }
+ dropped = [
+ change
+ for change in result.changes
+ if change.reason == "non-required-property-dropped"
+ ]
+ assert len(dropped) == 1
+ assert "note" in dropped[0].detail
+
+ def test_requires_every_property_when_required_is_missing(self):
+ result = to_strict_json_schema(
+ {
+ "type": "object",
+ "properties": {"a": {"type": "string"}, "b": {"type": "number"}},
+ }
+ )
+
+ assert result.schema["required"] == ["a", "b"]
+ assert result.schema["additionalProperties"] is False
+
+ def test_converts_nullable_type_arrays_into_any_of(self):
+ result = to_strict_json_schema(
+ {
+ "type": "object",
+ "properties": {
+ "id": {"type": ["string", "null"], "description": "identifier"}
+ },
+ "required": ["id"],
+ }
+ )
+
+ assert result.schema["properties"]["id"] == {
+ "anyOf": [
+ {"type": "string", "description": "identifier"},
+ {"type": "null"},
+ ],
+ "description": "identifier",
+ }
+ reasons = {change.reason for change in result.changes}
+ assert "nullable-type-converted" in reasons
+
+ def test_normalizes_composition_branches_recursively(self):
+ result = to_strict_json_schema(
+ {
+ "type": "object",
+ "properties": {
+ "payload": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "inner": {"type": "string"},
+ "extra": {"type": "string"},
+ },
+ "required": ["inner"],
+ },
+ {"type": "null"},
+ ]
+ }
+ },
+ "required": ["payload"],
+ }
+ )
+
+ branch = result.schema["properties"]["payload"]["anyOf"][0]
+ assert branch == {
+ "type": "object",
+ "properties": {"inner": {"type": "string"}},
+ "required": ["inner"],
+ "additionalProperties": False,
+ }
+
+ def test_normalizes_array_items(self):
+ result = to_strict_json_schema(
+ {
+ "type": "object",
+ "properties": {
+ "rows": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {"type": "string"},
+ "tag": {"type": "string"},
+ },
+ "required": ["id"],
+ },
+ }
+ },
+ "required": ["rows"],
+ }
+ )
+
+ assert result.schema["properties"]["rows"]["items"] == {
+ "type": "object",
+ "properties": {"id": {"type": "string"}},
+ "required": ["id"],
+ "additionalProperties": False,
+ }
+
+ def test_strips_annotation_keywords_and_reports_them(self):
+ result = to_strict_json_schema(
+ {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "examples": ["a"], "default": "x"}
+ },
+ "required": ["name"],
+ }
+ )
+
+ assert result.schema["properties"]["name"] == {"type": "string"}
+ stripped = [
+ change
+ for change in result.changes
+ if change.reason == "annotation-keyword-stripped"
+ ]
+ assert len(stripped) == 2
+
+ def test_does_not_mutate_input(self):
+ schema = {
+ "type": "object",
+ "properties": {
+ "cfg": {"type": "object", "properties": {"opt": {"type": "string"}}}
+ },
+ "required": ["cfg"],
+ }
+ import copy
+
+ snapshot = copy.deepcopy(schema)
+
+ to_strict_json_schema(schema)
+
+ assert schema == snapshot
+
+ def test_raises_past_maximum_depth(self):
+ deep = {"type": "string"}
+ for _ in range(600):
+ deep = {
+ "type": "object",
+ "properties": {"nest": deep},
+ "required": ["nest"],
+ }
+
+ with pytest.raises(ValueError, match="maximum nesting depth"):
+ to_strict_json_schema(deep)
+
+
+class TestOpenAIResponsesProviderStrict:
+ def _tool(self, input_parameters):
+ from tests.test_provider import create_mock_tool
+
+ tool = create_mock_tool("TEST_TOOL", "composio")
+ tool.input_parameters = input_parameters
+ return tool
+
+ def test_wrap_tool_passes_parameters_through_by_default(self):
+ from composio.core.provider._openai_responses import OpenAIResponsesProvider
+
+ provider = OpenAIResponsesProvider()
+ wrapped = provider.wrap_tool(self._tool({"type": "object", "properties": {}}))
+
+ assert wrapped["parameters"] == {"type": "object", "properties": {}}
+
+ def test_wrap_tool_normalizes_complex_schemas_in_strict_mode(self):
+ from composio.core.provider._openai_responses import OpenAIResponsesProvider
+
+ provider = OpenAIResponsesProvider(strict=True)
+ wrapped = provider.wrap_tool(
+ self._tool(
+ {
+ "type": "object",
+ "properties": {
+ "cfg": {
+ "type": "object",
+ "properties": {
+ "url": {"type": "string"},
+ "note": {"type": "string"},
+ },
+ "required": ["url"],
+ },
+ "id": {"type": ["string", "null"]},
+ },
+ "required": ["cfg", "id"],
+ }
+ )
+ )
+
+ import json
+
+ assert "$ref" not in json.dumps(wrapped)
+ assert wrapped["parameters"] == {
+ "type": "object",
+ "properties": {
+ "cfg": {
+ "type": "object",
+ "properties": {"url": {"type": "string"}},
+ "required": ["url"],
+ "additionalProperties": False,
+ },
+ "id": {"anyOf": [{"type": "string"}, {"type": "null"}]},
+ },
+ "required": ["cfg", "id"],
+ "additionalProperties": False,
+ }
+
+ def test_wrap_tool_inlines_defs_in_strict_mode(self):
+ from composio.core.provider._openai_responses import OpenAIResponsesProvider
+
+ provider = OpenAIResponsesProvider(strict=True)
+ wrapped = provider.wrap_tool(
+ self._tool(
+ {
+ "type": "object",
+ "properties": {"cfg": {"$ref": "#/$defs/Config"}},
+ "required": ["cfg"],
+ "$defs": {
+ "Config": {
+ "type": "object",
+ "properties": {"url": {"type": "string"}},
+ "required": ["url"],
+ }
+ },
+ }
+ )
+ )
+
+ assert wrapped["parameters"]["properties"]["cfg"] == {
+ "type": "object",
+ "properties": {"url": {"type": "string"}},
+ "required": ["url"],
+ "additionalProperties": False,
+ }
diff --git a/ts/packages/core/src/index.ts b/ts/packages/core/src/index.ts
index 874d7b023..49e27e1f5 100644
--- a/ts/packages/core/src/index.ts
+++ b/ts/packages/core/src/index.ts
@@ -10,11 +10,15 @@ export {
ensureObjectTypeOnProperties,
jsonSchemaToZodSchema,
removeNonRequiredProperties,
+ toStrictJsonSchema,
} from './utils/jsonSchema';
export type {
DereferenceJsonSchemaOptions,
UnresolvedRefReason,
UnresolvedRefStrategy,
+ StrictSchemaChange,
+ StrictSchemaChangeReason,
+ StrictJsonSchemaResult,
} from './utils/jsonSchema';
export { getExtensionFromMimeType } from './utils/mime';
export { normalizeToolArguments } from './utils/toolArguments';
diff --git a/ts/packages/core/src/utils/jsonSchema.ts b/ts/packages/core/src/utils/jsonSchema.ts
index 657600117..db56ecff1 100644
--- a/ts/packages/core/src/utils/jsonSchema.ts
+++ b/ts/packages/core/src/utils/jsonSchema.ts
@@ -496,3 +496,246 @@ export function jsonSchemaToZodSchema<T extends z.ZodTypeAny>(
});
}
}
+
+/**
+ * Reason recorded when strict normalization changes a schema node.
+ *
+ * - `nullable-type-converted` — a `type` array containing `'null'` became an
+ * `anyOf` with an explicit `{ type: 'null' }` branch.
+ * - `multi-type-converted` — a `type` array without `'null'` (e.g.
+ * `['string', 'number']`) became equivalent `anyOf` branches.
+ * - `annotation-keyword-stripped` — an annotation-only keyword (`examples`,
+ * `default`) that strict mode rejects was removed.
+ * - `non-required-property-dropped` — a property not listed in `required`
+ * was removed from its parent object.
+ */
+export type StrictSchemaChangeReason =
+ | 'nullable-type-converted'
+ | 'multi-type-converted'
+ | 'annotation-keyword-stripped'
+ | 'non-required-property-dropped';
+
+/** A single structural change applied by {@link toStrictJsonSchema}. */
+export interface StrictSchemaChange {
+ /** Path to the changed node relative to the root, e.g. `properties.cfg.items`. */
+ path: string;
+ reason: StrictSchemaChangeReason;
+ /** Human-readable detail about what specifically changed. */
+ detail?: string;
+}
+
+/** Result of {@link toStrictJsonSchema}: the normalized schema plus a change log. */
+export interface StrictJsonSchemaResult<T = unknown> {
+ schema: T;
+ changes: StrictSchemaChange[];
+}
+
+const MAX_STRICT_CHANGES = 50;
+
+/** Annotation-only keywords OpenAI structured outputs rejects; safe to strip. */
+const STRICT_STRIP_KEYWORDS = new Set(['examples', 'default']);
+
+/** Keywords whose values are literal data, not schemas — never recursed as schemas. */
+const STRICT_INSTANCE_VALUE_KEYWORDS = new Set(['const', 'enum']);
+
+const STRICT_SCHEMA_SINGLE_KEYS = new Set([
+ 'additionalItems',
+ 'additionalProperties',
+ 'contains',
+ 'contentSchema',
+ 'else',
+ 'if',
+ 'not',
+ 'propertyNames',
+ 'then',
+ 'unevaluatedItems',
+ 'unevaluatedProperties',
+]);
+const STRICT_SCHEMA_ARRAY_KEYS = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems']);
+const STRICT_SCHEMA_MAP_KEYS = new Set([
+ '$defs',
+ 'definitions',
+ 'dependentSchemas',
+ 'patternProperties',
+ 'properties',
+]);
+
+type StrictWalkMode = 'schema' | 'schema-array' | 'schema-map' | 'value';
+
+/**
+ * Normalizes a JSON Schema for OpenAI structured outputs (`strict: true`),
+ * which requires every object node to declare all of its properties in
+ * `required`, set `additionalProperties: false`, use only supported keywords,
+ * and express nullable / multi-typed fields via `anyOf`.
+ *
+ * The top-level `removeNonRequiredProperties` only handled the root object,
+ * so nested objects, composition branches and array items passed through
+ * untouched and the API rejected the whole request. This function applies the
+ * same contract at every depth:
+ *
+ * - Objects with a non-empty `required` keep only those properties
+ * (matching the established top-level behavior); objects without one keep
+ * every property but are forced to require them all — dropping everything
+ * would gut the tool, and leaving optional properties would be rejected.
+ * - `type` arrays become `anyOf` branches with an explicit `{type:'null'}`
+ * variant where applicable.
+ * - Annotation keywords (`examples`, `default`) are stripped.
+ * - Composition keywords (`anyOf`/`oneOf`/`allOf`), array `items`/
+ * `prefixItems` and property maps are normalized recursively.
+ *
+ * Every structural change is recorded so callers can surface diagnostics
+ * instead of failing silently. The input is never mutated. Dereference
+ * `$ref`s first (see {@link dereferenceJsonSchema}) so definitions referenced
+ * under `$defs` are normalized too, then run
+ * {@link deduplicateJsonSchemaRequiredArrays} on the result before emitting.
+ */
+export function toStrictJsonSchema<T = unknown>(schema: T): StrictJsonSchemaResult<T> {
+ const changes: StrictSchemaChange[] = [];
+ const recordChange = (change: StrictSchemaChange): void => {
+ if (changes.length < MAX_STRICT_CHANGES) {
+ changes.push(change);
+ }
+ };
+
+ const joinPath = (parent: string, key: string): string =>
+ parent ? `${parent}.${key}` : key;
+
+ const splitTypeArray = (node: Record<string, unknown>, path: string): Record<string, unknown> => {
+ const typeValues = node.type as unknown[];
+ const branches = typeValues.map(typeValue =>
+ typeValue === 'null' ? { type: 'null' } : { ...node, type: typeValue }
+ );
+ const { type: _droppedType, ...rest } = node;
+ recordChange({
+ path,
+ reason: typeValues.includes('null') ? 'nullable-type-converted' : 'multi-type-converted',
+ detail: `type [${typeValues.map(String).join(', ')}] converted to anyOf`,
+ });
+ return { ...rest, anyOf: branches };
+ };
+
+ function walkChildren(
+ node: Record<string, unknown>,
+ mode: StrictWalkMode,
+ depth: number,
+ path: string
+ ): Record<string, unknown> {
+ const clone: Record<string, unknown> = {};
+ for (const [key, child] of Object.entries(node)) {
+ let childMode: StrictWalkMode = 'value';
+ if (mode === 'schema-map') {
+ childMode = 'schema';
+ } else if (mode === 'schema') {
+ if (!STRICT_INSTANCE_VALUE_KEYWORDS.has(key)) {
+ if (STRICT_SCHEMA_MAP_KEYS.has(key)) {
+ childMode = 'schema-map';
+ } else if (STRICT_SCHEMA_ARRAY_KEYS.has(key) || (key === 'items' && Array.isArray(child))) {
+ childMode = 'schema-array';
+ } else if (STRICT_SCHEMA_SINGLE_KEYS.has(key) || key === 'items') {
+ childMode = 'schema';
+ }
+ }
+ }
+
+ if (childMode === 'schema-map' && isPlainObject(child)) {
+ const mapClone: Record<string, unknown> = {};
+ for (const [name, subSchema] of Object.entries(child)) {
+ mapClone[name] = walk(subSchema, 'schema', depth + 1, joinPath(joinPath(path, key), name));
+ }
+ clone[key] = mapClone;
+ continue;
+ }
+ clone[key] = walk(child, childMode, depth + 1, joinPath(path, key));
+ }
+ return clone;
+ }
+
+ function walk(value: unknown, mode: StrictWalkMode, depth: number, path: string): unknown {
+ if (depth > MAX_NODE_DEPTH) {
+ throw new RangeError(`JSON Schema exceeds maximum nesting depth of ${MAX_NODE_DEPTH}`);
+ }
+ if (Array.isArray(value)) {
+ const itemMode = mode === 'schema-array' ? 'schema' : 'value';
+ return value.map((item, index) => walk(item, itemMode, depth + 1, `${path}[${index}]`));
+ }
+ if (!isPlainObject(value)) return value;
+ if (mode === 'value') return value;
+
+ let node: Record<string, unknown> = value;
+
+ // Nullable / multi-type arrays must become anyOf before anything else so
+ // the generated branches flow through the normal recursion below.
+ if (Array.isArray(node.type)) {
+ node = splitTypeArray(node, path);
+ }
+
+ const strippedNode: Record<string, unknown> = {};
+ for (const [key, child] of Object.entries(node)) {
+ if (STRICT_STRIP_KEYWORDS.has(key)) {
+ recordChange({
+ path,
+ reason: 'annotation-keyword-stripped',
+ detail: `keyword "${key}" removed`,
+ });
+ continue;
+ }
+ strippedNode[key] = child;
+ }
+ node = strippedNode;
+
+ // Object strictening: complete required, closed additionalProperties.
+ const hasPropertiesKeyword = isPlainObject(node.properties);
+ const isObjectNode = hasPropertiesKeyword || node.type === 'object';
+ if (isObjectNode) {
+ const properties = hasPropertiesKeyword
+ ? (node.properties as Record<string, unknown>)
+ : {};
+ const declaredRequired = Array.isArray(node.required)
+ ? node.required.filter((entry): entry is string => typeof entry === 'string')
+ : [];
+ const keepOnlyRequired = declaredRequired.length > 0;
+ const keptKeys = new Set(
+ keepOnlyRequired ? declaredRequired.filter(key => key in properties) : Object.keys(properties)
+ );
+
+ const nextProperties: Record<string, unknown> = {};
+ for (const [name, propertySchema] of Object.entries(properties)) {
+ if (keptKeys.has(name)) {
+ nextProperties[name] = walk(
+ propertySchema,
+ 'schema',
+ depth + 1,
+ joinPath(path, `properties.${name}`)
+ );
+ } else {
+ recordChange({
+ path: joinPath(path, `properties.${name}`),
+ reason: 'non-required-property-dropped',
+ detail: `property "${name}" is not listed in "required"`,
+ });
+ }
+ }
+
+ // Recurse into any remaining schema-bearing siblings (e.g. `allOf`,
+ // `description`) while keeping the four managed keywords authoritative.
+ const managedKeys = new Set(['type', 'properties', 'required', 'additionalProperties']);
+ const restNode: Record<string, unknown> = {};
+ for (const [key, child] of Object.entries(node)) {
+ if (!managedKeys.has(key)) restNode[key] = child;
+ }
+
+ return {
+ ...walkChildren(restNode, 'schema', depth, path),
+ type: 'object',
+ properties: nextProperties,
+ required: Object.keys(nextProperties),
+ additionalProperties: false,
+ };
+ }
+
+ return walkChildren(node, mode, depth, path);
+ }
+
+ const normalized = walk(schema, 'schema', 0, '');
+ return { schema: normalized as T, changes };
+}
diff --git a/ts/packages/core/test/utils/jsonSchema.strict.test.ts b/ts/packages/core/test/utils/jsonSchema.strict.test.ts
new file mode 100644
index 000000000..122220cdd
--- /dev/null
+++ b/ts/packages/core/test/utils/jsonSchema.strict.test.ts
@@ -0,0 +1,262 @@
+import { describe, it, expect } from 'vitest';
+import {
+ deduplicateJsonSchemaRequiredArrays,
+ dereferenceJsonSchema,
+ toStrictJsonSchema,
+} from '../../src/utils/jsonSchema';
+
+const propertyOf = (schema: unknown, name: string): Record<string, unknown> =>
+ ((schema as Record<string, unknown>).properties as Record<string, string>)[
+ name
+ ] as unknown as Record<string, unknown>;
+
+describe('toStrictJsonSchema', () => {
+ it('keeps an already-flat all-required object valid', () => {
+ const input = {
+ type: 'object',
+ properties: { query: { type: 'string' } },
+ required: ['query'],
+ additionalProperties: false,
+ };
+
+ const { schema, changes } = toStrictJsonSchema(input);
+
+ expect(schema).toEqual(input);
+ expect(changes).toEqual([]);
+ });
+
+ it('drops nested non-required properties and closes every object', () => {
+ const { schema } = toStrictJsonSchema({
+ type: 'object',
+ properties: {
+ cfg: {
+ type: 'object',
+ properties: {
+ url: { type: 'string' },
+ note: { type: 'string' },
+ },
+ required: ['url'],
+ },
+ },
+ required: ['cfg'],
+ });
+
+ expect(schema).toEqual({
+ type: 'object',
+ properties: {
+ cfg: {
+ type: 'object',
+ properties: {
+ url: { type: 'string' },
+ },
+ required: ['url'],
+ additionalProperties: false,
+ },
+ },
+ required: ['cfg'],
+ additionalProperties: false,
+ });
+ });
+
+ it('requires every property when the object has no required array', () => {
+ const { schema } = toStrictJsonSchema({
+ type: 'object',
+ properties: {
+ a: { type: 'string' },
+ b: { type: 'number' },
+ },
+ });
+
+ expect(schema).toEqual({
+ type: 'object',
+ properties: {
+ a: { type: 'string' },
+ b: { type: 'number' },
+ },
+ required: ['a', 'b'],
+ additionalProperties: false,
+ });
+ });
+
+ it('converts nullable type arrays into anyOf with an explicit null branch', () => {
+ const { schema } = toStrictJsonSchema({
+ type: 'object',
+ properties: {
+ id: { type: ['string', 'null'], description: 'identifier' },
+ },
+ required: ['id'],
+ });
+
+ expect(schema).toEqual({
+ type: 'object',
+ properties: {
+ id: {
+ anyOf: [{ type: 'string', description: 'identifier' }, { type: 'null' }],
+ description: 'identifier',
+ },
+ },
+ required: ['id'],
+ additionalProperties: false,
+ });
+ });
+
+ it('converts multi-type arrays into anyOf branches', () => {
+ const { schema } = toStrictJsonSchema({
+ type: 'object',
+ properties: {
+ value: { type: ['string', 'number'] },
+ },
+ required: ['value'],
+ });
+
+ const property = propertyOf(schema, 'value');
+ expect(property.anyOf).toEqual([{ type: 'string' }, { type: 'number' }]);
+ });
+
+ it('normalizes composition branches recursively', () => {
+ const { schema } = toStrictJsonSchema({
+ type: 'object',
+ properties: {
+ payload: {
+ anyOf: [
+ {
+ type: 'object',
+ properties: { inner: { type: 'string' }, extra: { type: 'string' } },
+ required: ['inner'],
+ },
+ { type: 'null' },
+ ],
+ },
+ },
+ required: ['payload'],
+ });
+
+ const payload = propertyOf(schema, 'payload');
+ expect(payload.anyOf[0]).toEqual({
+ type: 'object',
+ properties: { inner: { type: 'string' } },
+ required: ['inner'],
+ additionalProperties: false,
+ });
+ });
+
+ it('normalizes array item schemas including tuples', () => {
+ const { schema } = toStrictJsonSchema({
+ type: 'object',
+ properties: {
+ rows: {
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: { id: { type: 'string' }, tag: { type: 'string' } },
+ required: ['id'],
+ },
+ },
+ pair: {
+ type: 'array',
+ prefixItems: [
+ { type: 'object', properties: { x: { type: 'number' }, y: { type: 'number' } } },
+ ],
+ },
+ },
+ required: ['rows', 'pair'],
+ });
+
+ const props = (schema as Record<string, unknown>).properties as Record<
+ string,
+ Record<string, unknown>
+ >;
+ expect(props.rows.items).toEqual({
+ type: 'object',
+ properties: { id: { type: 'string' } },
+ required: ['id'],
+ additionalProperties: false,
+ });
+ expect(props.pair.prefixItems[0]).toEqual({
+ type: 'object',
+ properties: { x: { type: 'number' }, y: { type: 'number' } },
+ required: ['x', 'y'],
+ additionalProperties: false,
+ });
+ });
+
+ it('strips annotation keywords and reports them', () => {
+ const { schema, changes } = toStrictJsonSchema({
+ type: 'object',
+ properties: { name: { type: 'string', examples: ['a'], default: 'x' } },
+ required: ['name'],
+ });
+
+ expect(propertyOf(schema, 'name')).toEqual({ type: 'string' });
+ expect(changes.filter(change => change.reason === 'annotation-keyword-stripped')).toHaveLength(
+ 2
+ );
+ });
+
+ it('reports dropped properties as changes without exceeding the cap', () => {
+ const properties: Record<string, unknown> = {};
+ for (let i = 0; i < 60; i++) properties[`p${i}`] = { type: 'string' };
+
+ const { schema, changes } = toStrictJsonSchema({
+ type: 'object',
+ properties,
+ required: ['p0'],
+ });
+
+ expect(Object.keys((schema as Record<string, unknown>).properties as object)).toEqual(['p0']);
+ expect(changes.length).toBeLessThanOrEqual(50);
+ });
+
+ it('does not mutate the input schema', () => {
+ const input = {
+ type: 'object',
+ properties: {
+ cfg: {
+ type: 'object',
+ properties: { opt: { type: 'string' } },
+ },
+ },
+ required: ['cfg'],
+ };
+ const snapshot = JSON.parse(JSON.stringify(input));
+
+ toStrictJsonSchema(input);
+
+ expect(input).toEqual(snapshot);
+ });
+
+ it('is idempotent for composed pipelines', () => {
+ const pipeline = (input: unknown): unknown =>
+ deduplicateJsonSchemaRequiredArrays(
+ toStrictJsonSchema(dereferenceJsonSchema(input, { onUnresolved: 'sentinel' })).schema
+ );
+
+ const once = pipeline({
+ type: 'object',
+ properties: {
+ cfg: {
+ $ref: '#/$defs/Config',
+ },
+ },
+ required: ['cfg'],
+ $defs: {
+ Config: {
+ type: 'object',
+ properties: { url: { type: 'string' }, note: { type: 'string' } },
+ required: ['url'],
+ },
+ },
+ });
+
+ expect(pipeline(once)).toEqual(once);
+ });
+
+ it('throws past the maximum nesting depth', () => {
+ let deep: Record<string, unknown> = { type: 'string' };
+ for (let i = 0; i < 600; i++) {
+ deep = { type: 'object', properties: { nest: deep }, required: ['nest'] };
+ }
+
+ expect(() => toStrictJsonSchema(deep)).toThrow(RangeError);
+ });
+});
diff --git a/ts/packages/providers/openai/src/OpenAIResponsesProvider.ts b/ts/packages/providers/openai/src/OpenAIResponsesProvider.ts
index b15e1a328..a2694142a 100644
--- a/ts/packages/providers/openai/src/OpenAIResponsesProvider.ts
+++ b/ts/packages/providers/openai/src/OpenAIResponsesProvider.ts
@@ -16,10 +16,12 @@ import {
ToolExecuteParams,
ExecuteToolModifiers,
ExecuteToolFnOptions,
- removeNonRequiredProperties,
McpUrlResponse,
normalizeToolArguments,
deduplicateJsonSchemaRequiredArrays,
+ dereferenceJsonSchema,
+ toStrictJsonSchema,
+ logger,
} from '@composio/core';
export type OpenAiTool = OpenAI.Responses.FunctionTool;
@@ -120,23 +122,32 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
* ```
*/
override wrapTool(tool: Tool): OpenAiTool {
- const inputParams = deduplicateJsonSchemaRequiredArrays(tool.inputParameters);
+ const inputParams = tool.inputParameters;
- const parameters =
- this.strict && inputParams?.type === 'object'
- ? removeNonRequiredProperties(
- inputParams as {
- type: 'object';
- properties: Record<string, unknown>;
- required?: string[];
- }
- )
- : (inputParams ?? {});
+ let parameters: Record<string, unknown> = (inputParams ?? {}) as Record<string, unknown>;
+ if (this.strict && inputParams?.type === 'object') {
+ // Structured outputs reject schemas whose nested objects keep optional
+ // properties or their own additionalProperties, so the strict contract
+ // must be applied at every depth. Inline $ref/$defs first (lenient mode
+ // keeps upstream schemas with dangling refs usable), then normalize.
+ const dereferenced = dereferenceJsonSchema(parameters, {
+ onUnresolved: 'sentinel',
+ onReplace: ref =>
+ logger.debug(
+ `OpenAIResponsesProvider: unresolved $ref "${ref}" in tool "${tool.slug}" replaced with a permissive schema`
+ ),
+ });
+ parameters = toStrictJsonSchema<Record<string, unknown>>(dereferenced).schema;
+ }
+
+ // Canonicalize required arrays at the vendor-schema emission boundary,
+ // after any provider-specific schema transformations.
+ const wrappedParameters = deduplicateJsonSchemaRequiredArrays(parameters);
return {
name: tool.slug,
description: tool.description,
- parameters,
+ parameters: wrappedParameters,
strict: this.strict,
type: 'function',
};
diff --git a/ts/packages/providers/openai/test/opeanai-responses.test.ts b/ts/packages/providers/openai/test/opeanai-responses.test.ts
index 63b1ab58e..05594cdfc 100644
--- a/ts/packages/providers/openai/test/opeanai-responses.test.ts
+++ b/ts/packages/providers/openai/test/opeanai-responses.test.ts
@@ -129,6 +129,110 @@ describe('OpenAIResponsesProvider', () => {
expect(wrapped.parameters.required).toEqual(['input']);
});
+
+ it('normalizes nested objects, nullable types and anyOf under strict mode', () => {
+ const strictProvider = new OpenAIResponsesProvider({ strict: true });
+ const wrapped = strictProvider.wrapTool({
+ ...mockTool,
+ inputParameters: {
+ type: 'object',
+ properties: {
+ cfg: {
+ type: 'object',
+ properties: {
+ url: { type: 'string' },
+ note: { type: 'string' },
+ },
+ required: ['url'],
+ },
+ id: { type: ['string', 'null'] },
+ payload: {
+ anyOf: [
+ {
+ type: 'object',
+ properties: { inner: { type: 'string' }, extra: { type: 'string' } },
+ required: ['inner'],
+ },
+ { type: 'null' },
+ ],
+ },
+ },
+ required: ['cfg', 'id', 'payload'],
+ },
+ }) as MockedOpenAITool;
+
+ expect(wrapped.parameters).toEqual({
+ type: 'object',
+ properties: {
+ cfg: {
+ type: 'object',
+ properties: { url: { type: 'string' } },
+ required: ['url'],
+ additionalProperties: false,
+ },
+ id: { anyOf: [{ type: 'string' }, { type: 'null' }] },
+ payload: {
+ anyOf: [
+ {
+ type: 'object',
+ properties: { inner: { type: 'string' } },
+ required: ['inner'],
+ additionalProperties: false,
+ },
+ { type: 'null' },
+ ],
+ },
+ },
+ required: ['cfg', 'id', 'payload'],
+ additionalProperties: false,
+ });
+ });
+
+ it('dereferences $defs before normalizing under strict mode', () => {
+ const strictProvider = new OpenAIResponsesProvider({ strict: true });
+ const wrapped = strictProvider.wrapTool({
+ ...mockTool,
+ inputParameters: {
+ type: 'object',
+ properties: {
+ cfg: { $ref: '#/$defs/Config' },
+ },
+ required: ['cfg'],
+ $defs: {
+ Config: {
+ type: 'object',
+ properties: { url: { type: 'string' }, opt: { type: 'string' } },
+ required: ['url'],
+ },
+ },
+ },
+ }) as MockedOpenAITool;
+
+ expect(JSON.stringify(wrapped.parameters)).not.toContain('$ref');
+ expect(wrapped.parameters).toEqual({
+ type: 'object',
+ properties: {
+ cfg: {
+ type: 'object',
+ properties: { url: { type: 'string' } },
+ required: ['url'],
+ additionalProperties: false,
+ },
+ },
+ required: ['cfg'],
+ additionalProperties: false,
+ });
+ });
+
+ it('leaves non-object schemas untouched in strict mode apart from required dedup', () => {
+ const strictProvider = new OpenAIResponsesProvider({ strict: true });
+ const wrapped = strictProvider.wrapTool({
+ ...mockTool,
+ inputParameters: undefined,
+ }) as MockedOpenAITool;
+
+ expect(wrapped.parameters).toEqual({});
+ });
});
describe('wrapTools', () => {
diff --git a/ts/packages/providers/vercel/src/index.ts b/ts/packages/providers/vercel/src/index.ts
index b6911ce9c..c0e7062f5 100644
--- a/ts/packages/providers/vercel/src/index.ts
+++ b/ts/packages/providers/vercel/src/index.ts
@@ -16,8 +16,11 @@ import {
ExecuteToolFn,
McpUrlResponse,
McpServerGetResponse,
- removeNonRequiredProperties,
+ deduplicateJsonSchemaRequiredArrays,
+ dereferenceJsonSchema,
+ toStrictJsonSchema,
jsonSchemaToZodSchema,
+ logger,
normalizeToolArguments,
} from '@composio/core';
import type { ToolSet as VercelToolSet, Tool as VercelTool } from 'ai';
@@ -109,18 +112,27 @@ export class VercelProvider extends BaseAgenticProvider<
wrapTool(composioTool: Tool, executeTool: ExecuteToolFn): VercelTool {
const inputParams = composioTool.inputParameters;
- const parameters =
- this.strict && inputParams?.type === 'object'
- ? removeNonRequiredProperties(
- inputParams as {
- type: 'object';
- properties: Record<string, unknown>;
- required?: string[];
- }
- )
- : (inputParams ?? {});
+ let parameters: Record<string, unknown> = (inputParams ?? {}) as Record<string, unknown>;
+ if (this.strict && inputParams?.type === 'object') {
+ // Structured outputs reject schemas whose nested objects keep optional
+ // properties or their own additionalProperties, so the strict contract
+ // must be applied at every depth. Inline $ref/$defs first (lenient mode
+ // keeps upstream schemas with dangling refs usable), then normalize.
+ const dereferenced = dereferenceJsonSchema(parameters, {
+ onUnresolved: 'sentinel',
+ onReplace: ref =>
+ logger.debug(
+ `VercelProvider: unresolved $ref "${ref}" in tool "${composioTool.slug}" replaced with a permissive schema`
+ ),
+ });
+ parameters = toStrictJsonSchema<Record<string, unknown>>(dereferenced).schema;
+ }
- const inputParametersSchema = jsonSchemaToZodSchema(parameters);
+ // Canonicalize required arrays at the vendor-schema emission boundary,
+ // after any provider-specific schema transformations.
+ const inputParametersSchema = jsonSchemaToZodSchema(
+ deduplicateJsonSchemaRequiredArrays(parameters)
+ );
return tool({
description: composioTool.description,
diff --git a/ts/packages/providers/vercel/test/vercel.test.ts b/ts/packages/providers/vercel/test/vercel.test.ts
index 4545aecf6..55478423e 100644
--- a/ts/packages/providers/vercel/test/vercel.test.ts
+++ b/ts/packages/providers/vercel/test/vercel.test.ts
@@ -133,6 +133,38 @@ describe('VercelProvider', () => {
expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
});
+
+ it('enforces the strict contract on complex schemas when strict mode is enabled', () => {
+ const strictProvider = new VercelProvider({ strict: true });
+ const wrapped = strictProvider.wrapTool(
+ {
+ ...mockTool,
+ inputParameters: {
+ type: 'object',
+ properties: {
+ cfg: {
+ type: 'object',
+ properties: { url: { type: 'string' }, note: { type: 'string' } },
+ required: ['url'],
+ },
+ id: { type: ['string', 'null'] },
+ },
+ required: ['cfg', 'id'],
+ },
+ },
+ mockExecuteToolFn
+ ) as unknown as MockedVercelTool;
+
+ const schema = wrapped.inputSchema as { safeParse: (value: unknown) => { success: boolean } };
+
+ // Nested required key present, nullable field null — valid.
+ expect(schema.safeParse({ cfg: { url: 'https://example.com' }, id: null }).success).toBe(
+ true
+ );
+ // Nested optional property was dropped under strict mode, so a value for
+ // it no longer parses.
+ expect(schema.safeParse({ cfg: { note: 'x' }, id: 'a' }).success).toBe(false);
+ });
});
describe('wrapTools', () => {