Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 23, 01:45 UTC
Fix custom tools (#21)
* Fix custom tool types * Add changesets
Musthaq Ahamad committed
Jun 2, 2025 at 18:07 UTC
0b15376c97d9b0b425a801ee9ae7923b54fe0f73
15 files changed
+911
-357
.changeset/seven-mangos-mix.md
new
+12
@@ -0,0 +1,12 @@
1
+---
2
+'@composio/core': patch
3
+'@composio/anthropic': patch
4
+'@composio/cloudflare': patch
5
+'@composio/google': patch
6
+'@composio/langchain': patch
7
+'@composio/mastra': patch
8
+'@composio/openai': patch
9
+'@composio/vercel': patch
10
+---
11
+
12
+Add custom toolkit examples
docs/api/custom-tools.md
+95
-237
@@ -1,279 +1,137 @@
1
-# Custom Tools API
1
+# Custom Tools
2
3
-Custom Tools allow you to extend Composio's functionality by creating your own tools with custom logic. These tools can be used alongside the built-in tools provided by Composio.
3
+Custom tools allow you to create your own tools that can be used with Composio. There are two types of custom tools:
4
5
-## Creating Custom Tools
5
+1. Standalone Tools - Simple tools that don't require any authentication
6
+2. Toolkit-based Tools - Tools that require authentication and can use toolkit credentials
7
7
-You can create custom tools using the `createCustomTool` method of the `Tools` class:
8
+## Creating a Custom Tool
9
+
10
+### Standalone Tool
11
+
12
+A standalone tool is the simplest form of custom tool. It only requires input parameters and an execute function:
13
14
```typescript
10
-const customTool = await composio.tools.createCustomTool({
11
- name: 'My Custom Tool',
12
- description: 'A custom tool that does something specific',
13
- slug: 'MY_CUSTOM_TOOL',
14
- inputParameters: {
15
- type: 'object',
16
- properties: {
17
- param1: {
18
- type: 'string',
19
- description: 'First parameter',
20
- },
21
- param2: {
22
- type: 'number',
23
- description: 'Second parameter',
24
- }
25
- },
26
- required: ['param1']
27
- },
28
- outputParameters: {
29
- type: 'object',
30
- properties: {
31
- result: {
32
- type: 'string',
33
- description: 'The result of the operation'
34
- }
35
- }
36
- },
37
- handler: async (params, context) => {
38
- // Custom logic here
39
- const { param1, param2 } = params.arguments;
40
-
41
- // Return a successful response
42
- return {
43
- data: {
44
- result: `Processed ${param1} with value ${param2}`
45
- },
15
+const tool = await composio.tools.createCustomTool({
16
+ slug: 'CALCULATE_SQUARE',
17
+ name: 'Calculate Square',
18
+ description: 'Calculates the square of a number',
19
+ inputParams: z.object({
20
+ number: z.number().describe('The number to calculate the square of'),
21
+ }),
22
+ execute: async input => {
23
+ const { number } = input;
24
+ return {
25
+ data: { result: number * number },
26
+ error: null,
27
successful: true,
47
- error: null
28
};
49
- }
29
+ },
30
});
31
```
32
53
-## Custom Tool Options
54
-
55
-When creating a custom tool, you need to specify the following options:
56
-
57
-| Property | Type | Required | Description |
58
-|----------|------|----------|-------------|
59
-| `name` | string | Yes | The name of the custom tool |
60
-| `description` | string | Yes | A description of what the tool does |
61
-| `slug` | string | Yes | A unique identifier for the tool (usually uppercase with underscores) |
62
-| `inputParameters` | JSONSchema | Yes | The JSON Schema defining the input parameters |
63
-| `outputParameters` | JSONSchema | No | The JSON Schema defining the output parameters |
64
-| `handler` | function | Yes | The function that implements the tool's logic |
65
-
66
-## Handler Function
67
-
68
-The handler function is where you implement the custom tool's logic. It receives the following parameters:
69
-
70
-1. `params`: The parameters passed to the tool, including:
71
- - `arguments`: The input arguments as defined in `inputParameters`
72
- - `userId`: The ID of the user executing the tool
73
- - `connectedAccountId`: (optional) The ID of the connected account to use
74
- - Additional properties as defined in `ToolExecuteParams`
33
+### Toolkit-based Tool
34
76
-2. `context`: Execution metadata, including:
77
- - `userId`: The ID of the user executing the tool
78
- - `connectedAccountId`: (optional) The ID of the connected account being used
35
+A toolkit-based tool has access to two ways of making authenticated requests:
36
80
-The handler must return a `ToolExecuteResponse` object with the following structure:
37
+1. Using `executeToolRequest` - The recommended way to make authenticated requests to the toolkit's API endpoints. Composio automatically handles credential injection using the connected account:
38
39
```typescript
83
-{
84
- data: Record<string, unknown>, // The output data matching the outputParameters schema
85
- error: string | null, // Error message (if any)
86
- successful: boolean, // Whether the execution was successful
87
- logId?: string, // Optional log ID for debugging
88
- sessionInfo?: unknown // Optional session information
89
-}
90
-```
91
-
92
-## JSON Schema for Parameters
93
-
94
-Both `inputParameters` and `outputParameters` should be defined using JSON Schema:
95
-
96
-```typescript
97
-const inputParametersSchema = {
98
- type: 'object',
99
- properties: {
100
- query: {
101
- type: 'string',
102
- description: 'The search query'
103
- },
104
- limit: {
105
- type: 'integer',
106
- description: 'Maximum number of results',
107
- default: 10
108
- }
109
- },
110
- required: ['query']
111
-};
40
+const tool = await composio.tools.createCustomTool({
41
+ slug: 'GITHUB_STAR_COMPOSIO_REPOSITORY',
42
+ name: 'Star Composios Repository',
43
+ description: 'Stars a repository under composiohq org',
44
+ toolkitSlug: 'github',
45
+ inputParams: z.object({
46
+ repository: z.string().describe('Name of the repository to star'),
47
+ }),
48
+ execute: async (input, authCredentials, executeToolRequest) => {
49
+ // executeToolRequest makes authenticated requests to the toolkit's API
50
+ // It automatically uses the connected account's credentials
51
+ const starResult = await executeToolRequest({
52
+ endpoint: `https://api.github.com/user/starred/composiohq/${input.repository}`,
53
+ method: 'PUT',
54
+ body: {},
55
+ });
56
113
-const outputParametersSchema = {
114
- type: 'object',
115
- properties: {
116
- results: {
117
- type: 'array',
118
- items: {
119
- type: 'object',
120
- properties: {
121
- title: { type: 'string' },
122
- url: { type: 'string' }
123
- }
124
- },
125
- description: 'Search results'
126
- },
127
- totalCount: {
128
- type: 'integer',
129
- description: 'Total number of results found'
130
- }
131
- }
132
-};
133
-```
134
-
135
-## Error Handling in Custom Tools
136
-
137
-Your handler function should handle errors gracefully:
138
-
139
-```typescript
140
-handler: async (params, context) => {
141
- try {
142
- // Custom logic here
143
- const { query, limit = 10 } = params.arguments;
144
-
145
- // Simulate an API call
146
- const results = await searchApi(query, limit);
147
-
57
return {
58
data: {
150
- results,
151
- totalCount: results.length
59
+ message: 'Successfully stared repository',
60
},
61
+ error: null,
62
successful: true,
154
- error: null
63
};
156
- } catch (error) {
157
- // Handle errors
158
- return {
159
- data: {},
160
- successful: false,
161
- error: error.message || 'An error occurred during tool execution'
162
- };
163
- }
164
-}
64
+ },
65
+});
66
```
67
167
-## Using Connected Accounts in Custom Tools
168
-
169
-You can use connected accounts in your custom tools to access authenticated services:
68
+2. Using `authCredentials` - For making direct API calls when needed:
69
70
```typescript
172
-handler: async (params, context) => {
173
- const { userId, connectedAccountId } = context;
174
-
175
- if (!connectedAccountId) {
176
- return {
177
- data: {},
178
- successful: false,
179
- error: 'No connected account provided'
180
- };
181
- }
182
-
183
- try {
184
- // Get the connected account details
185
- const connectedAccount = await composio.connectedAccounts.get(connectedAccountId);
186
-
187
- // Use the authentication tokens
188
- const accessToken = connectedAccount.meta.access_token;
189
-
190
- // Make authenticated API calls
191
- const apiResult = await callExternalApi(accessToken, params.arguments);
192
-
71
+const tool = await composio.tools.createCustomTool({
72
+ slug: 'GITHUB_DIRECT_API',
73
+ name: 'Direct GitHub API Call',
74
+ description: 'Makes direct calls to GitHub API',
75
+ toolkitSlug: 'github',
76
+ inputParams: z.object({
77
+ repo: z.string().describe('Repository name'),
78
+ }),
79
+ execute: async (input, authCredentials) => {
80
+ // Use authCredentials for direct API calls
81
+ const result = await fetch(`https://api.github.com/repos/${input.repo}`, {
82
+ headers: {
83
+ Authorization: `Bearer ${authCredentials.access_token}`,
84
+ },
85
+ });
86
+
87
return {
194
- data: apiResult,
88
+ data: await result.json(),
89
+ error: null,
90
successful: true,
196
- error: null
197
- };
198
- } catch (error) {
199
- return {
200
- data: {},
201
- successful: false,
202
- error: error.message
91
};
204
- }
205
-}
92
+ },
93
+});
94
```
95
208
-## Accessing Custom Tools
96
+## Executing Custom Tools
97
210
-Once created, custom tools can be accessed just like built-in tools:
98
+You can execute custom tools just like any other tool:
99
100
```typescript
213
-// Get the custom tool
214
-const tool = await composio.tools.get('default', 'MY_CUSTOM_TOOL');
215
-
216
-// Execute the custom tool
217
-const result = await composio.tools.execute('MY_CUSTOM_TOOL', {
218
- userId: 'default',
101
+const result = await composio.tools.execute('TOOL_SLUG', {
102
arguments: {
220
- param1: 'value1',
221
- param2: 42
222
- }
103
+ // Tool input parameters
104
+ },
105
+ userId: 'user-id',
106
+ connectedAccountId: 'optional-account-id', // Required for toolkit-based tools
107
});
224
-
225
-console.log(result.data); // { result: "Processed value1 with value 42" }
108
```
109
228
-## Types
229
-
230
-### CustomToolOptions
231
-
232
-```typescript
233
-interface CustomToolOptions {
234
- name: string;
235
- description: string;
236
- slug: string;
237
- inputParameters: JSONSchema;
238
- outputParameters?: JSONSchema;
239
- handler: (
240
- params: ToolExecuteParams,
241
- context: ExecuteMetadata
242
- ) => Promise<ToolExecuteResponse>;
243
-}
244
-```
110
+## Type Safety
111
246
-### ExecuteMetadata
112
+The custom tools implementation provides full type safety:
113
248
-```typescript
249
-interface ExecuteMetadata {
250
- userId: string;
251
- connectedAccountId?: string;
252
-}
253
-```
114
+1. Input parameters are validated using Zod schemas
115
+2. The execute function's parameters are inferred based on whether toolkitSlug is provided:
116
+ - Without toolkitSlug: `(input) => Promise<ToolExecuteResponse>`
117
+ - With toolkitSlug: `(input, authCredentials, executeToolRequest) => Promise<ToolExecuteResponse>`
118
255
-### ToolExecuteParams
119
+## Best Practices
120
257
-```typescript
258
-interface ToolExecuteParams {
259
- allowTracing?: boolean;
260
- connectedAccountId?: string;
261
- customAuthParams?: CustomAuthParams;
262
- arguments: Record<string, unknown>;
263
- userId: string;
264
- version?: string;
265
- text?: string;
266
-}
267
-```
121
+1. Use descriptive names and slugs for your tools
122
+2. Always provide descriptions for input parameters using `describe()`
123
+3. Handle errors gracefully in your execute function
124
+4. For toolkit-based tools:
125
+ - Prefer `executeToolRequest` over direct API calls when possible
126
+ - Remember that `executeToolRequest` can only call tools from the same toolkit
127
+ - Use `executeToolRequest` to leverage Composio's automatic credential handling
128
+ - Only use `authCredentials` when you need to make direct API calls or interact with different services
129
+5. Chain multiple toolkit operations using `executeToolRequest` for better maintainability
130
269
-### ToolExecuteResponse
131
+## Limitations
132
271
-```typescript
272
-interface ToolExecuteResponse {
273
- data: Record<string, unknown>;
274
- error: string | null;
275
- successful: boolean;
276
- logId?: string;
277
- sessionInfo?: unknown;
278
-}
279
-```
\ No newline at end of file
133
+1. Custom tools are stored in memory and are not persisted
134
+2. They need to be recreated when the application restarts
135
+3. Toolkit-based tools require a valid connected account with the specified toolkit
136
+4. `executeToolRequest` can only execute tools from the same toolkit that the custom tool belongs to
137
+5. Each toolkit-based tool can only use one connected account at a time
examples/custom-tools/.env.example
new
+6
@@ -0,0 +1,6 @@
1
+# Composio API Key - Get it from https://app.composio.dev
2
+COMPOSIO_API_KEY=your_composio_api_key_here
3
+
4
+# Add other environment variables as needed for your example
5
+# OPENAI_API_KEY=your_openai_api_key_here
6
+# ANTHROPIC_API_KEY=your_anthropic_api_key_here
examples/custom-tools/README.md
new
+165
@@ -0,0 +1,165 @@
1
+# Custom Tools Examples
2
+
3
+This directory contains examples demonstrating how to create and use custom tools with Composio SDK.
4
+
5
+## Examples
6
+
7
+### 1. Simple Custom Tool (`simple.ts`)
8
+
9
+Shows how to create a basic standalone tool that doesn't require authentication. The example creates a tool that calculates the square of a number:
10
+
11
+```typescript
12
+const tool = await composio.tools.createCustomTool({
13
+ slug: 'CALCULATE_SQUARE',
14
+ name: 'Calculate Square',
15
+ description: 'Calculates the square of a number',
16
+ inputParams: z.object({
17
+ number: z.number().describe('The number to calculate the square of'),
18
+ }),
19
+ execute: async input => {
20
+ const { number } = input;
21
+ return {
22
+ data: { result: number * number },
23
+ error: null,
24
+ successful: true,
25
+ };
26
+ },
27
+});
28
+```
29
+
30
+### 2. Toolkit-based Tools (`auth-credentials.ts`)
31
+
32
+Demonstrates two approaches to making authenticated requests in toolkit-based tools:
33
+
34
+#### Using executeToolRequest (Recommended)
35
+
36
+```typescript
37
+const tool = await composio.tools.createCustomTool({
38
+ slug: 'GITHUB_LIST_AND_STAR',
39
+ name: 'List and Star Repository',
40
+ description: 'Lists repositories and stars them',
41
+ toolkitSlug: 'github',
42
+ inputParams: z.object({
43
+ owner: z.string().describe('Repository owner'),
44
+ }),
45
+ execute: async (input, authCredentials, executeToolRequest) => {
46
+ // executeToolRequest can only call tools from the 'github' toolkit
47
+ // Uses the same connected account credentials automatically
48
+ const listResult = await executeToolRequest({
49
+ slug: 'LIST_REPOSITORIES', // must be a github toolkit tool
50
+ arguments: { owner: input.owner },
51
+ });
52
+
53
+ const starResult = await executeToolRequest({
54
+ slug: 'STAR_REPOSITORY', // must be a github toolkit tool
55
+ arguments: {
56
+ owner: input.owner,
57
+ repo: listResult.data.repositories[0].name,
58
+ },
59
+ });
60
+
61
+ return {
62
+ data: { listed: listResult.data, starred: starResult.data },
63
+ error: null,
64
+ successful: true,
65
+ };
66
+ },
67
+});
68
+```
69
+
70
+#### Using Direct API Calls
71
+
72
+```typescript
73
+const tool = await composio.tools.createCustomTool({
74
+ slug: 'GITHUB_STAR_REPO',
75
+ name: 'Star GitHub Repository',
76
+ toolkitSlug: 'github',
77
+ description: 'Stars a GitHub repository using direct API call',
78
+ inputParams: z.object({
79
+ repository: z.string().describe('The repository to star'),
80
+ }),
81
+ execute: async (input, authCredentials) => {
82
+ // Use authCredentials for direct API calls or when interacting with different services
83
+ const result = await fetch(
84
+ `https://api.github.com/user/starred/composiohq/${input.repository}`,
85
+ {
86
+ method: 'PUT',
87
+ headers: {
88
+ Authorization: `Bearer ${authCredentials?.access_token}`,
89
+ },
90
+ }
91
+ );
92
+ return {
93
+ data: await result.json(),
94
+ error: null,
95
+ successful: true,
96
+ };
97
+ },
98
+});
99
+```
100
+
101
+## Running the Examples
102
+
103
+1. Set up your environment:
104
+
105
+ ```bash
106
+ cp .env.example .env
107
+ ```
108
+
109
+2. Add your Composio API key to `.env`:
110
+
111
+ ```
112
+ COMPOSIO_API_KEY=your_api_key_here
113
+ ```
114
+
115
+3. Run an example:
116
+
117
+ ```bash
118
+ # Run the simple example
119
+ pnpm start:simple
120
+
121
+ # Run the auth credentials example
122
+ pnpm start:auth
123
+ ```
124
+
125
+## Key Concepts
126
+
127
+1. **Standalone vs Toolkit-based Tools**
128
+
129
+ - Standalone tools only receive input parameters
130
+ - Toolkit-based tools have access to both `executeToolRequest` and `authCredentials`
131
+
132
+2. **Authentication Methods**
133
+
134
+ - `executeToolRequest`: Recommended way to use toolkit tools
135
+ - Can only execute tools from the same toolkit
136
+ - Uses the connected account credentials automatically
137
+ - No need to manage auth tokens
138
+ - Better maintainability and security
139
+ - `authCredentials`: For direct API calls
140
+ - Use when you need to make direct API calls
141
+ - Use when you need to interact with different services
142
+ - Requires manual token management
143
+ - More flexible but requires more maintenance
144
+
145
+3. **Type Safety**
146
+
147
+ - Input parameters are validated using Zod schemas
148
+ - TypeScript infers the correct execute function signature based on toolkitSlug
149
+
150
+4. **Error Handling**
151
+
152
+ - Tools should always return a ToolExecuteResponse
153
+ - Handle errors gracefully and provide meaningful error messages
154
+
155
+## Related Examples
156
+
157
+- [OpenAI Example](../openai) - Shows integration with OpenAI
158
+- [LangChain Example](../langchain) - Shows integration with LangChain
159
+- [More Examples](../) - Browse all available examples
160
+
161
+## Support
162
+
163
+- [Documentation](https://docs.composio.dev)
164
+- [Discord Community](https://discord.gg/composio)
165
+- [GitHub Issues](https://github.com/composio/composio/issues)
examples/custom-tools/package.json
new
+29
@@ -0,0 +1,29 @@
1
+{
2
+ "name": "custom-tools-example",
3
+ "private": true,
4
+ "version": "0.1.0",
5
+ "description": "Example project for Custom-tools",
6
+ "main": "src/index.ts",
7
+ "scripts": {
8
+ "start": "bun src/index.ts",
9
+ "dev": "bun --watch src/index.ts",
10
+ "test": "echo \"Error: no test specified\" && exit 1"
11
+ },
12
+ "keywords": [
13
+ "composio",
14
+ "example",
15
+ "custom-tools"
16
+ ],
17
+ "author": "",
18
+ "license": "ISC",
19
+ "packageManager": "pnpm@10.8.0",
20
+ "dependencies": {
21
+ "@composio/core": "workspace:*",
22
+ "dotenv": "^16.4.1",
23
+ "zod": "^3.24.2"
24
+ },
25
+ "devDependencies": {
26
+ "@types/bun": "^1.2.9",
27
+ "typescript": "^5.8.3"
28
+ }
29
+}
examples/custom-tools/src/auth-credentials.ts
new
+88
@@ -0,0 +1,88 @@
1
+/**
2
+ * Custom-tools Example
3
+ *
4
+ * This example demonstrates how to use Composio SDK for custom-tools with auth credentials.
5
+ *
6
+ * Prerequisites:
7
+ * 1. Set up your COMPOSIO_API_KEY in the .env file
8
+ * 3. Run the example: pnpm start
9
+ */
10
+
11
+import { Composio } from '@composio/core';
12
+import 'dotenv/config';
13
+import { z } from 'zod';
14
+
15
+/**
16
+ * Initialize Composio
17
+ */
18
+const composio = new Composio({
19
+ apiKey: process.env.COMPOSIO_API_KEY,
20
+});
21
+
22
+/**
23
+ * Create a custom hackernews tool
24
+ * This tool will be registerd in the composio instance and store in memory temporarily.
25
+ */
26
+const customToolSlug = 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY';
27
+const tool = await composio.tools.createCustomTool({
28
+ slug: customToolSlug,
29
+ name: 'Github star composio repositories',
30
+ toolkitSlug: 'github',
31
+ description: 'For any given repository of the user composiohq, star the repository',
32
+ inputParams: z.object({
33
+ repository: z.string().describe('The repository to star'),
34
+ }),
35
+ execute: async (input, authCredentials) => {
36
+ console.log('🚀 ~ execute: ~ params:', input);
37
+ console.log('🚀 ~ execute: ~ authCredentials:', authCredentials);
38
+ /**
39
+ * The auth credentials are the auth credentials for the connected account.
40
+ * You can use them to make requests to the API.
41
+ */
42
+ const result = await fetch(
43
+ `https://api.github.com/user/starred/composiohq/${input.repository}`,
44
+ {
45
+ method: 'PUT',
46
+ headers: {
47
+ Authorization: `Bearer ${authCredentials?.access_token}`,
48
+ },
49
+ }
50
+ );
51
+ const data = await result.json();
52
+ return {
53
+ data: data,
54
+ error: null,
55
+ successful: true,
56
+ };
57
+ },
58
+});
59
+
60
+console.log('🚀 created tool:', tool);
61
+
62
+/**
63
+ * Main function to run the example
64
+ */
65
+async function main() {
66
+ try {
67
+ console.log('🚀 Starting Custom-tools Example...');
68
+
69
+ // Get available tools
70
+ const tools = await composio.tools.get('default', customToolSlug);
71
+
72
+ console.log('tools:', tools);
73
+
74
+ const result = await composio.tools.execute(customToolSlug, {
75
+ arguments: {
76
+ repository: 'composio',
77
+ },
78
+ userId: 'default',
79
+ });
80
+
81
+ console.log('🚀 Result:', result);
82
+ } catch (error) {
83
+ console.error('❌ Error running example:', error);
84
+ }
85
+}
86
+
87
+// Run the example
88
+main().catch(console.error);
examples/custom-tools/src/index.ts
new
+76
@@ -0,0 +1,76 @@
1
+/**
2
+ * Custom-tools Example
3
+ *
4
+ * This example demonstrates how to use Composio SDK for custom-tools.
5
+ *
6
+ * Prerequisites:
7
+ * 1. Set up your COMPOSIO_API_KEY in the .env file
8
+ * 3. Run the example: pnpm start
9
+ */
10
+
11
+import { Composio } from '@composio/core';
12
+import 'dotenv/config';
13
+import { z } from 'zod';
14
+
15
+/**
16
+ * Initialize Composio
17
+ */
18
+const composio = new Composio({
19
+ apiKey: process.env.COMPOSIO_API_KEY,
20
+});
21
+
22
+/**
23
+ * Create a custom hackernews tool
24
+ * This tool will be registerd in the composio instance and store in memory temporarily.
25
+ */
26
+const customToolSlug = 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY';
27
+const tool = await composio.tools.createCustomTool({
28
+ slug: customToolSlug,
29
+ name: 'Github star composio repositories',
30
+ toolkitSlug: 'github',
31
+ description: 'For any given repository of the user composiohq, star the repository',
32
+ inputParams: z.object({
33
+ repository: z.string().describe('The repository to star'),
34
+ }),
35
+ execute: async (input, authCredentials, executeToolRequest) => {
36
+ console.log('🚀 ~ execute: ~ params:', input);
37
+ console.log('🚀 ~ execute: ~ authCredentials:', authCredentials);
38
+
39
+ const result = await executeToolRequest({
40
+ endpoint: `https://api.github.com/user/starred/composiohq/${input.repository}`,
41
+ method: 'PUT',
42
+ body: {},
43
+ });
44
+ return result;
45
+ },
46
+});
47
+
48
+console.log('🚀 created tool:', tool);
49
+
50
+/**
51
+ * Main function to run the example
52
+ */
53
+async function main() {
54
+ try {
55
+ console.log('🚀 Starting Custom-tools Example...');
56
+
57
+ // Get available tools
58
+ const tools = await composio.tools.get('default', customToolSlug);
59
+
60
+ console.log('tools:', tools);
61
+
62
+ const result = await composio.tools.execute(customToolSlug, {
63
+ arguments: {
64
+ repository: 'composio',
65
+ },
66
+ userId: 'default',
67
+ });
68
+
69
+ console.log('🚀 Result:', result);
70
+ } catch (error) {
71
+ console.error('❌ Error running example:', error);
72
+ }
73
+}
74
+
75
+// Run the example
76
+main().catch(console.error);
examples/custom-tools/src/simple.ts
new
+76
@@ -0,0 +1,76 @@
1
+/**
2
+ * Custom-tools Example
3
+ *
4
+ * This example demonstrates how to use Composio SDK for simple custom-tools.
5
+ *
6
+ * Prerequisites:
7
+ * 1. Set up your COMPOSIO_API_KEY in the .env file
8
+ * 3. Run the example: pnpm start
9
+ */
10
+
11
+import { Composio } from '@composio/core';
12
+import 'dotenv/config';
13
+import { z } from 'zod';
14
+
15
+/**
16
+ * Initialize Composio
17
+ */
18
+const composio = new Composio({
19
+ apiKey: process.env.COMPOSIO_API_KEY,
20
+});
21
+
22
+/**
23
+ * Create a custom calculate square of a number tool
24
+ * This tool will be registerd in the composio instance and store in memory temporarily.
25
+ */
26
+const customToolSlug = 'CALCULATE_SQUARE_OF_A_NUMBER';
27
+const tool = await composio.tools.createCustomTool({
28
+ slug: customToolSlug,
29
+ name: 'Calculate square of a number',
30
+ description: 'For any given number the tool calculates the square of the number',
31
+ inputParams: z.object({
32
+ number: z.number().describe('The number to calculate the square of'),
33
+ }),
34
+ execute: async input => {
35
+ const { number } = input;
36
+ const result = Number(number) * Number(number);
37
+
38
+ return {
39
+ data: {
40
+ result,
41
+ },
42
+ error: null,
43
+ successful: true,
44
+ };
45
+ },
46
+});
47
+
48
+console.log('🚀 created tool:', tool);
49
+
50
+/**
51
+ * Main function to run the example
52
+ */
53
+async function main() {
54
+ try {
55
+ console.log('🚀 Starting Custom-tools Example...');
56
+
57
+ // Get available tools
58
+ const tools = await composio.tools.get('default', customToolSlug);
59
+
60
+ console.log('tools:', tools);
61
+
62
+ const result = await composio.tools.execute(customToolSlug, {
63
+ arguments: {
64
+ number: 2,
65
+ },
66
+ userId: 'default',
67
+ });
68
+
69
+ console.log('🚀 Result:', result);
70
+ } catch (error) {
71
+ console.error('❌ Error running example:', error);
72
+ }
73
+}
74
+
75
+// Run the example
76
+main().catch(console.error);
examples/custom-tools/tsconfig.json
new
+16
@@ -0,0 +1,16 @@
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
+ "resolveJsonModule": true
14
+ },
15
+ "include": ["src"]
16
+}
packages/core/src/models/CustomTools.ts
+116
-32
@@ -7,15 +7,13 @@
7
*/
8
import ComposioClient from '@composio/client';
9
import {
10
- CustomToolInput,
10
CustomToolInputParameter,
11
CustomToolOptions,
12
CustomToolRegistry,
14
- ExecuteMetadata,
13
InputParamsSchema,
14
} from '../types/customTool.types';
15
import zodToJsonSchema from 'zod-to-json-schema';
18
-import { Tool, ToolExecuteResponse, ToolList } from '../types/tool.types';
16
+import { Tool, ToolExecuteParams, ToolExecuteResponse, ToolList } from '../types/tool.types';
17
import { ToolProxyParams } from '@composio/client/resources/tools';
18
import logger from '../utils/logger';
19
import {
@@ -25,6 +23,11 @@ import {
23
import { ComposioConnectedAccountNotFoundError } from '../errors/ConnectedAccountsErrors';
24
import { ComposioError } from '../errors/ComposioError';
25
import { telemetry } from '../telemetry/Telemetry';
26
+import {
27
+ ConnectedAccountRetrieveResponse,
28
+ ConnectedAccountRetrieveResponseSchema,
29
+} from '../types/connectedAccounts.types';
30
+import { ValidationError } from '../errors';
31
32
export class CustomTools {
33
private readonly client: ComposioClient;
@@ -44,7 +47,7 @@ export class CustomTools {
47
* This is just an in memory registry and is not persisted.
48
* @param {CustomToolOptions} toolOptions CustomToolOptions
49
* @returns {Tool} The tool created
47
- *
50
+ *
51
* @example
52
* ```typescript
53
* // Create a custom tool with input parameters
@@ -65,7 +68,9 @@ export class CustomTools {
68
* });
69
* ```
70
*/
68
- async createTool(toolOptions: CustomToolOptions): Promise<Tool> {
71
+ async createTool<T extends CustomToolInputParameter>(
72
+ toolOptions: CustomToolOptions<T>
73
+ ): Promise<Tool> {
74
const { slug, execute, inputParams, name, description } = toolOptions;
75
if (!slug || !execute || !inputParams || !name) {
76
throw new Error('Invalid tool options');
@@ -93,11 +98,13 @@ export class CustomTools {
98
properties: {},
99
},
100
tags: [],
101
+ // this is never set to the user provided toolkitslug so that we can differentiate
102
+ // the toolkitslug is used via the execute function.
103
toolkit: { name: 'custom', slug: 'custom' },
104
};
105
106
this.customToolsRegistry.set(slug.toLowerCase(), {
100
- options: toolOptions,
107
+ options: toolOptions as unknown as CustomToolOptions<CustomToolInputParameter>,
108
schema: toolSchema,
109
});
110
return toolSchema;
@@ -107,12 +114,12 @@ export class CustomTools {
114
* Get all the custom tools from the registry.
115
* @param {string[]} param0.toolSlugs The slugs of the tools to get
116
* @returns {ToolList} The list of tools
110
- *
117
+ *
118
* @example
119
* ```typescript
120
* // Get all custom tools
121
* const allTools = await composio.customTools.getCustomTools({});
115
- *
122
+ *
123
* // Get specific custom tools by slug
124
* const specificTools = await composio.customTools.getCustomTools({
125
* toolSlugs: ['MY_CUSTOM_TOOL', 'ANOTHER_CUSTOM_TOOL']
@@ -142,7 +149,7 @@ export class CustomTools {
149
* Get a custom tool by slug from the registry.
150
* @param {string} slug The slug of the tool to get
151
* @returns {Tool} The tool
145
- *
152
+ *
153
* @example
154
* ```typescript
155
* // Get a specific custom tool by its slug
@@ -174,7 +181,11 @@ export class CustomTools {
181
* @param {ExecuteMetadata} metadata The metadata of the execution
182
* @returns {ConnectedAccount} The connected account
183
*/
177
- private async getConnectedAccount(toolkitSlug: string, metadata: ExecuteMetadata) {
184
+ private async getConnectedAccountForToolkit(
185
+ toolkitSlug: string,
186
+ userId: string,
187
+ connectedAccountId?: string
188
+ ): Promise<ConnectedAccountRetrieveResponse> {
189
try {
190
await this.client.toolkits.retrieve(toolkitSlug);
191
} catch (error) {
@@ -184,7 +195,7 @@ export class CustomTools {
195
}
196
const connectedAccounts = await this.client.connectedAccounts.list({
197
toolkit_slugs: [toolkitSlug],
187
- user_ids: [metadata.userId],
198
+ user_ids: [userId],
199
});
200
201
if (!connectedAccounts.items.length) {
@@ -192,46 +203,96 @@ export class CustomTools {
203
`No connected accounts found for toolkit ${toolkitSlug}`
204
);
205
}
195
-
196
- return metadata.connectedAccountId
197
- ? connectedAccounts.items.find(item => item.id === metadata.connectedAccountId)
206
+ // if a connected account id is provided, use it, otherwise use the first connected account
207
+ const connectedAccount = connectedAccountId
208
+ ? connectedAccounts.items.find(item => item.id === connectedAccountId)
209
: connectedAccounts.items[0];
210
+
211
+ if (!connectedAccount) {
212
+ throw new ComposioConnectedAccountNotFoundError(
213
+ `Connected account not found for toolkit ${toolkitSlug} for user ${userId}`
214
+ );
215
+ }
216
+
217
+ const connectedAccountResponse = await ConnectedAccountRetrieveResponseSchema.safeParse({
218
+ id: connectedAccount.id,
219
+ authConfig: {
220
+ id: connectedAccount.auth_config.id,
221
+ authScheme: connectedAccount.auth_config.auth_scheme,
222
+ isComposioManaged: connectedAccount.auth_config.is_composio_managed,
223
+ isDisabled: connectedAccount.auth_config.is_disabled,
224
+ },
225
+ userId: connectedAccount.user_id,
226
+ data: connectedAccount.data || {},
227
+ status: connectedAccount.status,
228
+ statusReason: connectedAccount.status_reason,
229
+ toolkit: {
230
+ slug: connectedAccount.toolkit.slug,
231
+ },
232
+ testRequestEndpoint: connectedAccount.test_request_endpoint,
233
+ isDisabled: connectedAccount.is_disabled,
234
+ createdAt: connectedAccount.created_at,
235
+ updatedAt: connectedAccount.updated_at,
236
+ });
237
+
238
+ if (!connectedAccountResponse.success) {
239
+ throw new ValidationError(
240
+ `Validation error for connected account of ${toolkitSlug} for user ${userId}`,
241
+ {
242
+ cause: connectedAccountResponse.error,
243
+ }
244
+ );
245
+ }
246
+
247
+ return connectedAccountResponse.data;
248
}
249
250
/**
251
* Execute a custom tool
252
+ *
253
+ * @description If a toolkit is used, the connected account id is used to execute the tool.
254
+ * If a connected account id is provided, it is used to execute the tool.
255
+ * If a connected account id is not provided, the first connected account for the toolkit is used.
256
+ *
257
* @param {slug} slug The slug of the tool to execute
258
* @param {Record<string, unknown>} inputParams The input parameters for the tool
259
* @param {ExecuteMetadata} metadata The metadata of the execution
260
* @returns {Promise<ToolExecuteResponse>} The response from the tool
261
*/
208
- async executeCustomTool(
209
- slug: string,
210
- inputParams: Record<string, unknown>,
211
- metadata: ExecuteMetadata
212
- ): Promise<ToolExecuteResponse> {
262
+ async executeCustomTool(slug: string, body: ToolExecuteParams): Promise<ToolExecuteResponse> {
263
const tool = this.customToolsRegistry.get(slug.toLowerCase());
264
if (!tool) {
265
throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);
266
}
267
268
let authCredentials: Record<string, unknown> = {};
219
- const { toolkitSlug, execute } = tool.options;
269
+ const { toolkitSlug, execute, inputParams } = tool.options;
270
// if a toolkit is used, get the connected account, and auth credentials
271
+ let connectedAccountId: string | undefined = body.connectedAccountId;
272
+
273
if (toolkitSlug && toolkitSlug !== 'custom') {
222
- const connectedAccount = await this.getConnectedAccount(toolkitSlug, metadata);
274
+ const connectedAccount = await this.getConnectedAccountForToolkit(
275
+ toolkitSlug,
276
+ body.userId,
277
+ body.connectedAccountId
278
+ );
279
+ logger.debug(
280
+ `[CustomTool] Connected account for ${toolkitSlug} found for user ${body.userId}`,
281
+ JSON.stringify(connectedAccount, null, 2)
282
+ );
283
if (!connectedAccount) {
284
throw new ComposioConnectedAccountNotFoundError(
225
- `Connected account not found for toolkit ${toolkitSlug} for user ${metadata.userId}`,
285
+ `Connected account not found for toolkit ${toolkitSlug} for user ${body.userId}`,
286
{
287
meta: {
288
toolkitSlug,
229
- userId: metadata.userId,
289
+ userId: body.userId,
290
},
291
}
292
);
293
}
234
- authCredentials = connectedAccount.data?.connectionParams as Record<string, unknown>;
294
+ authCredentials = connectedAccount.data as Record<string, unknown>;
295
+ connectedAccountId = connectedAccount.id;
296
}
297
298
if (typeof execute !== 'function') {
@@ -242,17 +303,40 @@ export class CustomTools {
303
});
304
}
305
// create a tool proxy request for users to execute in case of a toolkit being used
245
- const executeToolRequest = async (data: ToolProxyParams) => {
246
- return this.client.tools.proxy({
306
+ const executeToolRequest = async (data: ToolProxyParams): Promise<ToolExecuteResponse> => {
307
+ if (toolkitSlug && toolkitSlug === 'custom') {
308
+ throw new ComposioInvalidExecuteFunctionError(
309
+ 'Custom tools without a toolkit cannot be executed using the executeToolRequest function',
310
+ {
311
+ possibleFixes: [
312
+ 'Please manually execute the tool using your logic.',
313
+ 'Pass a toolkit slug to execute the tool on behalf of a toolkit credentials',
314
+ ],
315
+ }
316
+ );
317
+ }
318
+ const response = await this.client.tools.proxy({
319
...data,
248
- connected_account_id: metadata.connectedAccountId,
320
+ connected_account_id: connectedAccountId,
321
});
322
+
323
+ return {
324
+ data: response.data as Record<string, unknown>,
325
+ error: null,
326
+ successful: true,
327
+ logId: undefined,
328
+ sessionInfo: undefined,
329
+ };
330
};
331
252
- return execute(
253
- inputParams as CustomToolInput<CustomToolInputParameter>,
254
- authCredentials,
255
- executeToolRequest
256
- );
332
+ // Parse and validate the input using the tool's schema
333
+ const parsedInput = inputParams.safeParse(body.arguments);
334
+ if (!parsedInput.success) {
335
+ throw new ValidationError('Invalid input parameters', {
336
+ cause: parsedInput.error,
337
+ });
338
+ }
339
+
340
+ return execute(parsedInput.data, authCredentials, executeToolRequest);
341
}
342
}
packages/core/src/models/Tools.ts
+36
-24
@@ -20,7 +20,7 @@ import {
20
ToolExecuteResponse as ComposioToolExecuteResponse,
21
} from '@composio/client/resources/tools';
22
import { CustomTools } from './CustomTools';
23
-import { CustomToolOptions } from '../types/customTool.types';
23
+import { CustomToolInputParameter, CustomToolOptions } from '../types/customTool.types';
24
import {
25
ExecuteToolModifiers,
26
ProviderOptions,
@@ -343,7 +343,10 @@ export class Tools<
343
// check if the tool is a custom tool
344
const customTool = await this.customTools.getCustomToolBySlug(slug);
345
if (customTool) {
346
+ logger.debug(`Found ${slug} to be a custom tool`, JSON.stringify(customTool, null, 2));
347
return customTool;
348
+ } else {
349
+ logger.debug(`Tool ${slug} is not a custom tool. Fetching from Composio API`);
350
}
351
// if not, fetch the tool from the Composio API
352
let tool: ToolRetrieveResponse;
@@ -499,10 +502,7 @@ export class Tools<
502
}
503
}
504
502
- let result = await this.customTools.executeCustomTool(tool.slug, body, {
503
- userId: body.userId || 'default',
504
- connectedAccountId: body.connectedAccountId,
505
- });
505
+ let result = await this.customTools.executeCustomTool(tool.slug, body);
506
507
if (modifiers?.afterExecute) {
508
if (typeof modifiers.afterExecute === 'function') {
@@ -665,7 +665,7 @@ export class Tools<
665
* @param {string} slug - The ID of the tool to find input for
666
* @param {ToolGetInputParams} body - The parameters to be passed to the tool
667
* @returns {Promise<ToolGetInputResponse>} The input parameters schema for the specified tool
668
- *
668
+ *
669
* @example
670
* ```typescript
671
* // Get input parameters for a specific tool
@@ -681,13 +681,13 @@ export class Tools<
681
682
/**
683
* Proxies a custom request to a toolkit/integration.
684
- *
684
+ *
685
* This method allows sending custom requests to a specific toolkit or integration
686
* when you need more flexibility than the standard tool execution methods provide.
687
*
688
* @param {ToolProxyParams} body - The parameters for the proxy request including toolkit slug and custom data
689
* @returns {Promise<ToolProxyResponse>} The response from the proxied request
690
- *
690
+ *
691
* @example
692
* ```typescript
693
* // Send a custom request to a toolkit
@@ -717,31 +717,43 @@ export class Tools<
717
*
718
* @example
719
* ```typescript
720
- * const customTool = await composio.tools.createCustomTool({
720
+ * // creating a custom tool with a toolkit
721
+ * await composio.tools.createCustomTool({
722
* name: 'My Custom Tool',
723
* description: 'A custom tool that does something specific',
724
* slug: 'MY_CUSTOM_TOOL',
724
- * inputParameters: {
725
- * param1: {
726
- * type: 'string',
727
- * description: 'First parameter',
728
- * required: true
729
- * }
730
- * },
731
- * outputParameters: {
732
- * result: {
733
- * type: 'string',
734
- * description: 'The result of the operation'
735
- * }
736
- * },
737
- * handler: async (params, context) => {
725
+ * userId: 'default',
726
+ * connectedAccountId: '123',
727
+ * toolkitSlug: 'github',
728
+ * inputParameters: z.object({
729
+ * param1: z.string().describe('First parameter'),
730
+ * }),
731
+ * execute: async (input, authCredentials, executeToolRequest) => {
732
* // Custom logic here
733
* return { data: { result: 'Success!' } };
734
* }
735
* });
736
* ```
737
+ *
738
+ * @example
739
+ * ```typescript
740
+ * // creating a custom tool without a toolkit
741
+ * await composio.tools.createCustomTool({
742
+ * name: 'My Custom Tool',
743
+ * description: 'A custom tool that does something specific',
744
+ * slug: 'MY_CUSTOM_TOOL',
745
+ * inputParameters: z.object({
746
+ * param1: z.string().describe('First parameter'),
747
+ * }),
748
+ * execute: async (input) => {
749
+ * // Custom logic here
750
+ * return { data: { result: 'Success!' } };
751
+ * }
752
+ * });
753
*/
744
- async createCustomTool(body: CustomToolOptions): Promise<Tool> {
754
+ async createCustomTool<T extends CustomToolInputParameter>(
755
+ body: CustomToolOptions<T>
756
+ ): Promise<Tool> {
757
return this.customTools.createTool(body);
758
}
759
}
packages/core/src/types/customTool.types.ts
+32
-29
@@ -1,48 +1,51 @@
1
-import { z, ZodObject, ZodString, ZodNumber, ZodBoolean, ZodOptional } from 'zod';
2
-import { Tool, ToolExecuteResponse } from './tool.types';
3
-import { ToolProxyParams, ToolProxyResponse } from '@composio/client/resources/tools';
4
-import { JsonSchema7Type } from 'zod-to-json-schema';
5
-
6
-export type CustomToolInputParameter = ZodObject<{
7
- [key: string]:
8
- | ZodString
9
- | ZodNumber
10
- | ZodBoolean
11
- | ZodOptional<ZodString | ZodNumber | ZodBoolean>;
12
-}>;
13
-
14
-export type CustomToolInput<T extends CustomToolInputParameter> = {
15
- [K in keyof z.infer<T>]: z.infer<T>[K];
16
-};
1
+import { z } from 'zod';
2
+import { Tool } from './tool.types';
3
+import { ToolExecuteResponse, ToolProxyParams } from '@composio/client/resources/tools';
4
18
-export interface CustomToolOptions<T extends CustomToolInputParameter = CustomToolInputParameter> {
19
- slug: string;
5
+type BaseCustomToolOptions<T extends z.ZodType> = {
6
name: string;
21
- toolkitSlug?: string | null;
7
description?: string;
8
+ slug: string;
9
inputParams: T;
10
+};
11
+
12
+type ToolkitBasedExecute<T extends z.ZodType> = {
13
execute: (
25
- input: CustomToolInput<T>,
26
- authCredentials?: Record<string, unknown>,
27
- executeAppRequest?: (data: ToolProxyParams) => Promise<ToolProxyResponse>
14
+ input: z.infer<T>,
15
+ authCredentials: Record<string, unknown>,
16
+ executeToolRequest: (data: ToolProxyParams) => Promise<ToolExecuteResponse>
17
) => Promise<ToolExecuteResponse>;
29
-}
18
+ toolkitSlug: string;
19
+};
20
+
21
+type StandaloneExecute<T extends z.ZodType> = {
22
+ execute: (input: z.infer<T>) => Promise<ToolExecuteResponse>;
23
+ toolkitSlug?: never;
24
+};
25
+
26
+export type CustomToolOptions<T extends z.ZodType> = BaseCustomToolOptions<T> &
27
+ (ToolkitBasedExecute<T> | StandaloneExecute<T>);
28
29
export type CustomToolRegistry = Map<
30
string,
33
- {
34
- options: CustomToolOptions;
35
- schema: Tool;
36
- }
31
+ { options: CustomToolOptions<CustomToolInputParameter>; schema: Tool }
32
>;
33
39
-export interface InputParamsSchema {
34
+export type InputParamsSchema = {
35
definitions: {
36
input: {
42
- properties: Record<string, JsonSchema7Type>;
37
+ type: string;
38
+ properties: Record<string, unknown>;
39
required?: string[];
40
};
41
};
42
+};
43
+
44
+export type CustomToolInputParameter = z.ZodType;
45
+
46
+export interface CustomToolRegistryItem {
47
+ options: CustomToolOptions<CustomToolInputParameter>;
48
+ schema: Tool;
49
}
50
51
export interface ExecuteMetadata {
packages/core/test/tools/customTools.test.ts
+144
-34
@@ -4,6 +4,9 @@ import { mockClient } from '../utils/mocks/client.mock';
4
import { toolMocks } from '../utils/mocks/data.mock';
5
import ComposioClient from '@composio/client';
6
import { z } from 'zod';
7
+import { ComposioToolNotFoundError } from '../../src/errors/ToolErrors';
8
+import { ComposioConnectedAccountNotFoundError } from '../../src/errors/ConnectedAccountsErrors';
9
+import { ValidationError } from '../../src/errors';
10
11
describe('CustomTools', () => {
12
let customTools: CustomTools;
@@ -89,61 +92,168 @@ describe('CustomTools', () => {
92
});
93
94
describe('executeCustomTool', () => {
95
+ const executeParams = {
96
+ arguments: { query: 'test query' },
97
+ userId: 'test-user',
98
+ };
99
+
100
it('should execute a custom tool with provided parameters', async () => {
101
// Add a tool to the registry
102
await customTools.createTool(toolOptions);
103
96
- const inputParams = { query: 'test query' };
97
- const metadata = { userId: 'test-user' };
98
-
99
- const result = await customTools.executeCustomTool(toolOptions.slug, inputParams, metadata);
104
+ const result = await customTools.executeCustomTool(toolOptions.slug, executeParams);
105
101
- expect(toolOptions.execute).toHaveBeenCalledWith(inputParams, {}, expect.any(Function));
106
+ expect(toolOptions.execute).toHaveBeenCalledWith(
107
+ executeParams.arguments,
108
+ {},
109
+ expect.any(Function)
110
+ );
111
expect(result).toEqual(toolMocks.toolExecuteResponse);
112
});
113
114
it('should throw an error if tool does not exist', async () => {
115
const nonExistentSlug = 'NON_EXISTENT';
107
- const inputParams = { query: 'test query' };
108
- const metadata = { userId: 'test-user' };
116
110
- await expect(
111
- customTools.executeCustomTool(nonExistentSlug, inputParams, metadata)
112
- ).rejects.toThrow(`Tool with slug ${nonExistentSlug} not found`);
117
+ await expect(customTools.executeCustomTool(nonExistentSlug, executeParams)).rejects.toThrow(
118
+ ComposioToolNotFoundError
119
+ );
120
});
121
115
- it('should fetch auth credentials for toolkit-based custom tools', async () => {
116
- // Add a toolkit-based tool
122
+ it('should throw validation error for invalid input parameters', async () => {
123
+ await customTools.createTool(toolOptions);
124
+ const invalidParams = {
125
+ ...executeParams,
126
+ arguments: { invalidField: 'test' },
127
+ };
128
+
129
+ await expect(customTools.executeCustomTool(toolOptions.slug, invalidParams)).rejects.toThrow(
130
+ ValidationError
131
+ );
132
+ });
133
+
134
+ describe('toolkit-based custom tools', () => {
135
const toolkitTool = {
136
...toolOptions,
137
toolkitSlug: 'TEST_TOOLKIT',
138
};
121
- await customTools.createTool(toolkitTool);
122
-
123
- // Mock toolkit and connected account retrieval
124
- mockClient.toolkits.retrieve.mockResolvedValueOnce({ slug: 'TEST_TOOLKIT' });
125
- mockClient.connectedAccounts.list.mockResolvedValueOnce({
126
- items: [
127
- {
128
- id: 'conn-123',
129
- data: {
130
- connectionParams: { apiKey: 'test-key' },
131
- },
132
- },
133
- ],
134
- totalPages: 1,
139
+
140
+ const mockConnectedAccount = {
141
+ id: 'conn-123',
142
+ auth_config: {
143
+ id: 'auth-123',
144
+ auth_scheme: 'OAUTH2',
145
+ is_composio_managed: true,
146
+ is_disabled: false,
147
+ },
148
+ user_id: 'test-user',
149
+ data: {
150
+ apiKey: 'test-key',
151
+ },
152
+ status: 'ACTIVE',
153
+ status_reason: null,
154
+ toolkit: {
155
+ slug: 'TEST_TOOLKIT',
156
+ },
157
+ test_request_endpoint: 'https://api.test.com',
158
+ is_disabled: false,
159
+ created_at: '2024-01-01T00:00:00Z',
160
+ updated_at: '2024-01-01T00:00:00Z',
161
+ };
162
+
163
+ beforeEach(async () => {
164
+ await customTools.createTool(toolkitTool);
165
+ mockClient.toolkits.retrieve.mockResolvedValue({ slug: 'TEST_TOOLKIT' });
166
});
167
137
- const inputParams = { query: 'test query' };
138
- const metadata = { userId: 'test-user' };
168
+ it('should fetch and use auth credentials for toolkit-based custom tools', async () => {
169
+ mockClient.connectedAccounts.list.mockResolvedValueOnce({
170
+ items: [mockConnectedAccount],
171
+ totalPages: 1,
172
+ });
173
140
- await customTools.executeCustomTool(toolkitTool.slug, inputParams, metadata);
174
+ await customTools.executeCustomTool(toolkitTool.slug, executeParams);
175
142
- expect(toolkitTool.execute).toHaveBeenCalledWith(
143
- inputParams,
144
- { apiKey: 'test-key' },
145
- expect.any(Function)
146
- );
176
+ expect(toolkitTool.execute).toHaveBeenCalledWith(
177
+ executeParams.arguments,
178
+ mockConnectedAccount.data,
179
+ expect.any(Function)
180
+ );
181
+ });
182
+
183
+ it('should use specified connected account when connectedAccountId is provided', async () => {
184
+ const specificConnectedAccountId = 'conn-456';
185
+ const specificConnectedAccount = {
186
+ ...mockConnectedAccount,
187
+ id: specificConnectedAccountId,
188
+ };
189
+
190
+ mockClient.connectedAccounts.list.mockResolvedValueOnce({
191
+ items: [mockConnectedAccount, specificConnectedAccount],
192
+ totalPages: 1,
193
+ });
194
+
195
+ await customTools.executeCustomTool(toolkitTool.slug, {
196
+ ...executeParams,
197
+ connectedAccountId: specificConnectedAccountId,
198
+ });
199
+
200
+ expect(toolkitTool.execute).toHaveBeenCalledWith(
201
+ executeParams.arguments,
202
+ specificConnectedAccount.data,
203
+ expect.any(Function)
204
+ );
205
+ });
206
+
207
+ it('should throw error when toolkit is not found', async () => {
208
+ mockClient.toolkits.retrieve.mockRejectedValueOnce(new Error('Toolkit not found'));
209
+
210
+ await expect(
211
+ customTools.executeCustomTool(toolkitTool.slug, executeParams)
212
+ ).rejects.toThrow(ComposioToolNotFoundError);
213
+ });
214
+
215
+ it('should throw error when no connected accounts are found', async () => {
216
+ mockClient.connectedAccounts.list.mockResolvedValueOnce({
217
+ items: [],
218
+ totalPages: 1,
219
+ });
220
+
221
+ await expect(
222
+ customTools.executeCustomTool(toolkitTool.slug, executeParams)
223
+ ).rejects.toThrow(ComposioConnectedAccountNotFoundError);
224
+ });
225
+
226
+ it('should throw error when specified connected account is not found', async () => {
227
+ mockClient.connectedAccounts.list.mockResolvedValueOnce({
228
+ items: [mockConnectedAccount],
229
+ totalPages: 1,
230
+ });
231
+
232
+ await expect(
233
+ customTools.executeCustomTool(toolkitTool.slug, {
234
+ ...executeParams,
235
+ connectedAccountId: 'non-existent-id',
236
+ })
237
+ ).rejects.toThrow(ComposioConnectedAccountNotFoundError);
238
+ });
239
+
240
+ it('should throw error when trying to use executeToolRequest with custom toolkit', async () => {
241
+ const customToolkitTool = {
242
+ ...toolOptions,
243
+ toolkitSlug: 'custom',
244
+ execute: async (input: any, auth: any, executeToolRequest: any) => {
245
+ return executeToolRequest({ slug: 'TEST_TOOL', arguments: {} });
246
+ },
247
+ };
248
+
249
+ await customTools.createTool(customToolkitTool);
250
+
251
+ await expect(
252
+ customTools.executeCustomTool(customToolkitTool.slug, executeParams)
253
+ ).rejects.toThrow(
254
+ 'Custom tools without a toolkit cannot be executed using the executeToolRequest function'
255
+ );
256
+ });
257
});
258
});
259
});
packages/core/test/tools/tools.test.ts
+1
-1
@@ -346,7 +346,7 @@ describe('Tools', () => {
346
const result = await context.tools.execute(slug, body);
347
348
expect(getCustomToolBySlugSpy).toHaveBeenCalledWith(slug);
349
- expect(executeCustomToolSpy).toHaveBeenCalledWith(slug, body, expect.any(Object));
349
+ expect(executeCustomToolSpy).toHaveBeenCalledWith(slug, body);
350
expect(result).toEqual(toolMocks.toolExecuteResponse);
351
});
352
pnpm-lock.yaml
+19
@@ -89,6 +89,25 @@ importers:
89
specifier: ^5.8.3
90
version: 5.8.3
91
92
+ examples/custom-tools:
93
+ dependencies:
94
+ '@composio/core':
95
+ specifier: workspace:*
96
+ version: link:../../packages/core
97
+ dotenv:
98
+ specifier: ^16.4.1
99
+ version: 16.5.0
100
+ zod:
101
+ specifier: ^3.24.2
102
+ version: 3.24.4
103
+ devDependencies:
104
+ '@types/bun':
105
+ specifier: ^1.2.9
106
+ version: 1.2.13
107
+ typescript:
108
+ specifier: ^5.8.3
109
+ version: 5.8.3
110
+
111
examples/error-handling-demo:
112
dependencies:
113
'@composio/core':