1
import ComposioClient, { APIError } from '@composio/client';
2
import { FileToolModifier } from '#file_tool_modifier';
3
+import { z } from 'zod/v3';
4
import {
5
Tool,
6
ToolExecuteParams,
47
ComposioToolFetchRateLimitError,
48
ComposioToolNotFoundError,
49
ComposioProviderNotDefinedError,
50
+ ComposioToolSchemaInvalidError,
51
ComposioToolVersionRequiredError,
52
} from '../errors/ToolErrors';
53
import { ValidationError } from '../errors/ValidationErrors';
83
| ToolRetrieveResponse['input_parameters']
84
| ComposioToolListResponse['items'][0]['input_parameters'];
85
86
+type JsonSchemaNode = Record<string, unknown>;
87
+
88
+const isSchemaRecord = (value: unknown): value is JsonSchemaNode =>
89
+ typeof value === 'object' && value !== null && !Array.isArray(value);
90
+
91
+/**
92
+ * Flatten a value for interpolation into a log line.
93
+ *
94
+ * The logger writes straight to the console sink, and the slug and the zod
95
+ * issue paths here are built from property names a remote toolkit controls. A
96
+ * name carrying a newline could otherwise forge or erase a line in the host's
97
+ * log, and an ANSI clear-line sequence could hide what came before it.
98
+ */
99
+const sanitizeForLog = (value: string): string =>
100
+ // eslint-disable-next-line no-control-regex
101
+ value.replace(/[\u0000-\u001F\u007F-\u009F]/g, ' ');
102
+
103
+/**
104
+ * Rewrite one JSON-Schema node into the strict subset `ParametersSchema`
105
+ * accepts, preserving its meaning:
106
+ *
107
+ * - boolean nodes (`items: true` / `items: false`) become `{}` / `{ not: {} }`
108
+ * — the strict subset's way to express "anything" and "nothing", so the
109
+ * meaning survives; booleans are still valid JSON Schema (draft-04 style)
110
+ * that MCP toolkits emit;
111
+ * - draft-04 boolean `exclusiveMinimum`/`exclusiveMaximum` (paired with
112
+ * `minimum`/`maximum`) become the numeric form draft-07+ uses;
113
+ *
114
+ * Children are rewritten recursively. `additionalProperties` legitimately
115
+ * accepts a boolean, so it is only recursed into when it is a schema.
116
+ */
117
+function sanitizeJsonSchemaNode(node: unknown): unknown {
118
+ // Boolean JSON-Schema nodes (draft-04 style, still emitted by MCP toolkits):
119
+ // `true` accepts anything, which `{}` also expresses; `false` accepts
120
+ // nothing, which the strict subset (an object node) expresses as `not: {}`.
121
+ // Coercing `false` to `{}` would invert the schema's meaning.
122
+ if (typeof node === 'boolean') return node ? {} : { not: {} };
123
+ if (Array.isArray(node)) return node.map(sanitizeJsonSchemaNode);
124
+ if (!isSchemaRecord(node)) return node;
125
+
126
+ const schema: JsonSchemaNode = { ...node };
127
+
128
+ for (const [bound, limit] of [
129
+ ['exclusiveMinimum', 'minimum'],
130
+ ['exclusiveMaximum', 'maximum'],
131
+ ] as const) {
132
+ if (typeof schema[bound] !== 'boolean') continue;
133
+ if (schema[bound] && typeof schema[limit] === 'number') {
134
+ schema[bound] = schema[limit];
135
+ } else {
136
+ delete schema[bound];
137
+ }
138
+ }
139
+
140
+ for (const key of ['items', 'not', 'if', 'then', 'else', 'additionalProperties'] as const) {
141
+ const child = schema[key];
142
+ if (child === undefined) continue;
143
+ // Every keyword here takes a schema node except `additionalProperties`,
144
+ // which also accepts a boolean; the sanitizer coerces boolean nodes.
145
+ if (key === 'additionalProperties' && typeof child === 'boolean') continue;
146
+ schema[key] = sanitizeJsonSchemaNode(child);
147
+ }
148
+
149
+ for (const key of ['anyOf', 'oneOf', 'allOf'] as const) {
150
+ if (Array.isArray(schema[key])) {
151
+ schema[key] = sanitizeJsonSchemaNode(schema[key]);
152
+ }
153
+ }
154
+
155
+ for (const key of ['properties', 'patternProperties', '$defs', 'definitions'] as const) {
156
+ const children = schema[key];
157
+ if (!isSchemaRecord(children)) continue;
158
+ const mapped: JsonSchemaNode = {};
159
+ for (const [name, child] of Object.entries(children)) {
160
+ mapped[name] = sanitizeJsonSchemaNode(child);
161
+ }
162
+ schema[key] = mapped;
163
+ }
164
+
165
+ return schema;
166
+}
167
+
168
/**
169
* Normalize a raw `input_parameters` / `output_parameters` payload returned by
170
* the Composio API. Maps `null`, `undefined`, and empty `{}` — all of which
171
* mean "no declared schema" — to `undefined` so the strict `ParametersSchema`
88
- * validator never sees them. Non-empty objects pass through unchanged and
89
- * remain subject to strict Zod validation.
172
+ * validator never sees them, and rewrites the valid-but-unusual JSON Schema
173
+ * shapes MCP toolkits ship (boolean nodes, draft-04 boolean bounds, a bare
174
+ * combinator root) into the strict subset.
175
*
176
* MCP-backed toolkits (granola_mcp, apify_mcp, tavily_mcp, …) have no
177
* declared output schema and the API serializes that as `{}`, which would
178
* otherwise trip `ParametersSchema`. See
94
- * https://github.com/ComposioHQ/composio/issues/3354.
179
+ * https://github.com/ComposioHQ/composio/issues/3354. The malformed-shape
180
+ * handling covers the toolkits listed in
181
+ * https://github.com/ComposioHQ/composio/issues/4757.
182
*/
183
function normalizeRawToolParameters(
184
params: RawToolParameters | null | undefined
185
): RawToolParameters | undefined {
186
if (params == null || Object.keys(params).length === 0) return undefined;
100
- return params;
187
+ const sanitized = sanitizeJsonSchemaNode(params);
188
+ // A parameters root is a tool's named-argument object, so a bare combinator
189
+ // root (`oneOf`/`anyOf`/`allOf` with no `type`) still needs `type: "object"`
190
+ // to satisfy the strict schema.
191
+ if (
192
+ isSchemaRecord(sanitized) &&
193
+ sanitized.type === undefined &&
194
+ (Array.isArray(sanitized.anyOf) ||
195
+ Array.isArray(sanitized.oneOf) ||
196
+ Array.isArray(sanitized.allOf))
197
+ ) {
198
+ return { ...sanitized, type: 'object' } as RawToolParameters;
199
+ }
200
+ return sanitized as RawToolParameters;
201
}
202
203
/** How long `execute()` reuses a schema fetched for `latest`, which can change at any release. */
232
* Scoped per-instance so a fresh `Composio` starts with a clean slate.
233
*/
234
private readonly warnedAutoUploadDisabledForTool = new Set<string>();
235
+ /** Tools whose parameters were dropped by `transformToolCases`; warn once each. */
236
+ private readonly warnedMalformedToolParametersSlugs = new Set<string>();
237
+
238
/**
239
* Schemas `execute()` already fetched, so repeated executions don't each spend a request.
240
* Holds what `getRawComposioToolBySlug` returned with no `modifySchema`, so a caller's schema
281
* making them more consistent with JavaScript/TypeScript conventions.
282
*
283
* @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool object to transform
181
- * @returns {Tool} The transformed tool with camelCase properties
284
+ * @returns {Tool} The transformed tool with camelCase properties, or
285
+ * `undefined` when its input schema is unrepairable and the tool is skipped
286
*
287
* @private
288
*/
289
private transformToolCases(
290
tool: ToolRetrieveResponse | ComposioToolListResponse['items'][0]
187
- ): Tool {
188
- return ToolSchema.parse({
291
+ ): Tool | undefined {
292
+ const candidate = {
293
...tool,
294
inputParameters: normalizeRawToolParameters(tool.input_parameters),
295
outputParameters: normalizeRawToolParameters(tool.output_parameters),
296
availableVersions: tool.available_versions,
297
isDeprecated: tool.deprecated?.is_deprecated ?? false,
298
isNoAuth: tool.no_auth,
195
- });
299
+ };
300
+
301
+ const parsed = ToolSchema.safeParse(candidate);
302
+ if (parsed.success) return parsed.data;
303
+
304
+ // One malformed schema must not take down a whole toolkit's tool list
305
+ // (#4757). The output side degrades to "no schema"; the input side cannot,
306
+ // because providers build their call schema from it and a tool without one
307
+ // is not callable — @composio/langchain's wrapTool throws
308
+ // "Tool input parameters are not defined", so an unrepairable input schema
309
+ // would fail the provider's whole wrapTools pass one layer later. Such a
310
+ // tool is skipped instead, with the same warning. A failure outside the
311
+ // parameters is genuinely broken data and stays loud — including alongside
312
+ // a parameter failure, where skipping the tool would otherwise hide it.
313
+ const failingSides = new Set<'inputParameters' | 'outputParameters'>();
314
+ let hasNonParameterIssue = false;
315
+ for (const issue of parsed.error.issues) {
316
+ const root = issue.path[0];
317
+ if (root === 'inputParameters' || root === 'outputParameters') {
318
+ failingSides.add(root);
319
+ } else {
320
+ hasNonParameterIssue = true;
321
+ }
322
+ }
323
+ if (hasNonParameterIssue || failingSides.size === 0) throw parsed.error;
324
+
325
+ this.warnMalformedToolParameters(tool, parsed.error, [...failingSides]);
326
+ if (failingSides.has('inputParameters')) return undefined;
327
+ const degradedCandidate = { ...candidate };
328
+ for (const side of failingSides) {
329
+ degradedCandidate[side] = undefined;
330
+ }
331
+ const degraded = ToolSchema.safeParse(degradedCandidate);
332
+ if (degraded.success) return degraded.data;
333
+ throw parsed.error;
334
+ }
335
+
336
+ /**
337
+ * Warn once per tool that its declared parameters could not be parsed and
338
+ * were dropped, so a caller sees why a tool carries no schema instead of a
339
+ * bare TypeError from deep inside Zod.
340
+ */
341
+ private warnMalformedToolParameters(
342
+ tool: ToolRetrieveResponse | ComposioToolListResponse['items'][0],
343
+ error: z.ZodError,
344
+ droppedSides: Array<'inputParameters' | 'outputParameters'>
345
+ ): void {
346
+ const slug = String((tool as { slug?: unknown }).slug ?? '');
347
+ if (slug && this.warnedMalformedToolParametersSlugs.has(slug)) return;
348
+ if (slug) this.warnedMalformedToolParametersSlugs.add(slug);
349
+ const inputFailed = droppedSides.includes('inputParameters');
350
+ logger.warn(
351
+ `Tool "${sanitizeForLog(slug) || '(unknown slug)'}" has ${droppedSides.join(' and ')} that do not ` +
352
+ `match the expected schema, so the tool was ` +
353
+ `${inputFailed ? 'skipped' : 'returned without those parameters'}. ` +
354
+ `${inputFailed ? 'It cannot be offered without an input schema.' : 'The tool still executes, but LLM callers will not see those parameters.'} ` +
355
+ `Issues: ${error.issues.map(issue => `${sanitizeForLog(issue.path.join('.'))}: ${sanitizeForLog(issue.message)}`).join('; ')}`
356
+ );
357
}
358
359
/**
716
if (!tools) {
717
return [];
718
}
558
- const caseTransformedTools = tools.items.map(tool => this.transformToolCases(tool));
719
+ const caseTransformedTools = tools.items
720
+ .map(tool => this.transformToolCases(tool))
721
+ .filter((tool): tool is Tool => tool !== undefined);
722
723
let modifiedTools = await this.applyDefaultSchemaModifiers(caseTransformedTools);
724
775
() => this.client.toolRouter.session.tools(sessionId, sessionToolsParams, requestOptions),
776
requestOptions?.signal
777
);
615
- tools.push(...response.items.map(tool => this.transformToolCases(tool)));
778
+ tools.push(
779
+ ...response.items
780
+ .map(tool => this.transformToolCases(tool))
781
+ .filter((tool): tool is Tool => tool !== undefined)
782
+ );
783
cursor = response.next_cursor;
784
} while (cursor);
785
897
}
898
899
// change the case of the tool to camel case and apply default modifiers
733
- let [modifiedTool] = await this.applyDefaultSchemaModifiers([this.transformToolCases(tool)]);
900
+ const transformedTool = this.transformToolCases(tool);
901
+ if (transformedTool === undefined) {
902
+ // The tool exists; its schema is what could not be parsed. Reporting that
903
+ // as TOOL_NOT_FOUND makes a caller that treats the code as "no such tool"
904
+ // hide a real one.
905
+ throw new ComposioToolSchemaInvalidError(
906
+ `Tool with slug ${slug} has an unusable input schema`,
907
+ { meta: { slug } }
908
+ );
909
+ }
910
+ let [modifiedTool] = await this.applyDefaultSchemaModifiers([transformedTool]);
911
// apply local modifiers if they are provided
912
if (options?.modifySchema) {
913
const modifier = options.modifySchema;