@devries-cameron20 / composio Mirror · read-only / commits / be9218958
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): surface API error details from `tools.execute` (#5413)

This PR: - surfaces the API's error details on `tools.execute` failures: the message keeps the tool slug and appends the server's `error.message`, and `possibleFixes` becomes `[suggested_fix]` when the API sent one - falls back to a status-specific fix otherwise; 401, 402, 403, 410 and 5xx no longer suggest "check the tool slug and arguments" - declares `statusCode` and `requestId` publicly on `ComposioError`, derived from an `APIError` cause unless passed explicitly (explicit wins), replacing the old `BadRequestError`-only status derivation - adds `apiErrorCode` to `ComposioToolExecutionError` for the numeric API code; `.code` stays `TS-SDK::TOOL_EXECUTION_ERROR` - keeps `cause` on the 1803 `ComposioConnectedAccountNotFoundError` branch; its hardcoded 404 is unchanged - reads the client's validated `APIError.details` (`@composio/client` 2.1.32) instead of casting `APIError.error`; `ComposioAPIServerErrorBody` is now an alias of the client's `APIErrorBody`, where `request_id` and `suggested_fix` are optional - fixes `error-consistency.md` (`originalError` → `cause`) and `advanced/error-handling.md` (`error.context.toolSlug` → the real fields) ## Context The public surface change is additive: new optional fields and one new exported options type. `ComposioAPIServerErrorBody` was public through `export *`, so this PR keeps the name as an alias rather than deleting it. Its `request_id` and `suggested_fix` are now `string | undefined`, which is what the API actually sends. Python is out of scope. Commands run from the repository root, all on the final head: - `pnpm build:packages`: passed (19/19 tasks) - `pnpm typecheck`: passed (14/14 tasks) - `pnpm test`: every turbo test task passed (26/26). The final `test:examples` step failed locally because of four untracked leftover directories in my checkout (`ts/examples/{cjs,cloudflare-ai,custom-tools,livekit}`, holding only `.env`/`node_modules`). Rerunning `tsx ts/scripts/validate-examples.ts` in a clean worktree at this head passed: "Validated 22 example packages." - `pnpm --filter @composio/core exec vitest run test/tools/executeSchemaCache.test.ts`: 22 passed. With the old `handleToolExecutionError` restored, the 7 new wrapper tests fail. - `pnpm exec prettier --check` on the changed files: passed

Alberto Schiabel committed Nov 16, 2026 at 23:42 UTC be92189585bf51b67e27a51c2725dc38993b0360
6 files changed +228 -43
.changeset/tool-execution-error-details.md new
+19
@@ -0,0 +1,19 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Surface the API's error details when `tools.execute` fails. `ComposioError` now declares `statusCode` and `requestId`, read from the `@composio/client` `APIError` it wraps unless passed explicitly, and `ComposioToolExecutionError` adds `apiErrorCode`, the numeric `error.code` the API sent. `code` stays the SDK's `TS-SDK::` code. Branch on `error.statusCode` (for example `410`) instead of matching message text.
6 +
7 +**Behavior change:** a rejected execution's message now ends with the server's message, and its `possibleFixes` come from the server's `suggested_fix`.
8 +
9 +```ts
10 +// before
11 +error.message; // 'Error executing the tool GITHUB_GET_REPOS'
12 +error.possibleFixes; // ['Ensure the tool slug is correct and the input arguments for the tool is valid']
13 +
14 +// now
15 +error.message; // 'Error executing the tool GITHUB_GET_REPOS: <the API error message>'
16 +error.possibleFixes; // ['<the API suggested_fix>']
17 +```
18 +
19 +Without a `suggested_fix`, the fix depends on the HTTP status: a 401, 402, 403, 410 or 5xx no longer suggests checking the tool slug and arguments. A response that is not the API error envelope keeps the old message. `ComposioConnectedAccountNotFoundError` (API code 1803) now keeps the client error as `cause`, and errors that wrap an `APIError` cause, such as `ComposioToolFetchError`, now carry its `statusCode` and `requestId`. `ComposioAPIServerErrorBody` is now the client's `APIErrorBody`, where `request_id` and `suggested_fix` are optional, as the API sends them.
ts/docs/advanced/error-handling.md
+6 -2
@@ -48,9 +48,13 @@ try {
48 });
49 } catch (error) {
50 if (error instanceof ComposioToolExecutionError) {
51 + // The message names the tool and ends with the API's own message, when it sent one
52 console.error('Tool execution error:', error.message);
52 - console.error('Tool:', error.context.toolSlug);
53 - console.error('Execution params:', error.context.body);
53 + console.error('HTTP status:', error.statusCode); // e.g. 403, 410
54 + console.error('API error code:', error.apiErrorCode);
55 + console.error('Request id:', error.requestId);
56 + console.error('Try:', error.possibleFixes);
57 + console.error('Client error:', error.cause);
58 }
59 }
60 ```
ts/packages/core/docs/error-consistency.md
+3 -3
@@ -44,9 +44,9 @@ Some error classes have specific requirements:
44 new ValidationError('Message', { cause: someZodError });
45 ```
46
47 -2. **ComposioToolExecutionError**: Accepts an `originalError` in the options.
47 +2. **ComposioToolExecutionError**: Keeps the failure it wraps as `cause`, and accepts an `apiErrorCode` for the numeric code of a Composio API error response.
48 ```typescript
49 - new ComposioToolExecutionError('Message', { originalError: someError });
49 + new ComposioToolExecutionError('Message', { cause: someError });
50 ```
51
52 ## Using Error Classes
@@ -72,7 +72,7 @@ try {
72 } catch (error) {
73 // Handle tool execution errors
74 throw new ComposioToolExecutionError('Tool failed', {
75 - originalError: error,
75 + cause: error,
76 meta: { toolId: 'some-tool' },
77 });
78
ts/packages/core/src/errors/ComposioError.ts
+13 -6
@@ -10,7 +10,7 @@
10 */
11 import pc from 'picocolors';
12 import { ZodError } from 'zod/v3';
13 -import { BadRequestError } from '@composio/client';
13 +import { APIError } from '@composio/client';
14 import logger from '../utils/logger';
15
16 /**
@@ -31,8 +31,10 @@ export interface ErrorHandleOptions {
31 export type ComposioErrorOptions = {
32 /** Error code for categorizing errors */
33 code?: string;
34 - /** HTTP status code associated with the error */
34 + /** HTTP status code associated with the error. Defaults to the status of an `APIError` cause. */
35 statusCode?: number;
36 + /** Request id the API assigned. Defaults to the request id of an `APIError` cause. */
37 + requestId?: string;
38 /** The underlying cause of the error */
39 cause?: unknown;
40 /** Additional metadata associated with the error */
@@ -67,6 +69,10 @@ export class ComposioError extends Error {
69 public code?: string;
70 public possibleFixes?: string[];
71 public errorId?: string;
72 + /** HTTP status of the response behind the error, when there was one. */
73 + declare public readonly statusCode?: number;
74 + /** Request id the Composio API assigned to the request behind the error, when it sent one. */
75 + declare public readonly requestId?: string;
76
77 /**
78 * Creates a new ComposioError
@@ -81,10 +87,10 @@ export class ComposioError extends Error {
87 Error.captureStackTrace(this, this.constructor);
88 }
89
84 - // Process the status code - either from options or from the cause if it's a BadRequestError
85 - const statusCode =
86 - options.statusCode ||
87 - (options.cause instanceof BadRequestError ? options.cause.status : undefined);
90 + // Transport metadata: explicit options win, otherwise read it from an API error cause
91 + const apiCause = options.cause instanceof APIError ? options.cause : undefined;
92 + const statusCode = options.statusCode ?? apiCause?.status;
93 + const requestId = options.requestId ?? apiCause?.requestId;
94
95 this.code = `TS-SDK::${options.code}`;
96 // format the possible fixes
@@ -93,6 +99,7 @@ export class ComposioError extends Error {
99 // Only define properties that have values to avoid showing undefined in error display
100 // Node.js by default shows all the properties of the error object, so we are doing it conditionally
101 this.definePropertyIfExists('statusCode', statusCode);
102 + this.definePropertyIfExists('requestId', requestId);
103 this.definePropertyIfExists('cause', options.cause);
104
105 const combinedStack =
ts/packages/core/src/errors/ToolErrors.ts
+71 -31
@@ -1,4 +1,4 @@
1 -import { APIError } from '@composio/client';
1 +import { APIError, type APIErrorBody } from '@composio/client';
2 import { ComposioError, ComposioErrorOptions } from './ComposioError';
3 import { ComposioConnectedAccountNotFoundError } from './ConnectedAccountsErrors';
4 import { getRetryAfterSeconds, isRateLimitResponse } from '../utils/rateLimit';
@@ -146,17 +146,36 @@ export class ComposioInvalidModifierError extends ComposioError {
146 }
147 }
148
149 +/** Options for a `ComposioToolExecutionError`. */
150 +export type ComposioToolExecutionErrorOptions = ComposioErrorOptions & {
151 + /** The numeric `error.code` of the Composio API error response. */
152 + apiErrorCode?: number;
153 +};
154 +
155 export class ComposioToolExecutionError extends ComposioError {
150 - constructor(message: string = 'Tool execution error', options: ComposioErrorOptions = {}) {
156 + /**
157 + * The numeric `error.code` the Composio API sent when it rejected the execution.
158 + * `code` stays the SDK's `TS-SDK::` code.
159 + */
160 + declare public readonly apiErrorCode?: number;
161 +
162 + constructor(
163 + message: string = 'Tool execution error',
164 + options: ComposioToolExecutionErrorOptions = {}
165 + ) {
166 + const { apiErrorCode, ...errorOptions } = options;
167 super(message, {
152 - ...options,
153 - code: options.code || ToolErrorCodes.TOOL_EXECUTION_ERROR,
154 - cause: options.cause,
155 - possibleFixes: options.possibleFixes || [
168 + ...errorOptions,
169 + code: errorOptions.code || ToolErrorCodes.TOOL_EXECUTION_ERROR,
170 + cause: errorOptions.cause,
171 + possibleFixes: errorOptions.possibleFixes || [
172 'Ensure the tool is correctly configured and the input is valid',
173 'Ensure the userId is correct and has an active connected account for the user in case of non NoAuth toolkits',
174 ],
175 });
176 + if (apiErrorCode !== undefined) {
177 + this.apiErrorCode = apiErrorCode;
178 + }
179
180 this.name = 'ComposioToolExecutionError';
181 }
@@ -320,32 +339,45 @@ export class ComposioToolVersionRequiredError extends ComposioError {
339 this.name = 'ComposioToolVersionRequiredError';
340 }
341 }
323 -export interface ComposioAPIServerErrorBody {
324 - error: {
325 - message: string;
326 - code: number;
327 - status: number;
328 - request_id: string;
329 - suggested_fix: string;
330 - };
331 -}
342 +/** The error envelope of a Composio API error response, as `@composio/client` validates it. */
343 +export type ComposioAPIServerErrorBody = APIErrorBody;
344
345 // Map of error codes to their corresponding error constructors
334 -const ERROR_CODE_HANDLERS = new Map<number, (message: string) => ComposioError>([
335 - [1803, msg => new ComposioConnectedAccountNotFoundError(msg)],
346 +const ERROR_CODE_HANDLERS = new Map<number, (message: string, cause: APIError) => ComposioError>([
347 + [1803, (msg, cause) => new ComposioConnectedAccountNotFoundError(msg, { cause })],
348 // Add more error code handlers here as needed
349 ]);
350
351 +/** What to try when the API rejected an execution without a `suggested_fix`, by HTTP status. */
352 +const fallbackExecutionFixes = (status: number | undefined): string[] => {
353 + if (status === 401) {
354 + return ['Ensure you are using a valid Composio API key for this project'];
355 + }
356 + if (status === 402) {
357 + return ['Check the plan and billing limits of your Composio organization'];
358 + }
359 + if (status === 403) {
360 + return ['Ensure your API key and the connected account are allowed to run this tool'];
361 + }
362 + if (status === 410) {
363 + return ['The tool or the resource it acts on is no longer available; see the error message'];
364 + }
365 + if (status !== undefined && status >= 500) {
366 + return [
367 + 'The Composio API failed to process the request; retry later',
368 + 'If it keeps failing, contact Composio support with the request id',
369 + ];
370 + }
371 + return ['Ensure the tool slug is correct and the input arguments for the tool is valid'];
372 +};
373 +
374 export const handleToolExecutionError = (tool: string, actualError: Error): ComposioError => {
340 - // Handle specific API error codes
341 - if (actualError instanceof APIError && actualError.error) {
342 - const errorBody = actualError.error as ComposioAPIServerErrorBody;
343 - const errorCode = errorBody?.error?.code;
344 - const errorMessage = errorBody?.error?.message;
375 + const apiError = actualError instanceof APIError ? actualError : undefined;
376 + const details = apiError?.details;
377
346 - if (errorCode && ERROR_CODE_HANDLERS.has(errorCode)) {
347 - return ERROR_CODE_HANDLERS.get(errorCode)!(errorMessage || 'An error occurred');
348 - }
378 + // Handle specific API error codes
379 + if (apiError && details && ERROR_CODE_HANDLERS.has(details.code)) {
380 + return ERROR_CODE_HANDLERS.get(details.code)!(details.message || 'An error occurred', apiError);
381 }
382
383 if (isRateLimitResponse(actualError)) {
@@ -357,10 +389,18 @@ export const handleToolExecutionError = (tool: string, actualError: Error): Comp
389 }
390
391 // Default error for all other cases
360 - return new ComposioToolExecutionError(`Error executing the tool ${tool}`, {
361 - cause: actualError,
362 - possibleFixes: [
363 - 'Ensure the tool slug is correct and the input arguments for the tool is valid',
364 - ],
365 - });
392 + const serverMessage = details?.message;
393 + return new ComposioToolExecutionError(
394 + serverMessage
395 + ? `Error executing the tool ${tool}: ${serverMessage}`
396 + : `Error executing the tool ${tool}`,
397 + {
398 + cause: actualError,
399 + statusCode: apiError?.status,
400 + apiErrorCode: details?.code,
401 + possibleFixes: details?.suggested_fix
402 + ? [details.suggested_fix]
403 + : fallbackExecutionFixes(apiError?.status),
404 + }
405 + );
406 };
ts/packages/core/test/tools/executeSchemaCache.test.ts
+116 -1
@@ -1,9 +1,10 @@
1 import { describe, it, expect, vi, afterEach } from 'vitest';
2 -import ComposioClient, { Auth, createFetchTransport } from '@composio/client';
2 +import ComposioClient, { APIError, Auth, createFetchTransport } from '@composio/client';
3 import { Tools } from '../../src/models/Tools';
4 import { ComposioRequestCancelledError } from '../../src/errors/SDKErrors';
5 import { MockProvider } from '../utils/mocks/provider.mock';
6 import { toolMocks } from '../utils/mocks/data.mock';
7 +import { ComposioConnectedAccountNotFoundError } from '../../src/errors/ConnectedAccountsErrors';
8 import {
9 ComposioToolExecutionError,
10 ComposioToolExecutionRateLimitError,
@@ -236,3 +237,117 @@ describe('rate limit errors', () => {
237 expect(isComposioRateLimitError(error)).toBe(false);
238 });
239 });
240 +
241 +describe('transport metadata on errors', () => {
242 + it('reads the status and request id of a rejected schema fetch from its cause', async () => {
243 + const { tools } = createTools({
244 + retrieve: () =>
245 + json(
246 + { error: { message: 'bad key', code: 1001, slug: 'UNAUTHORIZED', status: 401 } },
247 + 401,
248 + { 'x-request-id': 'req_fetch_401' }
249 + ),
250 + });
251 +
252 + const error = await run(tools).catch(e => e);
253 +
254 + expect(error).toBeInstanceOf(ComposioToolFetchError);
255 + expect(error.statusCode).toBe(401);
256 + expect(error.requestId).toBe('req_fetch_401');
257 + expect(error.cause).toBeInstanceOf(APIError);
258 + });
259 +});
260 +
261 +describe('tool execution errors', () => {
262 + const rejected = (
263 + status: number,
264 + error: Record<string, unknown>,
265 + headers: Record<string, string> = {}
266 + ) => json({ error: { slug: 'ERROR', status, ...error } }, status, headers);
267 + const SLUG_FIX = 'Ensure the tool slug is correct and the input arguments for the tool is valid';
268 +
269 + it('surfaces the server message, suggested fix and codes of a 410', async () => {
270 + const { tools } = createTools({
271 + execute: () =>
272 + rejected(
273 + 410,
274 + {
275 + message: 'Toolkit version 20250101_00 is retired',
276 + code: 1410,
277 + suggested_fix: 'Pin 20250909_00',
278 + },
279 + { 'x-request-id': 'req_410' }
280 + ),
281 + });
282 +
283 + const error = await run(tools).catch(e => e);
284 +
285 + expect(error).toBeInstanceOf(ComposioToolExecutionError);
286 + expect(error.message).toBe(
287 + `Error executing the tool ${toolMocks.rawTool.slug}: Toolkit version 20250101_00 is retired`
288 + );
289 + expect(error.code).toBe('TS-SDK::TOOL_EXECUTION_ERROR');
290 + expect(error.statusCode).toBe(410);
291 + expect(error.apiErrorCode).toBe(1410);
292 + expect(error.requestId).toBe('req_410');
293 + expect(error.possibleFixes).toEqual(['Pin 20250909_00']);
294 + expect(error.cause).toBeInstanceOf(APIError);
295 + expect(error.cause.status).toBe(410);
296 + });
297 +
298 + it('falls back to a status-specific fix for a 403 without a suggested fix', async () => {
299 + const { tools } = createTools({
300 + execute: () =>
301 + rejected(403, { message: 'Connected account belongs to another project', code: 1403 }),
302 + });
303 +
304 + const error = await run(tools).catch(e => e);
305 +
306 + expect(error).toBeInstanceOf(ComposioToolExecutionError);
307 + expect(error.message).toBe(
308 + `Error executing the tool ${toolMocks.rawTool.slug}: Connected account belongs to another project`
309 + );
310 + expect(error.statusCode).toBe(403);
311 + expect(error.apiErrorCode).toBe(1403);
312 + expect(error.possibleFixes).toEqual([
313 + 'Ensure your API key and the connected account are allowed to run this tool',
314 + ]);
315 + expect(error.cause).toBeInstanceOf(APIError);
316 + });
317 +
318 + it.each([402, 410, 500, 503])('never blames the slug or arguments for a %i', async status => {
319 + const { tools } = createTools({ execute: () => rejected(status, { message: 'no', code: 1 }) });
320 +
321 + const error = await run(tools).catch(e => e);
322 +
323 + expect(error.statusCode).toBe(status);
324 + expect(error.possibleFixes).not.toContain(SLUG_FIX);
325 + });
326 +
327 + it('keeps the tool context alone when the body is not the error envelope', async () => {
328 + const { tools } = createTools({ execute: () => json({ unexpected: true }, 400) });
329 +
330 + const error = await run(tools).catch(e => e);
331 +
332 + expect(error).toBeInstanceOf(ComposioToolExecutionError);
333 + expect(error.message).toBe(`Error executing the tool ${toolMocks.rawTool.slug}`);
334 + expect(error.statusCode).toBe(400);
335 + expect(Object.keys(error)).not.toContain('apiErrorCode');
336 + expect(error.possibleFixes).toEqual([SLUG_FIX]);
337 + });
338 +
339 + it('keeps the cause of a missing connected account', async () => {
340 + const { tools } = createTools({
341 + execute: () => rejected(400, { message: 'No connected account found', code: 1803 }),
342 + });
343 +
344 + const error = await run(tools).catch(e => e);
345 +
346 + expect(error).toBeInstanceOf(ComposioConnectedAccountNotFoundError);
347 + expect(error.message).toBe('No connected account found');
348 + // The class sets its status itself, and an explicit status wins over the cause's.
349 + expect(error.statusCode).toBe(404);
350 + expect(error.cause).toBeInstanceOf(APIError);
351 + expect(error.cause.status).toBe(400);
352 + });
353 +});