@devries-cameron20 / composio Mirror · read-only / commits / 6aa3f31ec
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, 04:45 UTC

fix(core): tolerate malformed tool schemas instead of failing the whole call (#4780)

## Related issue Closes #4757 ## Summary `transformToolCases` ran every tool's parameters through `ToolSchema.parse`, so one tool with a schema shape the strict validator rejects took down the entire `getRawComposioTools` call — 8 of 1562 toolkits ship such tools and currently return nothing: - boolean JSON-Schema nodes (`items: true`, draft-04 style, still emitted by MCP toolkits), which the object-only property schema rejects - draft-04 boolean `exclusiveMinimum` / `exclusiveMaximum`, paired with `minimum` / `maximum` - a bare combinator root (`oneOf` / `anyOf` / `allOf` with no `type: "object"`) ## Fix — two layers, so no schema shape can throw a whole batch **1. Repair what is repairable.** `normalizeRawToolParameters` (the same normalizer that already handled empty schemas for #3354) now rewrites the malformed-but-valid shapes into the strict subset, preserving meaning: - boolean nodes become `{}` — both accept anything - draft-04 boolean bounds become their numeric form (`minimum: 5, exclusiveMinimum: true` → `exclusiveMinimum: 5`) - a combinator root gains `type: "object"` — a tool's parameter root is always its named-argument object **2. Degrade per tool instead of per batch.** `transformToolCases` now `safeParse`s; if a schema still fails, it drops only the parameter side that failed (input and output degrade independently), warns once per tool, and returns the tool. A failure outside the parameters — a missing slug, say — is genuinely broken data and stays loud. The issue asks for "tools returned, non-conforming per-tool schemas tolerated or skipped": layer 1 tolerates, layer 2 skips. ## Test Plan `pnpm --filter @composio/core exec vitest run test/tools/tools.test.ts` - **102 passed** (97 existing + 5 new) - With only the source fix reverted and the new tests kept: **5 failed / 97 passed** — the new cases fail with `ZodError`, confirming they pin the reported behaviour - `tsc --noEmit`: clean; `oxlint` on both changed files: 0 warnings, 0 errors New cases (in the existing `getRawComposioTools` block, using the repo's mock style): a boolean schema node, a draft-04 boolean bound, a bare combinator root, a batch where one tool is malformed and the rest still return, and a tool whose schema cannot be repaired (kept, minus its parameters). ## Notes - Local verification ran the repo suite against the sibling `@composio/json-schema-to-zod` package's source entry: its `tsdown` build fails on this Windows machine for reasons unrelated to this change. No repo files outside the two above were touched. Co-authored-by: insuffer <insuffer@users.noreply.github.com>

Cabeza committed Nov 13, 2026 at 22:36 UTC 6aa3f31ecf38fc5f9ea10d67e31a43ede2e2c693
4 files changed +466 -12
.changeset/tolerate-malformed-tool-schemas.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': patch
3 +---
4 +
5 +Tolerate malformed tool schemas instead of failing a whole toolkit's tool list. `getRawComposioTools` and the raw list path previously ran every tool's parameters through the strict schema validator with `parse`, so one tool whose schema used a valid-but-unusual JSON Schema shape — a boolean schema node (`items: true`, still emitted by MCP toolkits), a draft-04 boolean `exclusiveMinimum`/`exclusiveMaximum`, or a bare combinator root with no `type: "object"` — threw a `ZodError` and returned no tools at all for that toolkit (8 of 1562 toolkits ship such tools). Those shapes are now rewritten into the strict subset, preserving their meaning (`true` becomes `{}`, `false` becomes `{ not: {} }` — coercing it to `{}` would invert the schema). If a schema still cannot be repaired, the tool is skipped with a warning when its *input* schema failed — providers build their call schema from it, so a tool without one is not callable — and returned without the *output* schema when only that side failed. Identity-field failures stay loud.
\ No newline at end of file
ts/packages/core/src/errors/ToolErrors.ts
+25
@@ -7,6 +7,7 @@ export const ToolErrorCodes = {
7 TOOLSET_NOT_DEFINED: 'TOOLSET_NOT_DEFINED',
8 TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',
9 TOOL_FETCH_ERROR: 'TOOL_FETCH_ERROR',
10 + TOOL_SCHEMA_INVALID: 'TOOL_SCHEMA_INVALID',
11 INVALID_MODIFIER: 'INVALID_MODIFIER',
12 TOOL_EXECUTION_ERROR: 'TOOL_EXECUTION_ERROR',
13 INVALID_TOOL_ARGUMENTS: 'INVALID_TOOL_ARGUMENTS',
@@ -70,6 +71,30 @@ export class ComposioToolFetchError extends ComposioError {
71 }
72 }
73
74 +/**
75 + * Error thrown when a tool was retrieved but its declared parameters cannot be
76 + * parsed, so the tool cannot be offered. Distinct from
77 + * `ComposioToolNotFoundError`: the tool exists, its schema is what is broken,
78 + * and a caller that treats `TOOL_NOT_FOUND` as "no such tool" would otherwise
79 + * report a real tool as missing.
80 + */
81 +export class ComposioToolSchemaInvalidError extends ComposioError {
82 + constructor(
83 + message: string = 'Tool schema is invalid',
84 + options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
85 + ) {
86 + super(message, {
87 + ...options,
88 + code: ToolErrorCodes.TOOL_SCHEMA_INVALID,
89 + possibleFixes: options.possibleFixes || [
90 + 'The tool exists but its declared input schema could not be parsed',
91 + 'Report the tool slug to Composio so the schema can be corrected',
92 + ],
93 + });
94 + this.name = 'ComposioToolSchemaInvalidError';
95 + }
96 +}
97 +
98 /** Error options for a 429. Leaves out an unknown wait, as `ComposioError` does for unset fields. */
99 const rateLimitOptions = (cause: APIError, meta: Record<string, unknown>) => {
100 const retryAfterSeconds = getRetryAfterSeconds(cause);
ts/packages/core/src/models/Tools.ts
+188 -11
@@ -1,5 +1,6 @@
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,
@@ -46,6 +47,7 @@ import {
47 ComposioToolFetchRateLimitError,
48 ComposioToolNotFoundError,
49 ComposioProviderNotDefinedError,
50 + ComposioToolSchemaInvalidError,
51 ComposioToolVersionRequiredError,
52 } from '../errors/ToolErrors';
53 import { ValidationError } from '../errors/ValidationErrors';
@@ -81,23 +83,121 @@ type RawToolParameters =
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. */
@@ -132,6 +232,9 @@ export class Tools<
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
@@ -178,21 +281,79 @@ export class Tools<
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 /**
@@ -555,7 +716,9 @@ export class Tools<
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
@@ -612,7 +775,11 @@ export class Tools<
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
@@ -730,7 +897,17 @@ export class Tools<
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;
ts/packages/core/test/tools/tools.test.ts
+248 -1
@@ -13,7 +13,12 @@ import {
13 } from '../utils/toolExecuteUtils';
14 import { MockProvider } from '../utils/mocks/provider.mock';
15 import { ValidationError } from '../../src/errors/ValidationErrors';
16 -import { ComposioToolFetchError, ComposioToolNotFoundError } from '../../src/errors/ToolErrors';
16 +import {
17 + ComposioToolFetchError,
18 + ComposioToolNotFoundError,
19 + ComposioToolSchemaInvalidError,
20 +} from '../../src/errors/ToolErrors';
21 +import logger from '../../src/utils/logger';
22
23 // Minimal structural shape for a ComposioError-like value (possibly wrapping
24 // another error as its `cause`), used to narrow `catch (error: unknown)`
@@ -384,6 +389,230 @@ describe('Tools', () => {
389
390 await expect(context.tools.getRawComposioTools(emptyQuery)).rejects.toThrow(ValidationError);
391 });
392 +
393 + // One tool's malformed schema used to fail the whole call (#4757).
394 + it('should tolerate a tool whose inputParameters holds a boolean schema node', async () => {
395 + mockClient.tools.list.mockResolvedValueOnce({
396 + items: [
397 + {
398 + ...toolMocks.rawTool,
399 + input_parameters: {
400 + type: 'object',
401 + properties: {
402 + params: { type: 'object', items: true },
403 + },
404 + },
405 + },
406 + ],
407 + totalPages: 1,
408 + });
409 +
410 + const result = await context.tools.getRawComposioTools({ tools: ['COMPOSIO_TOOL'] });
411 +
412 + expect(result).toHaveLength(1);
413 + expect(result[0].inputParameters).toEqual({
414 + type: 'object',
415 + properties: {
416 + params: { type: 'object', items: {} },
417 + },
418 + });
419 + });
420 +
421 + it('should express a false boolean node as not-anything, not anything', async () => {
422 + mockClient.tools.list.mockResolvedValueOnce({
423 + items: [
424 + {
425 + ...toolMocks.rawTool,
426 + input_parameters: {
427 + type: 'object',
428 + properties: {
429 + // `false` accepts nothing; coercing it to `{}` would invert
430 + // the rule and accept everything.
431 + forbidden: { type: 'array', items: false },
432 + anything: { type: 'array', items: true },
433 + },
434 + },
435 + },
436 + ],
437 + totalPages: 1,
438 + });
439 +
440 + const result = await context.tools.getRawComposioTools({ tools: ['COMPOSIO_TOOL'] });
441 +
442 + expect(result).toHaveLength(1);
443 + expect(result[0].inputParameters).toEqual({
444 + type: 'object',
445 + properties: {
446 + forbidden: { type: 'array', items: { not: {} } },
447 + anything: { type: 'array', items: {} },
448 + },
449 + });
450 + });
451 +
452 + it('should tolerate a draft-04 boolean exclusiveMinimum', async () => {
453 + mockClient.tools.list.mockResolvedValueOnce({
454 + items: [
455 + {
456 + ...toolMocks.rawTool,
457 + input_parameters: {
458 + type: 'object',
459 + properties: {
460 + amount: { type: 'number', minimum: 5, exclusiveMinimum: true },
461 + },
462 + },
463 + },
464 + ],
465 + totalPages: 1,
466 + });
467 +
468 + const result = await context.tools.getRawComposioTools({ tools: ['COMPOSIO_TOOL'] });
469 +
470 + expect(result).toHaveLength(1);
471 + expect(result[0].inputParameters).toEqual({
472 + type: 'object',
473 + properties: {
474 + amount: { type: 'number', minimum: 5, exclusiveMinimum: 5 },
475 + },
476 + });
477 + });
478 +
479 + it('should tolerate a bare combinator root without a type', async () => {
480 + mockClient.tools.list.mockResolvedValueOnce({
481 + items: [
482 + {
483 + ...toolMocks.rawTool,
484 + input_parameters: {
485 + oneOf: [{ type: 'object', properties: { a: { type: 'string' } } }],
486 + },
487 + },
488 + ],
489 + totalPages: 1,
490 + });
491 +
492 + const result = await context.tools.getRawComposioTools({ tools: ['COMPOSIO_TOOL'] });
493 +
494 + expect(result).toHaveLength(1);
495 + expect(result[0].inputParameters).toEqual({
496 + type: 'object',
497 + oneOf: [{ type: 'object', properties: { a: { type: 'string' } } }],
498 + });
499 + });
500 +
501 + it('should return the conforming tools of a batch when one schema is malformed', async () => {
502 + mockClient.tools.list.mockResolvedValueOnce({
503 + items: [
504 + toolMocks.rawTool,
505 + {
506 + ...toolMocks.customTool,
507 + input_parameters: {
508 + type: 'object',
509 + properties: { filters: { type: 'array', items: true } },
510 + },
511 + },
512 + ],
513 + totalPages: 1,
514 + });
515 +
516 + const result = await context.tools.getRawComposioTools({ toolkits: ['test-toolkit'] });
517 +
518 + expect(result.map(tool => tool.slug)).toEqual(['COMPOSIO_TOOL', 'CUSTOM_TOOL']);
519 + });
520 +
521 + it('should keep a tool whose output schema cannot be repaired, minus that schema', async () => {
522 + mockClient.tools.list.mockResolvedValueOnce({
523 + items: [
524 + {
525 + ...toolMocks.rawTool,
526 + output_parameters: {
527 + type: 'object',
528 + properties: { query: { type: 'not-a-json-schema-type' } },
529 + },
530 + },
531 + ],
532 + totalPages: 1,
533 + });
534 +
535 + const result = await context.tools.getRawComposioTools({ tools: ['COMPOSIO_TOOL'] });
536 +
537 + expect(result).toHaveLength(1);
538 + expect(result[0].slug).toEqual('COMPOSIO_TOOL');
539 + expect(result[0].outputParameters).toBeUndefined();
540 + expect(result[0].inputParameters).toBeDefined();
541 + });
542 +
543 + it('should skip a tool whose input schema cannot be repaired', async () => {
544 + // An unrepairable input schema cannot degrade to "no schema": providers
545 + // build their call schema from it (@composio/langchain's wrapTool throws
546 + // "Tool input parameters are not defined"), so the tool is skipped and
547 + // the rest of the batch still returns.
548 + mockClient.tools.list.mockResolvedValueOnce({
549 + items: [
550 + toolMocks.rawTool,
551 + {
552 + ...toolMocks.customTool,
553 + input_parameters: {
554 + type: 'object',
555 + properties: { query: { type: 'not-a-json-schema-type' } },
556 + },
557 + },
558 + ],
559 + totalPages: 1,
560 + });
561 +
562 + const result = await context.tools.getRawComposioTools({ toolkits: ['test-toolkit'] });
563 +
564 + expect(result.map(tool => tool.slug)).toEqual(['COMPOSIO_TOOL']);
565 + });
566 +
567 + it('should still throw for a broken identity when a schema is also malformed', async () => {
568 + // Skipping the tool must not swallow a failure that is not about the
569 + // parameters: a tool with no name is broken data either way.
570 + mockClient.tools.list.mockResolvedValueOnce({
571 + items: [
572 + {
573 + ...toolMocks.rawTool,
574 + name: undefined as unknown as string,
575 + input_parameters: {
576 + type: 'object',
577 + properties: { query: { type: 'not-a-json-schema-type' } },
578 + },
579 + },
580 + ],
581 + totalPages: 1,
582 + });
583 +
584 + await expect(
585 + context.tools.getRawComposioTools({ toolkits: ['test-toolkit'] })
586 + ).rejects.toThrow();
587 + });
588 +
589 + it('should not let a schema property name forge lines in the warning', async () => {
590 + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => undefined);
591 + mockClient.tools.list.mockResolvedValueOnce({
592 + items: [
593 + {
594 + ...toolMocks.customTool,
595 + slug: 'FORGERY_TOOL',
596 + input_parameters: {
597 + type: 'object',
598 + properties: {
599 + 'evil\n[ERROR] security scan passed': { type: 'not-a-json-schema-type' },
600 + },
601 + },
602 + },
603 + ],
604 + totalPages: 1,
605 + });
606 +
607 + await context.tools.getRawComposioTools({ toolkits: ['test-toolkit'] });
608 +
609 + expect(warn).toHaveBeenCalledTimes(1);
610 + const message = String(warn.mock.calls[0][0]);
611 + // The forged line must not appear as its own line.
612 + expect(message.split('\n')).toHaveLength(1);
613 + expect(message).not.toContain('\n[ERROR]');
614 + warn.mockRestore();
615 + });
616 });
617
618 describe('getRawToolRouterSessionTools', () => {
@@ -442,6 +671,24 @@ describe('Tools', () => {
671 });
672
673 describe('getRawComposioToolBySlug', () => {
674 + it('should report an unusable schema as a schema error, not a missing tool', async () => {
675 + // The tool exists; only its schema is broken. Callers that catch
676 + // TOOL_NOT_FOUND would otherwise hide a real tool as missing.
677 + const slug = 'SCHEMA_BROKEN_TOOL';
678 + mockClient.tools.retrieve.mockResolvedValueOnce({
679 + ...toolMocks.customTool,
680 + slug,
681 + input_parameters: {
682 + type: 'object',
683 + properties: { query: { type: 'not-a-json-schema-type' } },
684 + },
685 + });
686 +
687 + await expect(context.tools.getRawComposioToolBySlug(slug)).rejects.toThrow(
688 + ComposioToolSchemaInvalidError
689 + );
690 + });
691 +
692 it('should fetch a tool by slug from the API', async () => {
693 const slug = 'TOOL_SLUG';
694