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
haxzie committed
May 16, 2025 at 17:13 UTC
a09ab158632713d5191a6334220eceba49dedf2b
20 files changed
+507
-99
examples/pre-processors/src/index.ts
+3
-4
@@ -8,10 +8,6 @@ const composio = new Composio({
8
apiKey: process.env.COMPOSIO_API_KEY,
9
});
10
11
-const toolkit = await composio.toolkits.get('HACKERNEWS');
12
-
13
-console.log(toolkit);
14
-
11
const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER', {
12
// toolkit slug too
13
modifyToolSchema: (toolSlug, toolkitSlug, toolSchema) => {
@@ -34,6 +30,9 @@ const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER', {
30
31
console.log(tools);
32
33
+/**
34
+ * Agentic toolset
35
+ */
36
const vercel = new Composio({
37
apiKey: process.env.COMPOSIO_API_KEY,
38
// calling this provider now no? or what? or toolProvider or toolManager?
examples/toolkits/.env.example
new
+2
@@ -0,0 +1,2 @@
1
+COMPOSIO_API_KEY=
2
+OPENAI_API_KEY=
\ No newline at end of file
examples/toolkits/README.md
new
+69
@@ -0,0 +1,69 @@
1
+# Vercel Example with Composio SDK
2
+
3
+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.
4
+
5
+## Features
6
+
7
+- Integration with Composio SDK and Vercel AI SDK
8
+- HackerNews front page summarization using GPT-4
9
+- Streaming AI responses
10
+- TypeScript support
11
+
12
+## Prerequisites
13
+
14
+- [Node.js](https://nodejs.org/) (Latest LTS version recommended)
15
+- [pnpm](https://pnpm.io/) (v10.8.0 or later)
16
+- Composio API Key
17
+- OpenAI API Key
18
+
19
+## Getting Started
20
+
21
+1. Clone the repository and navigate to the example directory:
22
+```bash
23
+cd examples/vercel
24
+```
25
+
26
+2. Install dependencies:
27
+```bash
28
+pnpm install
29
+```
30
+
31
+3. Copy the `.env.example` file to `.env` and fill in your API keys:
32
+```bash
33
+cp .env.example .env
34
+```
35
+
36
+4. Update the `.env` file with your credentials:
37
+```env
38
+COMPOSIO_API_KEY=your_composio_api_key
39
+OPENAI_API_KEY=your_openai_api_key
40
+```
41
+
42
+5. Start the development server:
43
+```bash
44
+pnpm start
45
+```
46
+
47
+## How It Works
48
+
49
+This example showcases how to:
50
+1. Initialize the Composio SDK with the Vercel toolset
51
+2. Use the HackerNews tool to fetch front page data
52
+3. Generate AI responses using OpenAI's GPT-4
53
+4. Handle tool calls and results in a chat-like interface
54
+
55
+## Dependencies
56
+
57
+- `@composio/core`: Core Composio SDK
58
+- `@composio/vercel`: Vercel integration for Composio
59
+- `@ai-sdk/openai`: OpenAI integration
60
+- `ai`: Vercel's AI SDK
61
+- TypeScript for type safety
62
+
63
+## License
64
+
65
+ISC
66
+
67
+## Support
68
+
69
+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
examples/toolkits/package.json
new
+25
@@ -0,0 +1,25 @@
1
+{
2
+ "name": "modifiers-example",
3
+ "private": true,
4
+ "version": "0.1.6-alpha.0",
5
+ "description": "",
6
+ "main": "src/index.ts",
7
+ "scripts": {
8
+ "start": "bun src/index.ts",
9
+ "test": "echo \"Error: no test specified\" && exit 1"
10
+ },
11
+ "keywords": [],
12
+ "author": "",
13
+ "license": "ISC",
14
+ "packageManager": "pnpm@10.8.0",
15
+ "dependencies": {
16
+ "@ai-sdk/openai": "^1.3.16",
17
+ "@composio/core": "workspace:*",
18
+ "@composio/vercel": "workspace:*",
19
+ "ai": "^4.3.8"
20
+ },
21
+ "devDependencies": {
22
+ "@types/bun": "^1.2.9",
23
+ "typescript": "^5.8.3"
24
+ }
25
+}
examples/toolkits/src/index.ts
new
+9
@@ -0,0 +1,9 @@
1
+import { Composio } from '@composio/core';
2
+
3
+const composio = new Composio({
4
+ apiKey: process.env.COMPOSIO_API_KEY,
5
+});
6
+
7
+const toolkit = await composio.toolkits.get('modifiers-example');
8
+
9
+console.log(toolkit);
examples/toolkits/tsconfig.json
new
+15
@@ -0,0 +1,15 @@
1
+{
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "ESNext",
5
+ "declaration": true,
6
+ "declarationDir": "./dist",
7
+ "outDir": "./dist",
8
+ "rootDir": "./src",
9
+ "strict": true,
10
+ "esModuleInterop": true,
11
+ "moduleResolution": "node",
12
+ "skipLibCheck": true
13
+ },
14
+ "include": ["src"]
15
+}
packages/core/src/errors/ComposioError.ts
new
+51
@@ -0,0 +1,51 @@
1
+/**
2
+ * @fileoverview Error class for Composio.
3
+ *
4
+ * This error class is used to create custom errors for Composio.
5
+ * It extends the built-in Error class and adds additional properties for code, status code, cause, meta, and possible fixes.
6
+ *
7
+ * @author Musthaq Ahamad <musthaq@composio.dev>
8
+ * @module errors/ComposioError
9
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error}
10
+ */
11
+export type ComposioErrorOptions = {
12
+ code?: string;
13
+ statusCode?: number;
14
+ cause?: unknown;
15
+ meta?: Record<string, unknown>;
16
+ possibleFixes?: string[];
17
+};
18
+export class ComposioError extends Error {
19
+ public name = 'ComposioError';
20
+ public readonly code?: string;
21
+ public readonly statusCode?: number;
22
+ public readonly cause?: unknown;
23
+ public readonly meta?: Record<string, unknown>;
24
+ public readonly possibleFixes?: string[];
25
+
26
+ constructor(message: string, options: ComposioErrorOptions = {}) {
27
+ super(message);
28
+ this.code = options.code;
29
+ this.statusCode = options.statusCode;
30
+ this.cause = options.cause;
31
+ this.meta = options.meta;
32
+ this.possibleFixes = options.possibleFixes;
33
+
34
+ // Captures stack trace excluding the constructor frame
35
+ if (Error.captureStackTrace) {
36
+ Error.captureStackTrace(this, this.constructor);
37
+ }
38
+ }
39
+
40
+ toJSON() {
41
+ return {
42
+ name: this.name,
43
+ message: this.message,
44
+ code: this.code,
45
+ statusCode: this.statusCode,
46
+ cause: this.cause instanceof Error ? this.cause.message : this.cause,
47
+ meta: this.meta,
48
+ possibleFixes: this.possibleFixes?.length ? this.possibleFixes.join('\n') : undefined,
49
+ };
50
+ }
51
+}
packages/core/src/errors/ConnectedAccountsError.ts
new
+18
@@ -0,0 +1,18 @@
1
+import { ComposioError } from './ComposioError';
2
+
3
+export const ConnectedAccountErrorCodes = {
4
+ CONNECTED_ACCOUNT_NOT_FOUND: 'CONNECTED_ACCOUNT_NOT_FOUND',
5
+} as const;
6
+
7
+export class ComposioConnectedAccountNotFoundError extends ComposioError {
8
+ constructor(message: string = 'Connected account not found', meta: Record<string, unknown> = {}) {
9
+ super(message, {
10
+ code: ConnectedAccountErrorCodes.CONNECTED_ACCOUNT_NOT_FOUND,
11
+ statusCode: 404,
12
+ meta,
13
+ possibleFixes: [
14
+ 'Ensure the connected account exists and is active in your Composio dashboard',
15
+ ],
16
+ });
17
+ }
18
+}
packages/core/src/errors/ConnectionRequestError.ts
new
+17
@@ -0,0 +1,17 @@
1
+import { ComposioError } from './ComposioError';
2
+
3
+export const ConnectionRequestErrorCodes = {
4
+ CONNECTION_REQUEST_TIMEOUT: 'CONNECTION_REQUEST_TIMEOUT',
5
+} as const;
6
+
7
+export class ConnectionRequestTimeoutError extends ComposioError {
8
+ constructor(
9
+ message: string = 'Connection request timed out',
10
+ meta: Record<string, unknown> = {}
11
+ ) {
12
+ super(message, {
13
+ code: ConnectionRequestErrorCodes.CONNECTION_REQUEST_TIMEOUT,
14
+ meta,
15
+ });
16
+ }
17
+}
packages/core/src/errors/ToolErrors.ts
new
+90
@@ -0,0 +1,90 @@
1
+import { ComposioError } from './ComposioError';
2
+import { ComposioError as ComposioClientError } from '@composio/client';
3
+
4
+export const ToolErrorCodes = {
5
+ TOOLSET_NOT_DEFINED: 'TOOLSET_NOT_DEFINED',
6
+ TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',
7
+ INVALID_MODIFIER: 'INVALID_MODIFIER',
8
+ CUSTOM_TOOLS_NOT_INITIALIZED: 'CUSTOM_TOOLS_NOT_INITIALIZED',
9
+ TOOL_EXECUTION_ERROR: 'TOOL_EXECUTION_ERROR',
10
+ INVALID_EXECUTE_FUNCTION: 'INVALID_EXECUTE_FUNCTION',
11
+} as const;
12
+
13
+export class ComposioToolsetNotDefinedError extends ComposioError {
14
+ constructor(message: string = 'Toolset not defined', meta: Record<string, unknown> = {}) {
15
+ super(message, {
16
+ code: ToolErrorCodes.TOOLSET_NOT_DEFINED,
17
+ meta,
18
+ possibleFixes: [
19
+ 'Ensure that the toolset is defined in the Composio project and passed into the tool instance',
20
+ ],
21
+ });
22
+ this.name = 'ComposioToolsetNotDefinedError';
23
+ }
24
+}
25
+
26
+export class ComposioToolNotFoundError extends ComposioError {
27
+ constructor(message: string = 'Tool not found', meta: Record<string, unknown> = {}) {
28
+ super(message, {
29
+ code: ToolErrorCodes.TOOL_NOT_FOUND,
30
+ meta,
31
+ possibleFixes: ['Ensure the tool slug is correct and exists in the Composio project'],
32
+ });
33
+ this.name = 'ComposioToolNotFoundError';
34
+ }
35
+}
36
+
37
+export class ComposioInvalidModifierError extends ComposioError {
38
+ constructor(message: string = 'Invalid modifier', meta: Record<string, unknown> = {}) {
39
+ super(message, {
40
+ code: ToolErrorCodes.INVALID_MODIFIER,
41
+ meta,
42
+ possibleFixes: ['Ensure the modifier is a function and returns a valid result'],
43
+ });
44
+ this.name = 'ComposioInvalidModifierError';
45
+ }
46
+}
47
+
48
+export class ComposioCustomToolsNotInitializedError extends ComposioError {
49
+ constructor(
50
+ message: string = 'Custom tools not initialized',
51
+ meta: Record<string, unknown> = {}
52
+ ) {
53
+ super(message, {
54
+ code: ToolErrorCodes.CUSTOM_TOOLS_NOT_INITIALIZED,
55
+ meta,
56
+ possibleFixes: ['Ensure the custom tools class is initialized in the Tools instance'],
57
+ });
58
+ this.name = 'ComposioCustomToolsNotInitializedError';
59
+ }
60
+}
61
+
62
+export class ComposioToolExecutionError extends ComposioError {
63
+ public readonly error: Error;
64
+ constructor(
65
+ error: Error,
66
+ message: string = 'Tool execution error',
67
+ meta: Record<string, unknown> = {}
68
+ ) {
69
+ super(message, {
70
+ code: ToolErrorCodes.TOOL_EXECUTION_ERROR,
71
+ cause: error,
72
+ meta,
73
+ possibleFixes: ['Ensure the tool is correctly configured and the input is valid'],
74
+ });
75
+
76
+ this.error = error;
77
+ this.name = 'ComposioToolExecutionError';
78
+ }
79
+}
80
+
81
+export class ComposioInvalidExecuteFunctionError extends ComposioError {
82
+ constructor(message: string = 'Invalid execute function', meta: Record<string, unknown> = {}) {
83
+ super(message, {
84
+ code: ToolErrorCodes.INVALID_EXECUTE_FUNCTION,
85
+ meta,
86
+ possibleFixes: ['Ensure the execute function is a valid function and returns a valid result'],
87
+ });
88
+ this.name = 'ComposioInvalidExecuteFunctionError';
89
+ }
90
+}
packages/core/src/errors/ToolkitErrors.ts
new
+16
@@ -0,0 +1,16 @@
1
+import { ComposioError } from './ComposioError';
2
+
3
+export const ToolkitErrorCodes = {
4
+ TOOLKIT_NOT_FOUND: 'TOOLKIT_NOT_FOUND',
5
+} as const;
6
+
7
+export class ToolkitNotFoundError extends ComposioError {
8
+ constructor(message: string = 'Toolkit not found', meta: Record<string, unknown> = {}) {
9
+ super(message, {
10
+ code: 'TOOLKIT_NOT_FOUND',
11
+ statusCode: 404,
12
+ meta,
13
+ possibleFixes: ['Ensure the toolkit is correctly configured and the slug is valid'],
14
+ });
15
+ }
16
+}
packages/core/src/errors/ValidationError.ts
new
+44
@@ -0,0 +1,44 @@
1
+// packages/core/src/errors/ValidationError.ts
2
+
3
+import { ZodError } from 'zod';
4
+import { ComposioError } from './ComposioError';
5
+import { error } from 'console';
6
+
7
+/**
8
+ * Represents an input validation error using Zod.
9
+ */
10
+export const ValidationErrorCodes = {
11
+ VALIDATION_ERROR: 'VALIDATION_ERROR',
12
+} as const;
13
+
14
+export class ValidationError extends ComposioError {
15
+ public readonly zodError: ZodError;
16
+
17
+ constructor(zodError: ZodError, message = 'Input validation failed') {
18
+ // check if it is a zod error, or else fallback to a generic error
19
+ let zodErrorInstance: ZodError;
20
+ if (!(zodError instanceof ZodError)) {
21
+ zodErrorInstance = new ZodError([
22
+ {
23
+ path: [],
24
+ message: 'Invalid input',
25
+ code: 'custom',
26
+ },
27
+ ]);
28
+ } else {
29
+ zodErrorInstance = zodError;
30
+ }
31
+ super(message, {
32
+ code: ValidationErrorCodes.VALIDATION_ERROR,
33
+ meta: {
34
+ issues: zodErrorInstance.issues.map(issue => ({
35
+ path: issue.path.join('.'),
36
+ message: issue.message,
37
+ code: issue.code,
38
+ })),
39
+ },
40
+ cause: zodErrorInstance,
41
+ });
42
+ this.zodError = zodErrorInstance;
43
+ }
44
+}
packages/core/src/models/AuthConfigs.ts
+23
-6
@@ -5,7 +5,7 @@
5
* @date 2025-05-05
6
* @module AuthConfigs
7
*/
8
-import ComposioClient from '@composio/client';
8
+import ComposioClient, { ComposioError } from '@composio/client';
9
import {
10
AuthConfigRetrieveResponse as ComposioAuthConfigRetrieveResponse,
11
AuthConfigDeleteResponse,
@@ -25,6 +25,8 @@ import {
25
CreateAuthConfigResponse,
26
CreateAuthConfigResponseSchema,
27
} from '../types/authConfigs.types';
28
+import { ZodError } from 'zod';
29
+import { ValidationError } from '../errors/ValidationError';
30
31
/**
32
* AuthConfigs class
@@ -42,7 +44,7 @@ export class AuthConfigs {
44
private parseAuthConfigRetrieveResponse(
45
authConfig: ComposioAuthConfigRetrieveResponse
46
): AuthConfigRetrieveResponse {
45
- return AuthConfigRetrieveResponseSchema.parse({
47
+ const result = AuthConfigRetrieveResponseSchema.safeParse({
48
id: authConfig.id,
49
name: authConfig.name,
50
noOfConnections: authConfig.no_of_connections,
@@ -60,6 +62,10 @@ export class AuthConfigs {
62
createdAt: authConfig.created_at,
63
lastUpdatedAt: authConfig.last_updated_at,
64
});
65
+ if (result.error) {
66
+ throw new ValidationError(result.error);
67
+ }
68
+ return result.data;
69
}
70
71
/**
@@ -76,11 +82,15 @@ export class AuthConfigs {
82
limit: parsedQuery?.limit?.toString(),
83
toolkit_slug: parsedQuery?.toolkitSlug,
84
});
79
- return AuthConfigListResponseSchema.parse({
85
+ const parsedResult = AuthConfigListResponseSchema.safeParse({
86
items: result.items.map(item => this.parseAuthConfigRetrieveResponse(item)),
87
nextCursor: result.next_cursor,
88
totalPages: result.total_pages,
89
});
90
+ if (parsedResult.error) {
91
+ throw new ValidationError(parsedResult.error);
92
+ }
93
+ return parsedResult.data;
94
}
95
96
/**
@@ -105,19 +115,26 @@ export class AuthConfigs {
115
toolkit: string,
116
options: CreateAuthConfigParams
117
): Promise<CreateAuthConfigResponse> {
108
- const parsedOptions = CreateAuthConfigParamsSchema.parse(options);
118
+ const parsedOptions = CreateAuthConfigParamsSchema.safeParse(options);
119
+ if (parsedOptions.error) {
120
+ throw new ValidationError(parsedOptions.error);
121
+ }
122
const result = await this.client.authConfigs.create({
123
toolkit: {
124
slug: toolkit,
125
},
113
- auth_config: parsedOptions,
126
+ auth_config: parsedOptions.data,
127
});
115
- return CreateAuthConfigResponseSchema.parse({
128
+ const parsedResult = CreateAuthConfigResponseSchema.safeParse({
129
id: result.auth_config.id,
130
authScheme: result.auth_config.auth_scheme,
131
isComposioManaged: result.auth_config.is_composio_managed,
132
toolkit: result.toolkit.slug,
133
});
134
+ if (parsedResult.error) {
135
+ throw new ValidationError(parsedResult.error);
136
+ }
137
+ return parsedResult.data;
138
}
139
140
/**
packages/core/src/models/ConnectionRequest.ts
+6
-1
@@ -15,6 +15,7 @@ import {
15
import { ConnectedAccountRetrieveResponse as OriginalConnectedAccountResponse } from '@composio/client/resources/connected-accounts';
16
import { ZodError } from 'zod';
17
import logger from '../utils/logger';
18
+import { ConnectionRequestTimeoutError } from '../errors/ConnectionRequestError';
19
export class ConnectionRequest {
20
private client: ComposioClient;
21
private connectedAccountId: string;
@@ -92,7 +93,11 @@ export class ConnectionRequest {
93
94
setTimeout(() => {
95
clearInterval(interval);
95
- reject(new Error('Connection request timed out'));
96
+ reject(
97
+ new ConnectionRequestTimeoutError(
98
+ `Connection request timed out for ${this.connectedAccountId}`
99
+ )
100
+ );
101
}, timeout);
102
});
103
}
packages/core/src/models/CustomTools.ts
+33
-7
@@ -18,6 +18,12 @@ import zodToJsonSchema from 'zod-to-json-schema';
18
import { Tool, ToolExecuteResponse, ToolList } from '../types/tool.types';
19
import { ToolProxyParams } from '@composio/client/resources/tools';
20
import logger from '../utils/logger';
21
+import {
22
+ ComposioInvalidExecuteFunctionError,
23
+ ComposioToolNotFoundError,
24
+} from '../errors/ToolErrors';
25
+import { ComposioConnectedAccountNotFoundError } from '../errors/ConnectedAccountsError';
26
+import { ComposioError } from '../errors/ComposioError';
27
28
export class CustomTools {
29
private readonly client: ComposioClient;
@@ -25,7 +31,7 @@ export class CustomTools {
31
32
constructor(client: ComposioClient) {
33
if (!client) {
28
- throw new Error('ComposioClient is required');
34
+ throw new ComposioError('ComposioClient is required');
35
}
36
this.client = client;
37
this.customToolsRegistry = new Map();
@@ -125,13 +131,25 @@ export class CustomTools {
131
* @returns {ConnectedAccount} The connected account
132
*/
133
private async getConnectedAccount(toolkitSlug: string, metadata: ExecuteMetadata) {
134
+ try {
135
+ await this.client.toolkits.retrieve(toolkitSlug);
136
+ } catch (error) {
137
+ throw new ComposioToolNotFoundError(`Toolkit with slug ${toolkitSlug} not found`, {
138
+ toolkitSlug,
139
+ });
140
+ }
141
const connectedAccounts = await this.client.connectedAccounts.list({
142
toolkit_slug: toolkitSlug,
143
user_id: metadata.userId,
144
});
145
146
if (!connectedAccounts.items.length) {
134
- throw new Error(`No connected accounts found for toolkit ${toolkitSlug}`);
147
+ throw new ComposioConnectedAccountNotFoundError(
148
+ `No connected accounts found for toolkit ${toolkitSlug}`,
149
+ {
150
+ toolkitSlug,
151
+ }
152
+ );
153
}
154
155
return metadata.connectedAccountId
@@ -153,24 +171,32 @@ export class CustomTools {
171
): Promise<ToolExecuteResponse> {
172
const tool = this.customToolsRegistry.get(slug.toLowerCase());
173
if (!tool) {
156
- throw new Error(`Tool with slug ${slug} not found`);
174
+ throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`, {
175
+ toolSlug: slug,
176
+ });
177
}
178
179
let authCredentials: Record<string, unknown> = {};
180
const { toolkitSlug, execute } = tool.options;
181
// if a toolkit is used, get the connected account, and auth credentials
162
- if (toolkitSlug) {
182
+ if (toolkitSlug && toolkitSlug !== 'custom') {
183
const connectedAccount = await this.getConnectedAccount(toolkitSlug, metadata);
184
if (!connectedAccount) {
165
- throw new Error(
166
- `Connected account not found for toolkit ${toolkitSlug} for user ${metadata.userId}`
185
+ throw new ComposioConnectedAccountNotFoundError(
186
+ `Connected account not found for toolkit ${toolkitSlug} for user ${metadata.userId}`,
187
+ {
188
+ toolkitSlug,
189
+ userId: metadata.userId,
190
+ }
191
);
192
}
193
authCredentials = connectedAccount.data?.connectionParams as Record<string, unknown>;
194
}
195
196
if (typeof execute !== 'function') {
173
- throw new Error('Invalid execute function');
197
+ throw new ComposioInvalidExecuteFunctionError('Invalid execute function', {
198
+ toolSlug: slug,
199
+ });
200
}
201
// create a tool proxy request for users to execute in case of a toolkit being used
202
const executeToolRequest = async (data: ToolProxyParams) => {
packages/core/src/models/Toolkits.ts
+23
-11
@@ -1,4 +1,4 @@
1
-import ComposioClient from '@composio/client';
1
+import ComposioClient, { ComposioError } from '@composio/client';
2
import {
3
ToolKitItemSchema,
4
ToolkitListParams,
@@ -11,6 +11,9 @@ import {
11
ToolkitRetrieveCategoriesResponseSchema,
12
ToolkitCategorySchema,
13
} from '../types/toolkit.types';
14
+import { ComposioToolNotFoundError } from '../errors/ToolErrors';
15
+import { ZodError } from 'zod';
16
+import { ValidationError } from '../errors/ValidationError';
17
18
/**
19
* Toolkits class
@@ -66,16 +69,25 @@ export class Toolkits {
69
* @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
70
*/
71
private async getToolkitBySlug(slug: string): Promise<ToolkitRetrieveResponse> {
69
- const result = await this.client.toolkits.retrieve(slug);
70
- const parsedResult = ToolkitRetrieveResponseSchema.parse({
71
- name: result.name,
72
- slug: result.slug,
73
- meta: result.meta,
74
- isLocalToolkit: result.is_local_toolkit,
75
- composioManagedAuthSchemes: result.composio_managed_auth_schemes,
76
- authConfigDetails: result.auth_config_details,
77
- });
78
- return parsedResult;
72
+ try {
73
+ const result = await this.client.toolkits.retrieve(slug);
74
+ const parsedResult = ToolkitRetrieveResponseSchema.parse({
75
+ name: result.name,
76
+ slug: result.slug,
77
+ meta: result.meta,
78
+ isLocalToolkit: result.is_local_toolkit,
79
+ composioManagedAuthSchemes: result.composio_managed_auth_schemes,
80
+ authConfigDetails: result.auth_config_details,
81
+ });
82
+ return parsedResult;
83
+ } catch (error) {
84
+ if (error instanceof ZodError) {
85
+ throw new ValidationError(error);
86
+ }
87
+ throw new ComposioToolNotFoundError(`Toolkit with slug ${slug} not found`, {
88
+ slug,
89
+ });
90
+ }
91
}
92
93
/**
packages/core/src/models/Tools.ts
+32
-12
@@ -29,6 +29,14 @@ import {
29
import { BaseComposioToolset } from '../toolset/BaseToolset';
30
import logger from '../utils/logger';
31
import { ExecuteToolFn } from '../types/toolset.types';
32
+import {
33
+ ComposioCustomToolsNotInitializedError,
34
+ ComposioInvalidModifierError,
35
+ ComposioToolExecutionError,
36
+ ComposioToolNotFoundError,
37
+ ComposioToolsetNotDefinedError,
38
+} from '../errors/ToolErrors';
39
+import { ValidationError } from '../errors/ValidationError';
40
41
/**
42
* This class is used to manage tools in the Composio SDK.
@@ -48,7 +56,7 @@ export class Tools<
56
throw new Error('ComposioClient is required');
57
}
58
if (!toolset) {
51
- throw new Error('Toolset is required');
59
+ throw new ComposioToolsetNotDefinedError('Toolset not passed into Tools instance');
60
}
61
62
this.client = client;
@@ -202,7 +210,7 @@ export class Tools<
210
): Promise<ToolList> {
211
const queryParams = ToolListParamsSchema.safeParse(query);
212
if (queryParams.error) {
205
- throw new Error(JSON.stringify(queryParams.error.flatten()));
213
+ throw new ValidationError(queryParams.error);
214
}
215
216
const tools = await this.client.tools.list({
@@ -240,7 +248,7 @@ export class Tools<
248
return modifier(tool.slug, tool.toolkit?.slug || 'unkown', tool);
249
});
250
} else {
243
- throw new Error('Invalid schema modifier. Not a function.');
251
+ throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
252
}
253
}
254
@@ -265,7 +273,7 @@ export class Tools<
273
// if not, fetch the tool from the Composio API
274
const tool = await this.client.tools.retrieve(slug);
275
if (!tool) {
268
- throw new Error(`Tool with slug ${slug} not found`);
276
+ throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);
277
}
278
// change the case of the tool to camel case
279
let modifiedToool = this.transformToolCases(tool);
@@ -274,7 +282,7 @@ export class Tools<
282
if (typeof modifier === 'function') {
283
modifiedToool = modifier(slug, modifiedToool.toolkit?.slug || 'unkown', modifiedToool);
284
} else {
277
- throw new Error('Invalid schema modifier. Not a function.');
285
+ throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
286
}
287
}
288
return modifiedToool;
@@ -338,7 +346,9 @@ export class Tools<
346
if (typeof modifiers.beforeToolExecute === 'function') {
347
body = modifiers.beforeToolExecute(tool.slug, 'unkown', body);
348
} else {
341
- throw new Error('Invalid beforeToolExecute modifier. Not a function.');
349
+ throw new ComposioInvalidModifierError(
350
+ 'Invalid beforeToolExecute modifier. Not a function.'
351
+ );
352
}
353
}
354
@@ -350,6 +360,10 @@ export class Tools<
360
if (modifiers?.afterToolExecute) {
361
if (typeof modifiers.afterToolExecute === 'function') {
362
result = modifiers.afterToolExecute(tool.slug, 'unkown', result);
363
+ } else {
364
+ throw new ComposioInvalidModifierError(
365
+ 'Invalid afterToolExecute modifier. Not a function.'
366
+ );
367
}
368
}
369
@@ -365,7 +379,9 @@ export class Tools<
379
if (typeof modifiers.beforeToolExecute === 'function') {
380
body = modifiers.beforeToolExecute(tool.slug, tool.toolkit?.slug || 'unkown', body);
381
} else {
368
- throw new Error('Invalid beforeToolExecute modifier. Not a function.');
382
+ throw new ComposioInvalidModifierError(
383
+ 'Invalid beforeToolExecute modifier. Not a function.'
384
+ );
385
}
386
}
387
// fetch connected accounts if doesn't exist
@@ -392,7 +408,9 @@ export class Tools<
408
if (typeof modifiers.afterToolExecute === 'function') {
409
result = modifiers.afterToolExecute(tool.slug, tool.toolkit?.slug || 'unkown', result);
410
} else {
395
- throw new Error('Invalid afterToolExecute modifier. Not a function.');
411
+ throw new ComposioInvalidModifierError(
412
+ 'Invalid afterToolExecute modifier. Not a function.'
413
+ );
414
}
415
}
416
return result;
@@ -413,7 +431,7 @@ export class Tools<
431
modifiers?: ExecuteToolModifiers
432
): Promise<ToolExecuteResponse> {
433
if (!this.customTools) {
416
- throw new Error(
434
+ throw new ComposioCustomToolsNotInitializedError(
435
'CustomTools not initialized. Make sure Tools class is properly constructed.'
436
);
437
}
@@ -427,13 +445,15 @@ export class Tools<
445
// handle composio tool execution
446
const composioTool = await this.getComposioToolBySlug(body.userId, slug);
447
if (!composioTool) {
430
- throw new Error(`Tool with slug ${slug} not found`);
448
+ throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);
449
}
450
return this.handleComposioToolExecution(composioTool, body, modifiers);
451
}
452
} catch (error) {
435
- logger.error(`Error executing tool ${slug}: ${error}`);
436
- throw error;
453
+ throw new ComposioToolExecutionError(error as Error, `Error executing tool ${slug}`, {
454
+ toolSlug: slug,
455
+ body,
456
+ });
457
}
458
}
459
packages/core/src/utils/error.ts
deleted
-44
@@ -1,44 +0,0 @@
1
-import { ZodError } from 'zod';
2
-
3
-export class ComposioError extends Error {
4
- private error: Error;
5
-
6
- constructor(messageOrError: string | unknown, error?: unknown) {
7
- let message: string;
8
- let err: Error;
9
-
10
- if (error instanceof ZodError) {
11
- const formattedMessage = error.errors
12
- .map(e => `Path: ${e.path.join('.') || '(root)'} - ${e.message}`)
13
- .join('; ');
14
- message = `${messageOrError}: ${formattedMessage}`;
15
- err = error;
16
- } else {
17
- message = typeof messageOrError === 'string' ? messageOrError : String(messageOrError);
18
- err = error as Error;
19
- }
20
-
21
- super(message);
22
- this.error = err;
23
-
24
- // Capture the stack trace of the caller
25
- if (Error.captureStackTrace) {
26
- Error.captureStackTrace(this, ComposioError);
27
- }
28
- }
29
-
30
- /**
31
- * Static method to handle Zod errors.
32
- * If the provided error is a ZodError, it formats the error message and returns a new ComposioError.
33
- * Otherwise, it returns a new ComposioError with the original message and error.
34
- */
35
- static fromZodError(message: string, error: unknown): ComposioError {
36
- if (error instanceof ZodError) {
37
- const formattedMessage = error.errors
38
- .map(e => `Path: ${e.path.join('.') || '(root)'} - ${e.message}`)
39
- .join('; ');
40
- return new ComposioError(`${message}: ${formattedMessage}`, error);
41
- }
42
- return new ComposioError(message, error as Error);
43
- }
44
-}
packages/core/src/utils/logger.ts
+9
-14
@@ -1,4 +1,4 @@
1
-import { getEnvVariable } from "./env";
1
+import { getEnvVariable } from './env';
2
3
// Define log levels with corresponding priorities
4
export const LOG_LEVELS = {
@@ -17,13 +17,8 @@ export type LogLevel = keyof typeof LOG_LEVELS;
17
* @returns {LogLevel} The current log level
18
*/
19
export const getLogLevel = (): LogLevel => {
20
- const envLevel = getEnvVariable(
21
- "COMPOSIO_LOGGING_LEVEL",
22
- "info"
23
- )?.toLowerCase();
24
- return envLevel && envLevel in LOG_LEVELS
25
- ? (envLevel as LogLevel)
26
- : "info";
20
+ const envLevel = getEnvVariable('COMPOSIO_LOGGING_LEVEL', 'info')?.toLowerCase();
21
+ return envLevel && envLevel in LOG_LEVELS ? (envLevel as LogLevel) : 'info';
22
};
23
24
interface LoggerOptions {
@@ -44,8 +39,8 @@ class Logger {
39
40
private formatMessage(args: unknown[]): string {
41
const formattedArgs = args
47
- .map((arg) => (typeof arg === "object" ? JSON.stringify(arg) : String(arg)))
48
- .join(" ");
42
+ .map(arg => (typeof arg === 'object' ? JSON.stringify(arg) : String(arg)))
43
+ .join('\n');
44
45
if (!this.includeTimestamp) {
46
return formattedArgs;
@@ -60,25 +55,25 @@ class Logger {
55
}
56
57
error(...args: unknown[]): void {
63
- if (this.shouldLog("error")) {
58
+ if (this.shouldLog('error')) {
59
this.console.error(this.formatMessage(args));
60
}
61
}
62
63
warn(...args: unknown[]): void {
69
- if (this.shouldLog("warn")) {
64
+ if (this.shouldLog('warn')) {
65
this.console.warn(this.formatMessage(args));
66
}
67
}
68
69
info(...args: unknown[]): void {
75
- if (this.shouldLog("info")) {
70
+ if (this.shouldLog('info')) {
71
this.console.info(this.formatMessage(args));
72
}
73
}
74
75
debug(...args: unknown[]): void {
81
- if (this.shouldLog("debug")) {
76
+ if (this.shouldLog('debug')) {
77
this.console.debug(this.formatMessage(args));
78
}
79
}
pnpm-lock.yaml
+22
@@ -130,6 +130,28 @@ importers:
130
specifier: ^5.8.3
131
version: 5.8.3
132
133
+ examples/toolkits:
134
+ dependencies:
135
+ '@ai-sdk/openai':
136
+ specifier: ^1.3.16
137
+ version: 1.3.22(zod@3.24.4)
138
+ '@composio/core':
139
+ specifier: workspace:*
140
+ version: link:../../packages/core
141
+ '@composio/vercel':
142
+ specifier: workspace:*
143
+ version: link:../../packages/toolsets/vercel
144
+ ai:
145
+ specifier: ^4.3.8
146
+ version: 4.3.15(react@19.1.0)(zod@3.24.4)
147
+ devDependencies:
148
+ '@types/bun':
149
+ specifier: ^1.2.9
150
+ version: 1.2.13
151
+ typescript:
152
+ specifier: ^5.8.3
153
+ version: 5.8.3
154
+
155
examples/vercel:
156
dependencies:
157
'@ai-sdk/openai':