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.

Add error handling

haxziea09ab1586327
diff --git a/examples/pre-processors/src/index.ts b/examples/pre-processors/src/index.ts
index 3f3e9bd0f..c64ac3950 100644
--- a/examples/pre-processors/src/index.ts
+++ b/examples/pre-processors/src/index.ts
@@ -8,10 +8,6 @@ const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
});
-const toolkit = await composio.toolkits.get('HACKERNEWS');
-
-console.log(toolkit);
-
const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER', {
// toolkit slug too
modifyToolSchema: (toolSlug, toolkitSlug, toolSchema) => {
@@ -34,6 +30,9 @@ const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER', {
console.log(tools);
+/**
+ * Agentic toolset
+ */
const vercel = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
// calling this provider now no? or what? or toolProvider or toolManager?
diff --git a/examples/toolkits/.env.example b/examples/toolkits/.env.example
new file mode 100644
index 000000000..ad0f7ed62
--- /dev/null
+++ b/examples/toolkits/.env.example
@@ -0,0 +1,2 @@
+COMPOSIO_API_KEY=
+OPENAI_API_KEY=
\ No newline at end of file
diff --git a/examples/toolkits/README.md b/examples/toolkits/README.md
new file mode 100644
index 000000000..30d3fa303
--- /dev/null
+++ b/examples/toolkits/README.md
@@ -0,0 +1,69 @@
+# Vercel Example with Composio SDK
+
+This example demonstrates how to use the Composio SDK with Vercel's AI SDK to create an AI-powered application that can interact with HackerNews data.
+
+## Features
+
+- Integration with Composio SDK and Vercel AI SDK
+- HackerNews front page summarization using GPT-4
+- Streaming AI responses
+- TypeScript support
+
+## Prerequisites
+
+- [Node.js](https://nodejs.org/) (Latest LTS version recommended)
+- [pnpm](https://pnpm.io/) (v10.8.0 or later)
+- Composio API Key
+- OpenAI API Key
+
+## Getting Started
+
+1. Clone the repository and navigate to the example directory:
+```bash
+cd examples/vercel
+```
+
+2. Install dependencies:
+```bash
+pnpm install
+```
+
+3. Copy the `.env.example` file to `.env` and fill in your API keys:
+```bash
+cp .env.example .env
+```
+
+4. Update the `.env` file with your credentials:
+```env
+COMPOSIO_API_KEY=your_composio_api_key
+OPENAI_API_KEY=your_openai_api_key
+```
+
+5. Start the development server:
+```bash
+pnpm start
+```
+
+## How It Works
+
+This example showcases how to:
+1. Initialize the Composio SDK with the Vercel toolset
+2. Use the HackerNews tool to fetch front page data
+3. Generate AI responses using OpenAI's GPT-4
+4. Handle tool calls and results in a chat-like interface
+
+## Dependencies
+
+- `@composio/core`: Core Composio SDK
+- `@composio/vercel`: Vercel integration for Composio
+- `@ai-sdk/openai`: OpenAI integration
+- `ai`: Vercel's AI SDK
+- TypeScript for type safety
+
+## License
+
+ISC
+
+## Support
+
+For questions and support, please refer to the [Composio documentation](https://docs.composio.dev) or open an issue in the repository.
\ No newline at end of file
diff --git a/examples/toolkits/package.json b/examples/toolkits/package.json
new file mode 100644
index 000000000..4c61c6fa1
--- /dev/null
+++ b/examples/toolkits/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "modifiers-example",
+ "private": true,
+ "version": "0.1.6-alpha.0",
+ "description": "",
+ "main": "src/index.ts",
+ "scripts": {
+ "start": "bun src/index.ts",
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "ISC",
+ "packageManager": "[email protected]",
+ "dependencies": {
+ "@ai-sdk/openai": "^1.3.16",
+ "@composio/core": "workspace:*",
+ "@composio/vercel": "workspace:*",
+ "ai": "^4.3.8"
+ },
+ "devDependencies": {
+ "@types/bun": "^1.2.9",
+ "typescript": "^5.8.3"
+ }
+}
diff --git a/examples/toolkits/src/index.ts b/examples/toolkits/src/index.ts
new file mode 100644
index 000000000..2404285ad
--- /dev/null
+++ b/examples/toolkits/src/index.ts
@@ -0,0 +1,9 @@
+import { Composio } from '@composio/core';
+
+const composio = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+});
+
+const toolkit = await composio.toolkits.get('modifiers-example');
+
+console.log(toolkit);
diff --git a/examples/toolkits/tsconfig.json b/examples/toolkits/tsconfig.json
new file mode 100644
index 000000000..ad82940d5
--- /dev/null
+++ b/examples/toolkits/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "module": "ESNext",
+ "declaration": true,
+ "declarationDir": "./dist",
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "moduleResolution": "node",
+ "skipLibCheck": true
+ },
+ "include": ["src"]
+}
diff --git a/packages/core/src/errors/ComposioError.ts b/packages/core/src/errors/ComposioError.ts
new file mode 100644
index 000000000..17becee28
--- /dev/null
+++ b/packages/core/src/errors/ComposioError.ts
@@ -0,0 +1,51 @@
+/**
+ * @fileoverview Error class for Composio.
+ *
+ * This error class is used to create custom errors for Composio.
+ * It extends the built-in Error class and adds additional properties for code, status code, cause, meta, and possible fixes.
+ *
+ * @author Musthaq Ahamad <[email protected]>
+ * @module errors/ComposioError
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error}
+ */
+export type ComposioErrorOptions = {
+ code?: string;
+ statusCode?: number;
+ cause?: unknown;
+ meta?: Record<string, unknown>;
+ possibleFixes?: string[];
+};
+export class ComposioError extends Error {
+ public name = 'ComposioError';
+ public readonly code?: string;
+ public readonly statusCode?: number;
+ public readonly cause?: unknown;
+ public readonly meta?: Record<string, unknown>;
+ public readonly possibleFixes?: string[];
+
+ constructor(message: string, options: ComposioErrorOptions = {}) {
+ super(message);
+ this.code = options.code;
+ this.statusCode = options.statusCode;
+ this.cause = options.cause;
+ this.meta = options.meta;
+ this.possibleFixes = options.possibleFixes;
+
+ // Captures stack trace excluding the constructor frame
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+ }
+
+ toJSON() {
+ return {
+ name: this.name,
+ message: this.message,
+ code: this.code,
+ statusCode: this.statusCode,
+ cause: this.cause instanceof Error ? this.cause.message : this.cause,
+ meta: this.meta,
+ possibleFixes: this.possibleFixes?.length ? this.possibleFixes.join('\n') : undefined,
+ };
+ }
+}
diff --git a/packages/core/src/errors/ConnectedAccountsError.ts b/packages/core/src/errors/ConnectedAccountsError.ts
new file mode 100644
index 000000000..6dc0cded7
--- /dev/null
+++ b/packages/core/src/errors/ConnectedAccountsError.ts
@@ -0,0 +1,18 @@
+import { ComposioError } from './ComposioError';
+
+export const ConnectedAccountErrorCodes = {
+ CONNECTED_ACCOUNT_NOT_FOUND: 'CONNECTED_ACCOUNT_NOT_FOUND',
+} as const;
+
+export class ComposioConnectedAccountNotFoundError extends ComposioError {
+ constructor(message: string = 'Connected account not found', meta: Record<string, unknown> = {}) {
+ super(message, {
+ code: ConnectedAccountErrorCodes.CONNECTED_ACCOUNT_NOT_FOUND,
+ statusCode: 404,
+ meta,
+ possibleFixes: [
+ 'Ensure the connected account exists and is active in your Composio dashboard',
+ ],
+ });
+ }
+}
diff --git a/packages/core/src/errors/ConnectionRequestError.ts b/packages/core/src/errors/ConnectionRequestError.ts
new file mode 100644
index 000000000..a95a06d87
--- /dev/null
+++ b/packages/core/src/errors/ConnectionRequestError.ts
@@ -0,0 +1,17 @@
+import { ComposioError } from './ComposioError';
+
+export const ConnectionRequestErrorCodes = {
+ CONNECTION_REQUEST_TIMEOUT: 'CONNECTION_REQUEST_TIMEOUT',
+} as const;
+
+export class ConnectionRequestTimeoutError extends ComposioError {
+ constructor(
+ message: string = 'Connection request timed out',
+ meta: Record<string, unknown> = {}
+ ) {
+ super(message, {
+ code: ConnectionRequestErrorCodes.CONNECTION_REQUEST_TIMEOUT,
+ meta,
+ });
+ }
+}
diff --git a/packages/core/src/errors/ToolErrors.ts b/packages/core/src/errors/ToolErrors.ts
new file mode 100644
index 000000000..75a3b96b3
--- /dev/null
+++ b/packages/core/src/errors/ToolErrors.ts
@@ -0,0 +1,90 @@
+import { ComposioError } from './ComposioError';
+import { ComposioError as ComposioClientError } from '@composio/client';
+
+export const ToolErrorCodes = {
+ TOOLSET_NOT_DEFINED: 'TOOLSET_NOT_DEFINED',
+ TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',
+ INVALID_MODIFIER: 'INVALID_MODIFIER',
+ CUSTOM_TOOLS_NOT_INITIALIZED: 'CUSTOM_TOOLS_NOT_INITIALIZED',
+ TOOL_EXECUTION_ERROR: 'TOOL_EXECUTION_ERROR',
+ INVALID_EXECUTE_FUNCTION: 'INVALID_EXECUTE_FUNCTION',
+} as const;
+
+export class ComposioToolsetNotDefinedError extends ComposioError {
+ constructor(message: string = 'Toolset not defined', meta: Record<string, unknown> = {}) {
+ super(message, {
+ code: ToolErrorCodes.TOOLSET_NOT_DEFINED,
+ meta,
+ possibleFixes: [
+ 'Ensure that the toolset is defined in the Composio project and passed into the tool instance',
+ ],
+ });
+ this.name = 'ComposioToolsetNotDefinedError';
+ }
+}
+
+export class ComposioToolNotFoundError extends ComposioError {
+ constructor(message: string = 'Tool not found', meta: Record<string, unknown> = {}) {
+ super(message, {
+ code: ToolErrorCodes.TOOL_NOT_FOUND,
+ meta,
+ possibleFixes: ['Ensure the tool slug is correct and exists in the Composio project'],
+ });
+ this.name = 'ComposioToolNotFoundError';
+ }
+}
+
+export class ComposioInvalidModifierError extends ComposioError {
+ constructor(message: string = 'Invalid modifier', meta: Record<string, unknown> = {}) {
+ super(message, {
+ code: ToolErrorCodes.INVALID_MODIFIER,
+ meta,
+ possibleFixes: ['Ensure the modifier is a function and returns a valid result'],
+ });
+ this.name = 'ComposioInvalidModifierError';
+ }
+}
+
+export class ComposioCustomToolsNotInitializedError extends ComposioError {
+ constructor(
+ message: string = 'Custom tools not initialized',
+ meta: Record<string, unknown> = {}
+ ) {
+ super(message, {
+ code: ToolErrorCodes.CUSTOM_TOOLS_NOT_INITIALIZED,
+ meta,
+ possibleFixes: ['Ensure the custom tools class is initialized in the Tools instance'],
+ });
+ this.name = 'ComposioCustomToolsNotInitializedError';
+ }
+}
+
+export class ComposioToolExecutionError extends ComposioError {
+ public readonly error: Error;
+ constructor(
+ error: Error,
+ message: string = 'Tool execution error',
+ meta: Record<string, unknown> = {}
+ ) {
+ super(message, {
+ code: ToolErrorCodes.TOOL_EXECUTION_ERROR,
+ cause: error,
+ meta,
+ possibleFixes: ['Ensure the tool is correctly configured and the input is valid'],
+ });
+
+ this.error = error;
+ this.name = 'ComposioToolExecutionError';
+ }
+}
+
+export class ComposioInvalidExecuteFunctionError extends ComposioError {
+ constructor(message: string = 'Invalid execute function', meta: Record<string, unknown> = {}) {
+ super(message, {
+ code: ToolErrorCodes.INVALID_EXECUTE_FUNCTION,
+ meta,
+ possibleFixes: ['Ensure the execute function is a valid function and returns a valid result'],
+ });
+ this.name = 'ComposioInvalidExecuteFunctionError';
+ }
+}
diff --git a/packages/core/src/errors/ToolkitErrors.ts b/packages/core/src/errors/ToolkitErrors.ts
new file mode 100644
index 000000000..afc73ddfb
--- /dev/null
+++ b/packages/core/src/errors/ToolkitErrors.ts
@@ -0,0 +1,16 @@
+import { ComposioError } from './ComposioError';
+
+export const ToolkitErrorCodes = {
+ TOOLKIT_NOT_FOUND: 'TOOLKIT_NOT_FOUND',
+} as const;
+
+export class ToolkitNotFoundError extends ComposioError {
+ constructor(message: string = 'Toolkit not found', meta: Record<string, unknown> = {}) {
+ super(message, {
+ code: 'TOOLKIT_NOT_FOUND',
+ statusCode: 404,
+ meta,
+ possibleFixes: ['Ensure the toolkit is correctly configured and the slug is valid'],
+ });
+ }
+}
diff --git a/packages/core/src/errors/ValidationError.ts b/packages/core/src/errors/ValidationError.ts
new file mode 100644
index 000000000..fb9735aff
--- /dev/null
+++ b/packages/core/src/errors/ValidationError.ts
@@ -0,0 +1,44 @@
+// packages/core/src/errors/ValidationError.ts
+
+import { ZodError } from 'zod';
+import { ComposioError } from './ComposioError';
+import { error } from 'console';
+
+/**
+ * Represents an input validation error using Zod.
+ */
+export const ValidationErrorCodes = {
+ VALIDATION_ERROR: 'VALIDATION_ERROR',
+} as const;
+
+export class ValidationError extends ComposioError {
+ public readonly zodError: ZodError;
+
+ constructor(zodError: ZodError, message = 'Input validation failed') {
+ // check if it is a zod error, or else fallback to a generic error
+ let zodErrorInstance: ZodError;
+ if (!(zodError instanceof ZodError)) {
+ zodErrorInstance = new ZodError([
+ {
+ path: [],
+ message: 'Invalid input',
+ code: 'custom',
+ },
+ ]);
+ } else {
+ zodErrorInstance = zodError;
+ }
+ super(message, {
+ code: ValidationErrorCodes.VALIDATION_ERROR,
+ meta: {
+ issues: zodErrorInstance.issues.map(issue => ({
+ path: issue.path.join('.'),
+ message: issue.message,
+ code: issue.code,
+ })),
+ },
+ cause: zodErrorInstance,
+ });
+ this.zodError = zodErrorInstance;
+ }
+}
diff --git a/packages/core/src/models/AuthConfigs.ts b/packages/core/src/models/AuthConfigs.ts
index 36f792990..6cfacc305 100644
--- a/packages/core/src/models/AuthConfigs.ts
+++ b/packages/core/src/models/AuthConfigs.ts
@@ -5,7 +5,7 @@
* @date 2025-05-05
* @module AuthConfigs
*/
-import ComposioClient from '@composio/client';
+import ComposioClient, { ComposioError } from '@composio/client';
import {
AuthConfigRetrieveResponse as ComposioAuthConfigRetrieveResponse,
AuthConfigDeleteResponse,
@@ -25,6 +25,8 @@ import {
CreateAuthConfigResponse,
CreateAuthConfigResponseSchema,
} from '../types/authConfigs.types';
+import { ZodError } from 'zod';
+import { ValidationError } from '../errors/ValidationError';
/**
* AuthConfigs class
@@ -42,7 +44,7 @@ export class AuthConfigs {
private parseAuthConfigRetrieveResponse(
authConfig: ComposioAuthConfigRetrieveResponse
): AuthConfigRetrieveResponse {
- return AuthConfigRetrieveResponseSchema.parse({
+ const result = AuthConfigRetrieveResponseSchema.safeParse({
id: authConfig.id,
name: authConfig.name,
noOfConnections: authConfig.no_of_connections,
@@ -60,6 +62,10 @@ export class AuthConfigs {
createdAt: authConfig.created_at,
lastUpdatedAt: authConfig.last_updated_at,
});
+ if (result.error) {
+ throw new ValidationError(result.error);
+ }
+ return result.data;
}
/**
@@ -76,11 +82,15 @@ export class AuthConfigs {
limit: parsedQuery?.limit?.toString(),
toolkit_slug: parsedQuery?.toolkitSlug,
});
- return AuthConfigListResponseSchema.parse({
+ const parsedResult = AuthConfigListResponseSchema.safeParse({
items: result.items.map(item => this.parseAuthConfigRetrieveResponse(item)),
nextCursor: result.next_cursor,
totalPages: result.total_pages,
});
+ if (parsedResult.error) {
+ throw new ValidationError(parsedResult.error);
+ }
+ return parsedResult.data;
}
/**
@@ -105,19 +115,26 @@ export class AuthConfigs {
toolkit: string,
options: CreateAuthConfigParams
): Promise<CreateAuthConfigResponse> {
- const parsedOptions = CreateAuthConfigParamsSchema.parse(options);
+ const parsedOptions = CreateAuthConfigParamsSchema.safeParse(options);
+ if (parsedOptions.error) {
+ throw new ValidationError(parsedOptions.error);
+ }
const result = await this.client.authConfigs.create({
toolkit: {
slug: toolkit,
},
- auth_config: parsedOptions,
+ auth_config: parsedOptions.data,
});
- return CreateAuthConfigResponseSchema.parse({
+ const parsedResult = CreateAuthConfigResponseSchema.safeParse({
id: result.auth_config.id,
authScheme: result.auth_config.auth_scheme,
isComposioManaged: result.auth_config.is_composio_managed,
toolkit: result.toolkit.slug,
});
+ if (parsedResult.error) {
+ throw new ValidationError(parsedResult.error);
+ }
+ return parsedResult.data;
}
/**
diff --git a/packages/core/src/models/ConnectionRequest.ts b/packages/core/src/models/ConnectionRequest.ts
index 1a7514463..2d60551c7 100644
--- a/packages/core/src/models/ConnectionRequest.ts
+++ b/packages/core/src/models/ConnectionRequest.ts
@@ -15,6 +15,7 @@ import {
import { ConnectedAccountRetrieveResponse as OriginalConnectedAccountResponse } from '@composio/client/resources/connected-accounts';
import { ZodError } from 'zod';
import logger from '../utils/logger';
+import { ConnectionRequestTimeoutError } from '../errors/ConnectionRequestError';
export class ConnectionRequest {
private client: ComposioClient;
private connectedAccountId: string;
@@ -92,7 +93,11 @@ export class ConnectionRequest {
setTimeout(() => {
clearInterval(interval);
- reject(new Error('Connection request timed out'));
+ reject(
+ new ConnectionRequestTimeoutError(
+ `Connection request timed out for ${this.connectedAccountId}`
+ )
+ );
}, timeout);
});
}
diff --git a/packages/core/src/models/CustomTools.ts b/packages/core/src/models/CustomTools.ts
index 6f5a121cc..120252d9c 100644
--- a/packages/core/src/models/CustomTools.ts
+++ b/packages/core/src/models/CustomTools.ts
@@ -18,6 +18,12 @@ import zodToJsonSchema from 'zod-to-json-schema';
import { Tool, ToolExecuteResponse, ToolList } from '../types/tool.types';
import { ToolProxyParams } from '@composio/client/resources/tools';
import logger from '../utils/logger';
+import {
+ ComposioInvalidExecuteFunctionError,
+ ComposioToolNotFoundError,
+} from '../errors/ToolErrors';
+import { ComposioConnectedAccountNotFoundError } from '../errors/ConnectedAccountsError';
+import { ComposioError } from '../errors/ComposioError';
export class CustomTools {
private readonly client: ComposioClient;
@@ -25,7 +31,7 @@ export class CustomTools {
constructor(client: ComposioClient) {
if (!client) {
- throw new Error('ComposioClient is required');
+ throw new ComposioError('ComposioClient is required');
}
this.client = client;
this.customToolsRegistry = new Map();
@@ -125,13 +131,25 @@ export class CustomTools {
* @returns {ConnectedAccount} The connected account
*/
private async getConnectedAccount(toolkitSlug: string, metadata: ExecuteMetadata) {
+ try {
+ await this.client.toolkits.retrieve(toolkitSlug);
+ } catch (error) {
+ throw new ComposioToolNotFoundError(`Toolkit with slug ${toolkitSlug} not found`, {
+ toolkitSlug,
+ });
+ }
const connectedAccounts = await this.client.connectedAccounts.list({
toolkit_slug: toolkitSlug,
user_id: metadata.userId,
});
if (!connectedAccounts.items.length) {
- throw new Error(`No connected accounts found for toolkit ${toolkitSlug}`);
+ throw new ComposioConnectedAccountNotFoundError(
+ `No connected accounts found for toolkit ${toolkitSlug}`,
+ {
+ toolkitSlug,
+ }
+ );
}
return metadata.connectedAccountId
@@ -153,24 +171,32 @@ export class CustomTools {
): Promise<ToolExecuteResponse> {
const tool = this.customToolsRegistry.get(slug.toLowerCase());
if (!tool) {
- throw new Error(`Tool with slug ${slug} not found`);
+ throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`, {
+ toolSlug: slug,
+ });
}
let authCredentials: Record<string, unknown> = {};
const { toolkitSlug, execute } = tool.options;
// if a toolkit is used, get the connected account, and auth credentials
- if (toolkitSlug) {
+ if (toolkitSlug && toolkitSlug !== 'custom') {
const connectedAccount = await this.getConnectedAccount(toolkitSlug, metadata);
if (!connectedAccount) {
- throw new Error(
- `Connected account not found for toolkit ${toolkitSlug} for user ${metadata.userId}`
+ throw new ComposioConnectedAccountNotFoundError(
+ `Connected account not found for toolkit ${toolkitSlug} for user ${metadata.userId}`,
+ {
+ toolkitSlug,
+ userId: metadata.userId,
+ }
);
}
authCredentials = connectedAccount.data?.connectionParams as Record<string, unknown>;
}
if (typeof execute !== 'function') {
- throw new Error('Invalid execute function');
+ throw new ComposioInvalidExecuteFunctionError('Invalid execute function', {
+ toolSlug: slug,
+ });
}
// create a tool proxy request for users to execute in case of a toolkit being used
const executeToolRequest = async (data: ToolProxyParams) => {
diff --git a/packages/core/src/models/Toolkits.ts b/packages/core/src/models/Toolkits.ts
index c089a349a..48cfa038a 100644
--- a/packages/core/src/models/Toolkits.ts
+++ b/packages/core/src/models/Toolkits.ts
@@ -1,4 +1,4 @@
-import ComposioClient from '@composio/client';
+import ComposioClient, { ComposioError } from '@composio/client';
import {
ToolKitItemSchema,
ToolkitListParams,
@@ -11,6 +11,9 @@ import {
ToolkitRetrieveCategoriesResponseSchema,
ToolkitCategorySchema,
} from '../types/toolkit.types';
+import { ComposioToolNotFoundError } from '../errors/ToolErrors';
+import { ZodError } from 'zod';
+import { ValidationError } from '../errors/ValidationError';
/**
* Toolkits class
@@ -66,16 +69,25 @@ export class Toolkits {
* @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
*/
private async getToolkitBySlug(slug: string): Promise<ToolkitRetrieveResponse> {
- const result = await this.client.toolkits.retrieve(slug);
- const parsedResult = ToolkitRetrieveResponseSchema.parse({
- name: result.name,
- slug: result.slug,
- meta: result.meta,
- isLocalToolkit: result.is_local_toolkit,
- composioManagedAuthSchemes: result.composio_managed_auth_schemes,
- authConfigDetails: result.auth_config_details,
- });
- return parsedResult;
+ try {
+ const result = await this.client.toolkits.retrieve(slug);
+ const parsedResult = ToolkitRetrieveResponseSchema.parse({
+ name: result.name,
+ slug: result.slug,
+ meta: result.meta,
+ isLocalToolkit: result.is_local_toolkit,
+ composioManagedAuthSchemes: result.composio_managed_auth_schemes,
+ authConfigDetails: result.auth_config_details,
+ });
+ return parsedResult;
+ } catch (error) {
+ if (error instanceof ZodError) {
+ throw new ValidationError(error);
+ }
+ throw new ComposioToolNotFoundError(`Toolkit with slug ${slug} not found`, {
+ slug,
+ });
+ }
}
/**
diff --git a/packages/core/src/models/Tools.ts b/packages/core/src/models/Tools.ts
index 3324b104e..49e56d7bc 100644
--- a/packages/core/src/models/Tools.ts
+++ b/packages/core/src/models/Tools.ts
@@ -29,6 +29,14 @@ import {
import { BaseComposioToolset } from '../toolset/BaseToolset';
import logger from '../utils/logger';
import { ExecuteToolFn } from '../types/toolset.types';
+import {
+ ComposioCustomToolsNotInitializedError,
+ ComposioInvalidModifierError,
+ ComposioToolExecutionError,
+ ComposioToolNotFoundError,
+ ComposioToolsetNotDefinedError,
+} from '../errors/ToolErrors';
+import { ValidationError } from '../errors/ValidationError';
/**
* This class is used to manage tools in the Composio SDK.
@@ -48,7 +56,7 @@ export class Tools<
throw new Error('ComposioClient is required');
}
if (!toolset) {
- throw new Error('Toolset is required');
+ throw new ComposioToolsetNotDefinedError('Toolset not passed into Tools instance');
}
this.client = client;
@@ -202,7 +210,7 @@ export class Tools<
): Promise<ToolList> {
const queryParams = ToolListParamsSchema.safeParse(query);
if (queryParams.error) {
- throw new Error(JSON.stringify(queryParams.error.flatten()));
+ throw new ValidationError(queryParams.error);
}
const tools = await this.client.tools.list({
@@ -240,7 +248,7 @@ export class Tools<
return modifier(tool.slug, tool.toolkit?.slug || 'unkown', tool);
});
} else {
- throw new Error('Invalid schema modifier. Not a function.');
+ throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
}
}
@@ -265,7 +273,7 @@ export class Tools<
// if not, fetch the tool from the Composio API
const tool = await this.client.tools.retrieve(slug);
if (!tool) {
- throw new Error(`Tool with slug ${slug} not found`);
+ throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);
}
// change the case of the tool to camel case
let modifiedToool = this.transformToolCases(tool);
@@ -274,7 +282,7 @@ export class Tools<
if (typeof modifier === 'function') {
modifiedToool = modifier(slug, modifiedToool.toolkit?.slug || 'unkown', modifiedToool);
} else {
- throw new Error('Invalid schema modifier. Not a function.');
+ throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
}
}
return modifiedToool;
@@ -338,7 +346,9 @@ export class Tools<
if (typeof modifiers.beforeToolExecute === 'function') {
body = modifiers.beforeToolExecute(tool.slug, 'unkown', body);
} else {
- throw new Error('Invalid beforeToolExecute modifier. Not a function.');
+ throw new ComposioInvalidModifierError(
+ 'Invalid beforeToolExecute modifier. Not a function.'
+ );
}
}
@@ -350,6 +360,10 @@ export class Tools<
if (modifiers?.afterToolExecute) {
if (typeof modifiers.afterToolExecute === 'function') {
result = modifiers.afterToolExecute(tool.slug, 'unkown', result);
+ } else {
+ throw new ComposioInvalidModifierError(
+ 'Invalid afterToolExecute modifier. Not a function.'
+ );
}
}
@@ -365,7 +379,9 @@ export class Tools<
if (typeof modifiers.beforeToolExecute === 'function') {
body = modifiers.beforeToolExecute(tool.slug, tool.toolkit?.slug || 'unkown', body);
} else {
- throw new Error('Invalid beforeToolExecute modifier. Not a function.');
+ throw new ComposioInvalidModifierError(
+ 'Invalid beforeToolExecute modifier. Not a function.'
+ );
}
}
// fetch connected accounts if doesn't exist
@@ -392,7 +408,9 @@ export class Tools<
if (typeof modifiers.afterToolExecute === 'function') {
result = modifiers.afterToolExecute(tool.slug, tool.toolkit?.slug || 'unkown', result);
} else {
- throw new Error('Invalid afterToolExecute modifier. Not a function.');
+ throw new ComposioInvalidModifierError(
+ 'Invalid afterToolExecute modifier. Not a function.'
+ );
}
}
return result;
@@ -413,7 +431,7 @@ export class Tools<
modifiers?: ExecuteToolModifiers
): Promise<ToolExecuteResponse> {
if (!this.customTools) {
- throw new Error(
+ throw new ComposioCustomToolsNotInitializedError(
'CustomTools not initialized. Make sure Tools class is properly constructed.'
);
}
@@ -427,13 +445,15 @@ export class Tools<
// handle composio tool execution
const composioTool = await this.getComposioToolBySlug(body.userId, slug);
if (!composioTool) {
- throw new Error(`Tool with slug ${slug} not found`);
+ throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);
}
return this.handleComposioToolExecution(composioTool, body, modifiers);
}
} catch (error) {
- logger.error(`Error executing tool ${slug}: ${error}`);
- throw error;
+ throw new ComposioToolExecutionError(error as Error, `Error executing tool ${slug}`, {
+ toolSlug: slug,
+ body,
+ });
}
}
diff --git a/packages/core/src/utils/error.ts b/packages/core/src/utils/error.ts
deleted file mode 100644
index 189e3eae9..000000000
--- a/packages/core/src/utils/error.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { ZodError } from 'zod';
-
-export class ComposioError extends Error {
- private error: Error;
-
- constructor(messageOrError: string | unknown, error?: unknown) {
- let message: string;
- let err: Error;
-
- if (error instanceof ZodError) {
- const formattedMessage = error.errors
- .map(e => `Path: ${e.path.join('.') || '(root)'} - ${e.message}`)
- .join('; ');
- message = `${messageOrError}: ${formattedMessage}`;
- err = error;
- } else {
- message = typeof messageOrError === 'string' ? messageOrError : String(messageOrError);
- err = error as Error;
- }
-
- super(message);
- this.error = err;
-
- // Capture the stack trace of the caller
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, ComposioError);
- }
- }
-
- /**
- * Static method to handle Zod errors.
- * If the provided error is a ZodError, it formats the error message and returns a new ComposioError.
- * Otherwise, it returns a new ComposioError with the original message and error.
- */
- static fromZodError(message: string, error: unknown): ComposioError {
- if (error instanceof ZodError) {
- const formattedMessage = error.errors
- .map(e => `Path: ${e.path.join('.') || '(root)'} - ${e.message}`)
- .join('; ');
- return new ComposioError(`${message}: ${formattedMessage}`, error);
- }
- return new ComposioError(message, error as Error);
- }
-}
diff --git a/packages/core/src/utils/logger.ts b/packages/core/src/utils/logger.ts
index 4a0e2db0b..7ee6779ad 100644
--- a/packages/core/src/utils/logger.ts
+++ b/packages/core/src/utils/logger.ts
@@ -1,4 +1,4 @@
-import { getEnvVariable } from "./env";
+import { getEnvVariable } from './env';
// Define log levels with corresponding priorities
export const LOG_LEVELS = {
@@ -17,13 +17,8 @@ export type LogLevel = keyof typeof LOG_LEVELS;
* @returns {LogLevel} The current log level
*/
export const getLogLevel = (): LogLevel => {
- const envLevel = getEnvVariable(
- "COMPOSIO_LOGGING_LEVEL",
- "info"
- )?.toLowerCase();
- return envLevel && envLevel in LOG_LEVELS
- ? (envLevel as LogLevel)
- : "info";
+ const envLevel = getEnvVariable('COMPOSIO_LOGGING_LEVEL', 'info')?.toLowerCase();
+ return envLevel && envLevel in LOG_LEVELS ? (envLevel as LogLevel) : 'info';
};
interface LoggerOptions {
@@ -44,8 +39,8 @@ class Logger {
private formatMessage(args: unknown[]): string {
const formattedArgs = args
- .map((arg) => (typeof arg === "object" ? JSON.stringify(arg) : String(arg)))
- .join(" ");
+ .map(arg => (typeof arg === 'object' ? JSON.stringify(arg) : String(arg)))
+ .join('\n');
if (!this.includeTimestamp) {
return formattedArgs;
@@ -60,25 +55,25 @@ class Logger {
}
error(...args: unknown[]): void {
- if (this.shouldLog("error")) {
+ if (this.shouldLog('error')) {
this.console.error(this.formatMessage(args));
}
}
warn(...args: unknown[]): void {
- if (this.shouldLog("warn")) {
+ if (this.shouldLog('warn')) {
this.console.warn(this.formatMessage(args));
}
}
info(...args: unknown[]): void {
- if (this.shouldLog("info")) {
+ if (this.shouldLog('info')) {
this.console.info(this.formatMessage(args));
}
}
debug(...args: unknown[]): void {
- if (this.shouldLog("debug")) {
+ if (this.shouldLog('debug')) {
this.console.debug(this.formatMessage(args));
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c5fe1d836..3de393ebb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -130,6 +130,28 @@ importers:
specifier: ^5.8.3
version: 5.8.3
+ examples/toolkits:
+ dependencies:
+ '@ai-sdk/openai':
+ specifier: ^1.3.16
+ version: 1.3.22([email protected])
+ '@composio/core':
+ specifier: workspace:*
+ version: link:../../packages/core
+ '@composio/vercel':
+ specifier: workspace:*
+ version: link:../../packages/toolsets/vercel
+ ai:
+ specifier: ^4.3.8
+ devDependencies:
+ '@types/bun':
+ specifier: ^1.2.9
+ version: 1.2.13
+ typescript:
+ specifier: ^5.8.3
+ version: 5.8.3
+
examples/vercel:
dependencies:
'@ai-sdk/openai':