@devries-cameron20 / composio-1 / commits / 8a23b1408
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.

Fix errors

haxzie committed May 22, 2025 at 17:43 UTC 8a23b1408568b85549271fa23e77be160587dca6
12 files changed +127 -98
examples/toolkits/src/index.ts
+2 -2
@@ -4,5 +4,5 @@ const composio = new Composio({
4 apiKey: process.env.COMPOSIO_API_KEY,
5 });
6
7 -const toolkit = await composio.toolkits.get('hackernews');
8 -const client = composio.getClient();
7 +const toolkit = await composio.tools.get('default', 'INvalid tool');
8 +// const client = composio.getClient();
packages/core/docs/error-consistency.md
+1 -1
@@ -41,7 +41,7 @@ Some error classes have specific requirements:
41 1. **ValidationError**: Accepts a `zodError` in the options.
42
43 ```typescript
44 - new ValidationError('Message', { zodError: someZodError });
44 + new ValidationError('Message', { cause: someZodError });
45 ```
46
47 2. **ComposioToolExecutionError**: Accepts an `originalError` in the options.
packages/core/src/errors/ComposioError.ts
+7 -5
@@ -66,6 +66,7 @@ export class ComposioError extends Error {
66 public name = 'ComposioError';
67 public code?: string;
68 public possibleFixes?: string[];
69 + public errorId?: string;
70
71 /**
72 * Creates a new ComposioError
@@ -80,12 +81,15 @@ export class ComposioError extends Error {
81 options.statusCode ||
82 (options.cause instanceof BadRequestError ? options.cause.status : undefined);
83
83 - // Only define properties that have values to avoid showing undefined in error display
84 - this.code = options.code;
84 + this.code = `TS-SDK:${options.code}`;
85 + // format the possible fixes
86 this.possibleFixes = options.possibleFixes;
87
88 + // Only define properties that have values to avoid showing undefined in error display
89 + // Node.js by default shows all the properties of the error object, so we are doing it conditionally
90 this.definePropertyIfExists('statusCode', statusCode);
91 this.definePropertyIfExists('cause', options.cause);
92 + this.definePropertyIfExists('stack', options.stack);
93
94 if (options.meta && Object.keys(options.meta).length > 0) {
95 this.definePropertyIfExists('meta', options.meta);
@@ -197,9 +201,7 @@ export class ComposioError extends Error {
201
202 if (data.possibleFixes?.length) {
203 logger.error('\n' + chalk.cyan.bold('Try the following:'));
200 - data.possibleFixes.forEach((fix, index) => {
201 - logger.error(' ' + chalk.green(`${index + 1}. ${fix}`));
202 - });
204 + logger.error(data.possibleFixes);
205 }
206
207 if (data.stack?.length) {
packages/core/src/errors/ToolErrors.ts
-1
@@ -37,7 +37,6 @@ export class ComposioToolNotFoundError extends ComposioError {
37 possibleFixes: options.possibleFixes || [
38 'Ensure the tool slug is correct and exists in the Composio project',
39 ],
40 - statusCode: 404,
40 });
41 this.name = 'ComposioToolNotFoundError';
42 }
packages/core/src/errors/ValidationErrors.ts
+6 -11
@@ -11,14 +11,9 @@ export const ValidationErrorCodes = {
11 } as const;
12
13 export class ValidationError extends ComposioError {
14 - public readonly zodError: ZodError;
15 -
16 - constructor(
17 - message: string = 'Input validation failed',
18 - options: ComposioErrorOptions & { zodError?: ZodError } = {}
19 - ) {
14 + constructor(message: string = 'Input validation failed', options: ComposioErrorOptions = {}) {
15 // Extract and process the ZodError
21 - const { zodError: providedZodError, ...restOptions } = options;
16 + const { cause: providedZodError, ...restOptions } = options;
17
18 // Determine the ZodError instance to use
19 let zodErrorInstance: ZodError;
@@ -49,10 +44,10 @@ export class ValidationError extends ComposioError {
44 super(message, {
45 ...restOptions,
46 code: options.code || ValidationErrorCodes.VALIDATION_ERROR,
52 - cause,
47 + possibleFixes: issues,
48 + cause: zodErrorInstance,
49 });
50
55 - this.zodError = zodErrorInstance;
51 this.name = 'ValidationError';
52
53 // Capture the original stack trace from where the error occurred
@@ -65,8 +60,8 @@ export class ValidationError extends ComposioError {
60
61 private generateUserFriendlyMessage(): string {
62 // Extract the most relevant information from the ZodError
68 - if (this.zodError.issues.length > 0) {
69 - const issue = this.zodError.issues[0];
63 + if (this.cause instanceof ZodError && this.cause.issues.length > 0) {
64 + const issue = this.cause.issues[0];
65 const path = issue.path.join('.');
66 const param = path || 'parameter';
67
packages/core/src/models/AuthConfigs.ts
+5 -5
@@ -86,7 +86,7 @@ export class AuthConfigs {
86 });
87 if (result.error) {
88 throw new ValidationError('Failed to parse auth config response', {
89 - zodError: result.error,
89 + cause: result.error,
90 });
91 }
92 return result.data;
@@ -133,7 +133,7 @@ export class AuthConfigs {
133 });
134 if (parsedResult.error) {
135 throw new ValidationError('Failed to parse auth config list response', {
136 - zodError: parsedResult.error,
136 + cause: parsedResult.error,
137 });
138 }
139 return parsedResult.data;
@@ -164,7 +164,7 @@ export class AuthConfigs {
164 const parsedOptions = CreateAuthConfigParamsSchema.safeParse(options);
165 if (parsedOptions.error) {
166 throw new ValidationError('Failed to parse auth config create options', {
167 - zodError: parsedOptions.error,
167 + cause: parsedOptions.error,
168 });
169 }
170 const result = await this.client.authConfigs.create({
@@ -181,7 +181,7 @@ export class AuthConfigs {
181 });
182 if (parsedResult.error) {
183 throw new ValidationError('Failed to parse auth config create response', {
184 - zodError: parsedResult.error,
184 + cause: parsedResult.error,
185 });
186 }
187 return parsedResult.data;
@@ -245,7 +245,7 @@ export class AuthConfigs {
245 const parsedData = AuthConfigUpdateParamsSchema.safeParse(data);
246 if (parsedData.error) {
247 throw new ValidationError('Failed to parse auth config update data', {
248 - zodError: parsedData.error,
248 + cause: parsedData.error,
249 });
250 }
251 return this.client.authConfigs.update(
packages/core/src/models/ConnectedAccounts.ts
+3 -3
@@ -61,7 +61,7 @@ export class ConnectedAccounts {
61 });
62 if (!result.success) {
63 throw new ValidationError('Failed to parse connected account retrieve response', {
64 - zodError: result.error,
64 + cause: result.error,
65 });
66 }
67 return result.data;
@@ -98,7 +98,7 @@ export class ConnectedAccounts {
98 const parsedQuery = ConnectedAccountListParamsSchema.safeParse(query);
99 if (!parsedQuery.success) {
100 throw new ValidationError('Failed to parse connected account list query', {
101 - zodError: parsedQuery.error,
101 + cause: parsedQuery.error,
102 });
103 }
104 rawQuery = {
@@ -122,7 +122,7 @@ export class ConnectedAccounts {
122 });
123 if (!parsedResponse.success) {
124 throw new ValidationError('Failed to parse connected account list response', {
125 - zodError: parsedResponse.error,
125 + cause: parsedResponse.error,
126 });
127 }
128 return parsedResponse.data;
packages/core/src/models/Toolkits.ts
+3 -3
@@ -48,7 +48,7 @@ export class Toolkits {
48 const parsedQuery = ToolkitsListParamsSchema.safeParse(query);
49 if (!parsedQuery.success) {
50 throw new ValidationError('Failed to parse toolkit list query', {
51 - zodError: parsedQuery.error,
51 + cause: parsedQuery.error,
52 });
53 }
54 const result = await this.client.toolkits.list({
@@ -77,7 +77,7 @@ export class Toolkits {
77
78 if (!parsedResult.success) {
79 throw new ValidationError('Failed to parse toolkit list response', {
80 - zodError: parsedResult.error,
80 + cause: parsedResult.error,
81 });
82 }
83
@@ -131,7 +131,7 @@ export class Toolkits {
131 });
132 if (!parsedResult.success) {
133 throw new ValidationError('Failed to parse toolkit response', {
134 - zodError: parsedResult.error,
134 + cause: parsedResult.error,
135 });
136 }
137 return parsedResult.data;
packages/core/src/models/Tools.ts
+9 -6
@@ -254,7 +254,7 @@ export class Tools<
254 const queryParams = ToolListParamsSchema.safeParse(query);
255 if (queryParams.error) {
256 throw new ValidationError('Invalid tool list parameters', {
257 - zodError: queryParams.error,
257 + cause: queryParams.error,
258 });
259 }
260
@@ -322,12 +322,15 @@ export class Tools<
322 return customTool;
323 }
324 // if not, fetch the tool from the Composio API
325 - const tool = await this.client.tools.retrieve(slug);
326 - if (!tool) {
327 - throw new ComposioToolNotFoundError(
328 - `[getRawComposioToolBySlug] Tool with slug ${slug} not found`
329 - );
325 + let tool: ToolRetrieveResponse;
326 + try {
327 + tool = await this.client.tools.retrieve(slug);
328 + } catch (error) {
329 + throw new ComposioToolNotFoundError(`Unable to retrieve tool with slug ${slug}`, {
330 + cause: error,
331 + });
332 }
333 +
334 // change the case of the tool to camel case
335 let modifiedToool = this.transformToolCases(tool);
336 // apply local modifiers if they are provided
packages/core/src/telemetry/Telemetry.ts
+25 -11
@@ -1,3 +1,10 @@
1 +// Extend the Error interface to include errorId
2 +declare global {
3 + interface Error {
4 + errorId?: string;
5 + }
6 +}
7 +
8 import { ComposioError as ComposioClientError } from '@composio/client';
9 import {
10 TELEMETRY_EVENTS,
@@ -14,6 +21,7 @@ import { BaseTelemetryTransport } from './TelemetryTransport';
21 import { BrowserTelemetryTransport } from './transports/BrowserTransport';
22 import { ProcessTelemetryTransport } from './transports/ProcessTransport';
23 import { ComposioError } from '../errors/ComposioError';
24 +import { getRandomUUID } from '../utils/uuid';
25 /**
26 * The Telemetry class is used to log the telemetry for any given instance which extends InstrumentedInstance.
27 *
@@ -107,15 +115,20 @@ export class TelemetryService {
115 try {
116 return await originalMethod.apply(instance, args);
117 } catch (error) {
118 + // inject error id to the error, this is to ensure we can track the error in logs
119 + if (error instanceof Error && !error.errorId) {
120 + // if there is error id, it means the error is already handled
121 + error.errorId = getRandomUUID();
122 + await this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
123 + }
124 // @TODO: check if this will send the error telemetry to the server
111 - await this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name);
125 // rethrow the error to be handled by the caller
126 throw error;
127 }
128 };
116 -
117 - return instance;
129 }
130 +
131 + return instance;
132 }
133
134 /**
@@ -142,38 +155,39 @@ export class TelemetryService {
155 private async prepareAndSendErrorTelemetry(
156 error: unknown,
157 instrumentedClassName: string,
145 - name: string
158 + name: string,
159 + args: unknown[]
160 ) {
161 // client error, this is likely handled by the API itseld
162 if (error instanceof ComposioClientError) {
163 const telemetryPayload: TelemetryErrorPayloadParams = {
150 - error_id: error.name,
164 + error_id: error.errorId || '',
165 error_message: error.message,
166 original_error: error.cause || error,
167 current_stack: error.stack?.split('\n') || [],
154 - description: `${this.telemetryMetadata.source}:${instrumentedClassName}.${name}`,
168 + description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
169 };
170 await this.sendErrorTelemetry(telemetryPayload);
171 } else if (error instanceof ComposioError) {
172 // Composio SDK Errors
173 const telemetryPayload: TelemetryErrorPayloadParams = {
160 - error_id: error.name,
174 + error_id: error.errorId || '',
175 error_message: error.message,
176 original_error: error.cause || error,
177 current_stack: error.stack?.split('\n') || [],
178 error_code: error.code,
179 possible_fix: error.possibleFixes?.join('\n'),
166 - description: `${this.telemetryMetadata.source}:${instrumentedClassName}.${name}`,
180 + description: `Original Call : ${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
181 };
182 await this.sendErrorTelemetry(telemetryPayload);
183 } else if (error instanceof Error) {
184 // Unhandled errors
185 const telemetryPayload: TelemetryErrorPayloadParams = {
172 - error_id: error.name,
186 + error_id: error.errorId || '',
187 error_message: error instanceof Error ? error.name : 'Unknown error',
188 original_error: error,
189 current_stack: error.stack?.split('\n') || [],
176 - description: `${this.telemetryMetadata.source}:${instrumentedClassName}.${name}`,
190 + description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
191 };
192 await this.sendErrorTelemetry(telemetryPayload);
193 }
@@ -221,7 +235,7 @@ export class TelemetryService {
235 headers: { 'Content-Type': 'application/json' },
236 };
237
224 - this.transport.send(reqPayload);
238 + await this.transport.send(reqPayload);
239 }
240 }
241
packages/core/src/telemetry/transports/ProcessTransport.ts
+64 -48
@@ -3,64 +3,80 @@ import { TelemetryTransportParams } from '../../types/telemetry.types';
3 import logger from '../../utils/logger';
4 import { BaseTelemetryTransport } from '../TelemetryTransport';
5 export class ProcessTelemetryTransport implements BaseTelemetryTransport {
6 - send(payload: TelemetryTransportParams): Promise<void> {
6 + async send(payload: TelemetryTransportParams): Promise<void> {
7 if (typeof window !== 'undefined') {
8 return Promise.reject(
9 new Error('ProcessTelemetryTransport can only be used in Node.js environments')
10 );
11 }
12
13 - return new Promise(resolve => {
14 - try {
15 - const url = new URL(payload.url);
16 - const protocol = url.protocol === 'https:' ? 'https' : 'http';
17 - const port = url.port || (url.protocol === 'https:' ? 443 : 80);
13 + try {
14 + await fetch(payload.url, {
15 + method: payload.method,
16 + headers: payload.headers,
17 + body: JSON.stringify(payload.data),
18 + });
19 + logger.debug(chalk.yellow('ProcessTelemetry'), JSON.stringify(payload, null, 2));
20 + } catch (error) {
21 + logger.error('Error sending telemetry', error);
22 + return Promise.resolve();
23 + }
24 +
25 + // return new Promise(resolve => {
26 + // try {
27 + // // use fetch to send the telemetry
28 +
29 + // const url = new URL(payload.url);
30 + // const protocol = url.protocol === 'https:' ? 'https' : 'http';
31 + // const port = url.port || (url.protocol === 'https:' ? 443 : 80);
32 +
33 + // const args = [
34 + // '-e',
35 + // `
36 + // const http = require('${protocol}');
37 + // const options = {
38 + // hostname: '${url.hostname}',
39 + // path: '${url.pathname}${url.search}',
40 + // port: ${port},
41 + // method: '${payload.method}',
42 + // headers: ${JSON.stringify(payload.headers)}
43 + // };
44
19 - const args = [
20 - '-e',
21 - `
22 - const http = require('${protocol}');
23 - const options = {
24 - hostname: '${url.hostname}',
25 - path: '${url.pathname}${url.search}',
26 - port: ${port},
27 - method: '${payload.method}',
28 - headers: ${JSON.stringify(payload.headers)}
29 - };
45 + // const req = http.request(options, (res) => {
46 + // res.on('data', () => {});
47 + // res.on('end', () => {
48 + // process.exit(0);
49 + // });
50 + // });
51
31 - const req = http.request(options, (res) => {
32 - res.on('data', () => {});
33 - res.on('end', () => {
34 - process.exit(0);
35 - });
36 - });
52 + // req.on('error', () => {
53
38 - req.on('error', () => {
39 - process.exit(0);
40 - });
54 + // process.exit(0);
55 + // });
56
42 - req.write(JSON.stringify(${JSON.stringify(payload.data)}));
43 - req.end();
44 - `,
45 - ];
57 + // req.write(JSON.stringify(${JSON.stringify(payload.data)}));
58 + // req.end();
59 + // `,
60 + // ];
61
47 - import('child_process')
48 - .then(({ spawn }) => {
49 - spawn('node', args, {
50 - stdio: 'ignore',
51 - detached: true,
52 - shell: false,
53 - }).unref();
54 - resolve();
55 - })
56 - .catch(() => {
57 - resolve();
58 - });
59 - logger.debug(chalk.yellow('Process telemetry'), JSON.stringify(payload, null, 2));
60 - } catch (error) {
61 - logger.error('Error sending telemetry', error);
62 - resolve();
63 - }
64 - });
62 + // import('child_process')
63 + // .then(({ spawn }) => {
64 + // spawn('node', args, {
65 + // stdio: 'ignore',
66 + // detached: false,
67 + // shell: false,
68 + // }).unref();
69 + // resolve();
70 + // })
71 + // .catch(error => {
72 + // logger.error('Error sending telemetry', error);
73 + // resolve();
74 + // });
75 + // logger.debug(chalk.yellow('Process Telemetry'), JSON.stringify(payload, null, 2));
76 + // } catch (error) {
77 + // logger.error('Error sending telemetry', error);
78 + // resolve();
79 + // }
80 + // });
81 }
82 }
packages/core/test/tools/tools.test.ts
+2 -2
@@ -170,10 +170,10 @@ describe('Tools', () => {
170
171 const getCustomToolBySlugSpy = vi.spyOn(context.tools['customTools'], 'getCustomToolBySlug');
172 getCustomToolBySlugSpy.mockResolvedValueOnce(undefined);
173 - mockClient.tools.retrieve.mockResolvedValueOnce(null);
173 + mockClient.tools.retrieve.mockRejectedValue(null);
174
175 await expect(context.tools.getRawComposioToolBySlug(userId, slug)).rejects.toThrow(
176 - `Tool with slug ${slug} not found`
176 + `Unable to retrieve tool with slug ${slug}`
177 );
178 });
179