Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(openai): send tools strict mode cannot express without strict
jkomyno6a7ddbad0619
diff --git a/ts/packages/providers/openai/src/OpenAIResponsesProvider.ts b/ts/packages/providers/openai/src/OpenAIResponsesProvider.tsindex 954e6f982..ea540229f 100644--- a/ts/packages/providers/openai/src/OpenAIResponsesProvider.ts+++ b/ts/packages/providers/openai/src/OpenAIResponsesProvider.ts@@ -20,12 +20,20 @@ import {McpUrlResponse,normalizeToolArguments,deduplicateJsonSchemaRequiredArrays,- dereferenceJsonSchema,+ omitNullToolArguments,toStrictJsonSchema,logger,} from '@composio/core';export type OpenAiTool = OpenAI.Responses.FunctionTool;++/** Parameters emitted for a tool without input parameters under strict mode. */+const EMPTY_OBJECT_SCHEMA = {+ type: 'object',+ properties: {},+ required: [],+ additionalProperties: false,+} as const;export type OpenAiMcpTool = OpenAI.Responses.Tool.Mcp;export type OpenAiToolCollection = Array<OpenAiTool>;export type OpenAIResponsesProviderOptions = {@@ -46,6 +54,12 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<> {readonly name = 'openai';private strict: boolean | null;+ /**+ * Dereferenced parameter schemas of the tools wrapped under strict mode,+ * keyed by slug, so tool-call arguments can be reconciled against the+ * schema the model actually saw.+ */+ private readonly strictInputSchemas = new Map<string, Record<string, unknown>>();/*** Creates a new instance of the OpenAIProvider.@@ -124,32 +138,56 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<*/override wrapTool(tool: Tool): OpenAiTool {const inputParams = tool.inputParameters;-- 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;+ if (!this.strict) {+ return {+ name: tool.slug,+ description: tool.description,+ // Canonicalize required arrays at the vendor-schema emission boundary.+ parameters: deduplicateJsonSchemaRequiredArrays(+ (inputParams ?? {}) as Record<string, unknown>+ ),+ strict: this.strict,+ type: 'function',+ };}- // Canonicalize required arrays at the vendor-schema emission boundary,- // after any provider-specific schema transformations.- const wrappedParameters = deduplicateJsonSchemaRequiredArrays(parameters);+ // Structured outputs enforce their contract at every depth: all+ // properties required, closed objects, no annotation keywords. The strict+ // rewrite keeps every parameter (optional ones become nullable) and+ // reports constructs it cannot express; such a tool is sent without+ // strict mode rather than with a narrower schema.+ const source = (inputParams ?? EMPTY_OBJECT_SCHEMA) as Record<string, unknown>;+ const strict = toStrictJsonSchema(source);+ if (strict.unsupported.length > 0) {+ const reasons = strict.unsupported+ .map(entry => `${entry.path || '<root>'}: ${entry.keyword} (${entry.detail})`)+ .join('; ');+ logger.warn(+ `OpenAIResponsesProvider: tool "${tool.slug}" is sent without strict mode because its schema cannot be expressed as strict structured outputs: ${reasons}`+ );+ this.strictInputSchemas.delete(tool.slug);+ return {+ name: tool.slug,+ description: tool.description,+ parameters: deduplicateJsonSchemaRequiredArrays(source),+ strict: false,+ type: 'function',+ };+ }+ if (strict.totalChanges > 0) {+ logger.debug(+ `OpenAIResponsesProvider: strict mode rewrote ${strict.totalChanges} node(s) of tool "${tool.slug}": ${strict.changes+ .map(change => `${change.path}: ${change.reason}`)+ .join('; ')}`+ );+ }+ this.strictInputSchemas.set(tool.slug, strict.source);return {name: tool.slug,description: tool.description,- parameters: wrappedParameters,- strict: this.strict,+ parameters: strict.schema,+ strict: true,type: 'function',};}@@ -246,7 +284,13 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<): Promise<string> {// OpenAI always serializes tool arguments as a JSON string; normalize tolerates// empty / object-shaped payloads too (issue #2406).- const arguments_ = normalizeToolArguments(tool.arguments, tool.name);+ const normalizedArguments = normalizeToolArguments(tool.arguments, tool.name);+ // Under strict mode optional parameters are emitted as required-nullable,+ // so a `null` the tool's own schema does not accept means "omitted".+ const strictSchema = this.strictInputSchemas.get(tool.name);+ const arguments_ = strictSchema+ ? omitNullToolArguments(normalizedArguments, strictSchema)+ : normalizedArguments;const result = await this.executeToolForTarget(executionTarget,tool.name,diff --git a/ts/packages/providers/openai/test/opeanai-responses.test.ts b/ts/packages/providers/openai/test/opeanai-responses.test.tsindex cb917eb60..0a9ee83d8 100644--- a/ts/packages/providers/openai/test/opeanai-responses.test.ts+++ b/ts/packages/providers/openai/test/opeanai-responses.test.ts@@ -130,7 +130,7 @@ describe('OpenAIResponsesProvider', () => {expect(wrapped.parameters.required).toEqual(['input']);});- it('normalizes nested objects, nullable types and anyOf under strict mode', () => {+ it('keeps optional parameters as required-nullable under strict mode', () => {const strictProvider = new OpenAIResponsesProvider({ strict: true });const wrapped = strictProvider.wrapTool({...mockTool,@@ -156,39 +156,42 @@ describe('OpenAIResponsesProvider', () => {{ type: 'null' },],},+ label: { type: 'string', default: 'x' },},required: ['cfg', 'id', 'payload'],},}) as MockedOpenAITool;+ expect(wrapped.strict).toBe(true);expect(wrapped.parameters).toEqual({type: 'object',properties: {cfg: {type: 'object',- properties: { url: { type: 'string' } },- required: ['url'],+ properties: { url: { type: 'string' }, note: { type: ['string', 'null'] } },+ required: ['url', 'note'],additionalProperties: false,},- id: { anyOf: [{ type: 'string' }, { type: 'null' }] },+ id: { type: ['string', 'null'] },payload: {anyOf: [{type: 'object',- properties: { inner: { type: 'string' } },- required: ['inner'],+ properties: { inner: { type: 'string' }, extra: { type: ['string', 'null'] } },+ required: ['inner', 'extra'],additionalProperties: false,},{ type: 'null' },],},+ label: { type: ['string', 'null'] },},- required: ['cfg', 'id', 'payload'],+ required: ['cfg', 'id', 'payload', 'label'],additionalProperties: false,});});- it('dereferences $defs before normalizing under strict mode', () => {+ it('keeps nullable nested objects nullable and inlines $defs under strict mode', () => {const strictProvider = new OpenAIResponsesProvider({ strict: true });const wrapped = strictProvider.wrapTool({...mockTool,@@ -200,7 +203,7 @@ describe('OpenAIResponsesProvider', () => {required: ['cfg'],$defs: {Config: {- type: 'object',+ type: ['object', 'null'],properties: { url: { type: 'string' }, opt: { type: 'string' } },required: ['url'],},@@ -209,13 +212,14 @@ 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: {- type: 'object',- properties: { url: { type: 'string' } },- required: ['url'],+ type: ['object', 'null'],+ properties: { url: { type: 'string' }, opt: { type: ['string', 'null'] } },+ required: ['url', 'opt'],additionalProperties: false,},},@@ -224,14 +228,36 @@ describe('OpenAIResponsesProvider', () => {});});- it('leaves non-object schemas untouched in strict mode apart from required dedup', () => {+ it('sends tools strict mode cannot express without strict, keeping their schema', () => {+ const strictProvider = new OpenAIResponsesProvider({ strict: true });+ const inputParameters = {+ type: 'object',+ properties: {+ headers: { type: 'object', additionalProperties: { type: 'string' } },+ name: { type: 'string' },+ },+ required: ['headers', 'name', 'name'],+ };+ const wrapped = strictProvider.wrapTool({ ...mockTool, inputParameters }) as MockedOpenAITool;++ expect(wrapped.strict).toBe(false);+ expect(wrapped.parameters).toEqual({ ...inputParameters, required: ['headers', 'name'] });+ });++ it('emits an empty closed object for tools without parameters in strict mode', () => {const strictProvider = new OpenAIResponsesProvider({ strict: true });const wrapped = strictProvider.wrapTool({...mockTool,inputParameters: undefined,}) as MockedOpenAITool;- expect(wrapped.parameters).toEqual({});+ expect(wrapped.strict).toBe(true);+ expect(wrapped.parameters).toEqual({+ type: 'object',+ properties: {},+ required: [],+ additionalProperties: false,+ });});});@@ -301,6 +327,48 @@ describe('OpenAIResponsesProvider', () => {);});+ it('omits nulls the tool schema does not accept before executing under strict mode', async () => {+ const strictProvider = new OpenAIResponsesProvider({ strict: true });+ strictProvider._setExecuteToolFn(mockExecuteToolFn);+ strictProvider.wrapTool({+ ...mockTool,+ slug: 'test-tool',+ inputParameters: {+ type: 'object',+ properties: {+ cfg: {+ type: 'object',+ properties: { url: { type: 'string' }, note: { type: 'string' } },+ required: ['url'],+ },+ label: { type: 'string' },+ clearable: { type: ['string', 'null'] },+ },+ required: ['cfg'],+ },+ });+ const toolCall = {+ id: 'call-123',+ type: 'function',+ name: 'test-tool',+ arguments: JSON.stringify({ cfg: { url: 'u', note: null }, label: null, clearable: null }),+ call_id: 'call-123',+ } as unknown as OpenAI.Responses.ResponseFunctionToolCall;++ await strictProvider.executeToolCall('test-user', toolCall);++ expect(mockExecuteToolFn).toHaveBeenCalledWith(+ 'test-tool',+ {+ arguments: { cfg: { url: 'u' }, clearable: null },+ userId: 'test-user',+ connectedAccountId: undefined,+ customAuthParams: undefined,+ },+ undefined+ );+ });+it('should coerce empty-string arguments to an empty object (issue #2406)', async () => {const toolCall = {id: 'call-123',