Skip to content

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

haxzie8a23b1408568
diff --git a/examples/toolkits/src/index.ts b/examples/toolkits/src/index.ts
index 83982d541..5fa53e242 100644
--- a/examples/toolkits/src/index.ts
+++ b/examples/toolkits/src/index.ts
@@ -4,5 +4,5 @@ const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
});
-const toolkit = await composio.toolkits.get('hackernews');
-const client = composio.getClient();
+const toolkit = await composio.tools.get('default', 'INvalid tool');
+// const client = composio.getClient();
diff --git a/packages/core/docs/error-consistency.md b/packages/core/docs/error-consistency.md
index 049d495af..5c57a289e 100644
--- a/packages/core/docs/error-consistency.md
+++ b/packages/core/docs/error-consistency.md
@@ -41,7 +41,7 @@ Some error classes have specific requirements:
1. **ValidationError**: Accepts a `zodError` in the options.
```typescript
- new ValidationError('Message', { zodError: someZodError });
+ new ValidationError('Message', { cause: someZodError });
```
2. **ComposioToolExecutionError**: Accepts an `originalError` in the options.
diff --git a/packages/core/src/errors/ComposioError.ts b/packages/core/src/errors/ComposioError.ts
index ca9d26207..c05c0fcd3 100644
--- a/packages/core/src/errors/ComposioError.ts
+++ b/packages/core/src/errors/ComposioError.ts
@@ -66,6 +66,7 @@ export class ComposioError extends Error {
public name = 'ComposioError';
public code?: string;
public possibleFixes?: string[];
+ public errorId?: string;
/**
* Creates a new ComposioError
@@ -80,12 +81,15 @@ export class ComposioError extends Error {
options.statusCode ||
(options.cause instanceof BadRequestError ? options.cause.status : undefined);
- // Only define properties that have values to avoid showing undefined in error display
- this.code = options.code;
+ this.code = `TS-SDK:${options.code}`;
+ // format the possible fixes
this.possibleFixes = options.possibleFixes;
+ // Only define properties that have values to avoid showing undefined in error display
+ // Node.js by default shows all the properties of the error object, so we are doing it conditionally
this.definePropertyIfExists('statusCode', statusCode);
this.definePropertyIfExists('cause', options.cause);
+ this.definePropertyIfExists('stack', options.stack);
if (options.meta && Object.keys(options.meta).length > 0) {
this.definePropertyIfExists('meta', options.meta);
@@ -197,9 +201,7 @@ export class ComposioError extends Error {
if (data.possibleFixes?.length) {
logger.error('\n' + chalk.cyan.bold('Try the following:'));
- data.possibleFixes.forEach((fix, index) => {
- logger.error(' ' + chalk.green(`${index + 1}. ${fix}`));
- });
+ logger.error(data.possibleFixes);
}
if (data.stack?.length) {
diff --git a/packages/core/src/errors/ToolErrors.ts b/packages/core/src/errors/ToolErrors.ts
index 86aef702e..b4097d8c1 100644
--- a/packages/core/src/errors/ToolErrors.ts
+++ b/packages/core/src/errors/ToolErrors.ts
@@ -37,7 +37,6 @@ export class ComposioToolNotFoundError extends ComposioError {
possibleFixes: options.possibleFixes || [
'Ensure the tool slug is correct and exists in the Composio project',
],
- statusCode: 404,
});
this.name = 'ComposioToolNotFoundError';
}
diff --git a/packages/core/src/errors/ValidationErrors.ts b/packages/core/src/errors/ValidationErrors.ts
index 39970b2dc..83ad2f253 100644
--- a/packages/core/src/errors/ValidationErrors.ts
+++ b/packages/core/src/errors/ValidationErrors.ts
@@ -11,14 +11,9 @@ export const ValidationErrorCodes = {
} as const;
export class ValidationError extends ComposioError {
- public readonly zodError: ZodError;
-
- constructor(
- message: string = 'Input validation failed',
- options: ComposioErrorOptions & { zodError?: ZodError } = {}
- ) {
+ constructor(message: string = 'Input validation failed', options: ComposioErrorOptions = {}) {
// Extract and process the ZodError
- const { zodError: providedZodError, ...restOptions } = options;
+ const { cause: providedZodError, ...restOptions } = options;
// Determine the ZodError instance to use
let zodErrorInstance: ZodError;
@@ -49,10 +44,10 @@ export class ValidationError extends ComposioError {
super(message, {
...restOptions,
code: options.code || ValidationErrorCodes.VALIDATION_ERROR,
- cause,
+ possibleFixes: issues,
+ cause: zodErrorInstance,
});
- this.zodError = zodErrorInstance;
this.name = 'ValidationError';
// Capture the original stack trace from where the error occurred
@@ -65,8 +60,8 @@ export class ValidationError extends ComposioError {
private generateUserFriendlyMessage(): string {
// Extract the most relevant information from the ZodError
- if (this.zodError.issues.length > 0) {
- const issue = this.zodError.issues[0];
+ if (this.cause instanceof ZodError && this.cause.issues.length > 0) {
+ const issue = this.cause.issues[0];
const path = issue.path.join('.');
const param = path || 'parameter';
diff --git a/packages/core/src/models/AuthConfigs.ts b/packages/core/src/models/AuthConfigs.ts
index 57730e769..c357896f0 100644
--- a/packages/core/src/models/AuthConfigs.ts
+++ b/packages/core/src/models/AuthConfigs.ts
@@ -86,7 +86,7 @@ export class AuthConfigs {
});
if (result.error) {
throw new ValidationError('Failed to parse auth config response', {
- zodError: result.error,
+ cause: result.error,
});
}
return result.data;
@@ -133,7 +133,7 @@ export class AuthConfigs {
});
if (parsedResult.error) {
throw new ValidationError('Failed to parse auth config list response', {
- zodError: parsedResult.error,
+ cause: parsedResult.error,
});
}
return parsedResult.data;
@@ -164,7 +164,7 @@ export class AuthConfigs {
const parsedOptions = CreateAuthConfigParamsSchema.safeParse(options);
if (parsedOptions.error) {
throw new ValidationError('Failed to parse auth config create options', {
- zodError: parsedOptions.error,
+ cause: parsedOptions.error,
});
}
const result = await this.client.authConfigs.create({
@@ -181,7 +181,7 @@ export class AuthConfigs {
});
if (parsedResult.error) {
throw new ValidationError('Failed to parse auth config create response', {
- zodError: parsedResult.error,
+ cause: parsedResult.error,
});
}
return parsedResult.data;
@@ -245,7 +245,7 @@ export class AuthConfigs {
const parsedData = AuthConfigUpdateParamsSchema.safeParse(data);
if (parsedData.error) {
throw new ValidationError('Failed to parse auth config update data', {
- zodError: parsedData.error,
+ cause: parsedData.error,
});
}
return this.client.authConfigs.update(
diff --git a/packages/core/src/models/ConnectedAccounts.ts b/packages/core/src/models/ConnectedAccounts.ts
index 7dfa6c39f..3feb5f89a 100644
--- a/packages/core/src/models/ConnectedAccounts.ts
+++ b/packages/core/src/models/ConnectedAccounts.ts
@@ -61,7 +61,7 @@ export class ConnectedAccounts {
});
if (!result.success) {
throw new ValidationError('Failed to parse connected account retrieve response', {
- zodError: result.error,
+ cause: result.error,
});
}
return result.data;
@@ -98,7 +98,7 @@ export class ConnectedAccounts {
const parsedQuery = ConnectedAccountListParamsSchema.safeParse(query);
if (!parsedQuery.success) {
throw new ValidationError('Failed to parse connected account list query', {
- zodError: parsedQuery.error,
+ cause: parsedQuery.error,
});
}
rawQuery = {
@@ -122,7 +122,7 @@ export class ConnectedAccounts {
});
if (!parsedResponse.success) {
throw new ValidationError('Failed to parse connected account list response', {
- zodError: parsedResponse.error,
+ cause: parsedResponse.error,
});
}
return parsedResponse.data;
diff --git a/packages/core/src/models/Toolkits.ts b/packages/core/src/models/Toolkits.ts
index 8ad4d0316..bba38d791 100644
--- a/packages/core/src/models/Toolkits.ts
+++ b/packages/core/src/models/Toolkits.ts
@@ -48,7 +48,7 @@ export class Toolkits {
const parsedQuery = ToolkitsListParamsSchema.safeParse(query);
if (!parsedQuery.success) {
throw new ValidationError('Failed to parse toolkit list query', {
- zodError: parsedQuery.error,
+ cause: parsedQuery.error,
});
}
const result = await this.client.toolkits.list({
@@ -77,7 +77,7 @@ export class Toolkits {
if (!parsedResult.success) {
throw new ValidationError('Failed to parse toolkit list response', {
- zodError: parsedResult.error,
+ cause: parsedResult.error,
});
}
@@ -131,7 +131,7 @@ export class Toolkits {
});
if (!parsedResult.success) {
throw new ValidationError('Failed to parse toolkit response', {
- zodError: parsedResult.error,
+ cause: parsedResult.error,
});
}
return parsedResult.data;
diff --git a/packages/core/src/models/Tools.ts b/packages/core/src/models/Tools.ts
index 3f11e0b4c..6935fbb7b 100644
--- a/packages/core/src/models/Tools.ts
+++ b/packages/core/src/models/Tools.ts
@@ -254,7 +254,7 @@ export class Tools<
const queryParams = ToolListParamsSchema.safeParse(query);
if (queryParams.error) {
throw new ValidationError('Invalid tool list parameters', {
- zodError: queryParams.error,
+ cause: queryParams.error,
});
}
@@ -322,12 +322,15 @@ export class Tools<
return customTool;
}
// if not, fetch the tool from the Composio API
- const tool = await this.client.tools.retrieve(slug);
- if (!tool) {
- throw new ComposioToolNotFoundError(
- `[getRawComposioToolBySlug] Tool with slug ${slug} not found`
- );
+ let tool: ToolRetrieveResponse;
+ try {
+ tool = await this.client.tools.retrieve(slug);
+ } catch (error) {
+ throw new ComposioToolNotFoundError(`Unable to retrieve tool with slug ${slug}`, {
+ cause: error,
+ });
}
+
// change the case of the tool to camel case
let modifiedToool = this.transformToolCases(tool);
// apply local modifiers if they are provided
diff --git a/packages/core/src/telemetry/Telemetry.ts b/packages/core/src/telemetry/Telemetry.ts
index 92162b5ae..873d1187f 100644
--- a/packages/core/src/telemetry/Telemetry.ts
+++ b/packages/core/src/telemetry/Telemetry.ts
@@ -1,3 +1,10 @@
+// Extend the Error interface to include errorId
+declare global {
+ interface Error {
+ errorId?: string;
+ }
+}
+
import { ComposioError as ComposioClientError } from '@composio/client';
import {
TELEMETRY_EVENTS,
@@ -14,6 +21,7 @@ import { BaseTelemetryTransport } from './TelemetryTransport';
import { BrowserTelemetryTransport } from './transports/BrowserTransport';
import { ProcessTelemetryTransport } from './transports/ProcessTransport';
import { ComposioError } from '../errors/ComposioError';
+import { getRandomUUID } from '../utils/uuid';
/**
* The Telemetry class is used to log the telemetry for any given instance which extends InstrumentedInstance.
*
@@ -107,15 +115,20 @@ export class TelemetryService {
try {
return await originalMethod.apply(instance, args);
} catch (error) {
+ // inject error id to the error, this is to ensure we can track the error in logs
+ if (error instanceof Error && !error.errorId) {
+ // if there is error id, it means the error is already handled
+ error.errorId = getRandomUUID();
+ await this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
+ }
// @TODO: check if this will send the error telemetry to the server
- await this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name);
// rethrow the error to be handled by the caller
throw error;
}
};
-
- return instance;
}
+
+ return instance;
}
/**
@@ -142,38 +155,39 @@ export class TelemetryService {
private async prepareAndSendErrorTelemetry(
error: unknown,
instrumentedClassName: string,
- name: string
+ name: string,
+ args: unknown[]
) {
// client error, this is likely handled by the API itseld
if (error instanceof ComposioClientError) {
const telemetryPayload: TelemetryErrorPayloadParams = {
- error_id: error.name,
+ error_id: error.errorId || '',
error_message: error.message,
original_error: error.cause || error,
current_stack: error.stack?.split('\n') || [],
- description: `${this.telemetryMetadata.source}:${instrumentedClassName}.${name}`,
+ description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
};
await this.sendErrorTelemetry(telemetryPayload);
} else if (error instanceof ComposioError) {
// Composio SDK Errors
const telemetryPayload: TelemetryErrorPayloadParams = {
- error_id: error.name,
+ error_id: error.errorId || '',
error_message: error.message,
original_error: error.cause || error,
current_stack: error.stack?.split('\n') || [],
error_code: error.code,
possible_fix: error.possibleFixes?.join('\n'),
- description: `${this.telemetryMetadata.source}:${instrumentedClassName}.${name}`,
+ description: `Original Call : ${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
};
await this.sendErrorTelemetry(telemetryPayload);
} else if (error instanceof Error) {
// Unhandled errors
const telemetryPayload: TelemetryErrorPayloadParams = {
- error_id: error.name,
+ error_id: error.errorId || '',
error_message: error instanceof Error ? error.name : 'Unknown error',
original_error: error,
current_stack: error.stack?.split('\n') || [],
- description: `${this.telemetryMetadata.source}:${instrumentedClassName}.${name}`,
+ description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`,
};
await this.sendErrorTelemetry(telemetryPayload);
}
@@ -221,7 +235,7 @@ export class TelemetryService {
headers: { 'Content-Type': 'application/json' },
};
- this.transport.send(reqPayload);
+ await this.transport.send(reqPayload);
}
}
diff --git a/packages/core/src/telemetry/transports/ProcessTransport.ts b/packages/core/src/telemetry/transports/ProcessTransport.ts
index c0d76468b..7f00eeb3a 100644
--- a/packages/core/src/telemetry/transports/ProcessTransport.ts
+++ b/packages/core/src/telemetry/transports/ProcessTransport.ts
@@ -3,64 +3,80 @@ import { TelemetryTransportParams } from '../../types/telemetry.types';
import logger from '../../utils/logger';
import { BaseTelemetryTransport } from '../TelemetryTransport';
export class ProcessTelemetryTransport implements BaseTelemetryTransport {
- send(payload: TelemetryTransportParams): Promise<void> {
+ async send(payload: TelemetryTransportParams): Promise<void> {
if (typeof window !== 'undefined') {
return Promise.reject(
new Error('ProcessTelemetryTransport can only be used in Node.js environments')
);
}
- return new Promise(resolve => {
- try {
- const url = new URL(payload.url);
- const protocol = url.protocol === 'https:' ? 'https' : 'http';
- const port = url.port || (url.protocol === 'https:' ? 443 : 80);
+ try {
+ await fetch(payload.url, {
+ method: payload.method,
+ headers: payload.headers,
+ body: JSON.stringify(payload.data),
+ });
+ logger.debug(chalk.yellow('ProcessTelemetry'), JSON.stringify(payload, null, 2));
+ } catch (error) {
+ logger.error('Error sending telemetry', error);
+ return Promise.resolve();
+ }
+
+ // return new Promise(resolve => {
+ // try {
+ // // use fetch to send the telemetry
+
+ // const url = new URL(payload.url);
+ // const protocol = url.protocol === 'https:' ? 'https' : 'http';
+ // const port = url.port || (url.protocol === 'https:' ? 443 : 80);
+
+ // const args = [
+ // '-e',
+ // `
+ // const http = require('${protocol}');
+ // const options = {
+ // hostname: '${url.hostname}',
+ // path: '${url.pathname}${url.search}',
+ // port: ${port},
+ // method: '${payload.method}',
+ // headers: ${JSON.stringify(payload.headers)}
+ // };
- const args = [
- '-e',
- `
- const http = require('${protocol}');
- const options = {
- hostname: '${url.hostname}',
- path: '${url.pathname}${url.search}',
- port: ${port},
- method: '${payload.method}',
- headers: ${JSON.stringify(payload.headers)}
- };
+ // const req = http.request(options, (res) => {
+ // res.on('data', () => {});
+ // res.on('end', () => {
+ // process.exit(0);
+ // });
+ // });
- const req = http.request(options, (res) => {
- res.on('data', () => {});
- res.on('end', () => {
- process.exit(0);
- });
- });
+ // req.on('error', () => {
- req.on('error', () => {
- process.exit(0);
- });
+ // process.exit(0);
+ // });
- req.write(JSON.stringify(${JSON.stringify(payload.data)}));
- req.end();
- `,
- ];
+ // req.write(JSON.stringify(${JSON.stringify(payload.data)}));
+ // req.end();
+ // `,
+ // ];
- import('child_process')
- .then(({ spawn }) => {
- spawn('node', args, {
- stdio: 'ignore',
- detached: true,
- shell: false,
- }).unref();
- resolve();
- })
- .catch(() => {
- resolve();
- });
- logger.debug(chalk.yellow('Process telemetry'), JSON.stringify(payload, null, 2));
- } catch (error) {
- logger.error('Error sending telemetry', error);
- resolve();
- }
- });
+ // import('child_process')
+ // .then(({ spawn }) => {
+ // spawn('node', args, {
+ // stdio: 'ignore',
+ // detached: false,
+ // shell: false,
+ // }).unref();
+ // resolve();
+ // })
+ // .catch(error => {
+ // logger.error('Error sending telemetry', error);
+ // resolve();
+ // });
+ // logger.debug(chalk.yellow('Process Telemetry'), JSON.stringify(payload, null, 2));
+ // } catch (error) {
+ // logger.error('Error sending telemetry', error);
+ // resolve();
+ // }
+ // });
}
}
diff --git a/packages/core/test/tools/tools.test.ts b/packages/core/test/tools/tools.test.ts
index 3afc1be12..1be761d03 100644
--- a/packages/core/test/tools/tools.test.ts
+++ b/packages/core/test/tools/tools.test.ts
@@ -170,10 +170,10 @@ describe('Tools', () => {
const getCustomToolBySlugSpy = vi.spyOn(context.tools['customTools'], 'getCustomToolBySlug');
getCustomToolBySlugSpy.mockResolvedValueOnce(undefined);
- mockClient.tools.retrieve.mockResolvedValueOnce(null);
+ mockClient.tools.retrieve.mockRejectedValue(null);
await expect(context.tools.getRawComposioToolBySlug(userId, slug)).rejects.toThrow(
- `Tool with slug ${slug} not found`
+ `Unable to retrieve tool with slug ${slug}`
);
});