1
-/**
2
- * @fileoverview Custom tools class for Composio SDK, used to manage custom tools created by users.
3
- *
4
- * @author Musthaq Ahamad <musthaq@composio.dev>
5
- * @date 2025-05-05
6
- * @module CustomTools
7
- */
8
-import ComposioClient from '@composio/client';
9
-import {
10
- CustomToolInputParameter,
11
- CustomToolOptions,
12
- CustomToolRegistry,
13
- InputParamsSchema,
14
-} from '../types/customTool.types';
15
-import * as zodToJsonSchema from 'zod-to-json-schema';
16
-import {
17
- Tool,
18
- ToolExecuteParams,
19
- ToolExecuteResponse,
20
- ToolList,
21
- ToolProxyParams,
22
-} from '../types/tool.types';
23
-import logger from '../utils/logger';
24
-import {
25
- ComposioInvalidExecuteFunctionError,
26
- ComposioToolNotFoundError,
27
-} from '../errors/ToolErrors';
28
-import { ComposioConnectedAccountNotFoundError } from '../errors/ConnectedAccountsErrors';
29
-import { ComposioError } from '../errors/ComposioError';
30
-import { telemetry } from '../telemetry/Telemetry';
31
-import { ConnectedAccountRetrieveResponse } from '../types/connectedAccounts.types';
32
-import { ValidationError } from '../errors';
33
-import { transformConnectedAccountResponse } from '../utils/transformers/connectedAccounts';
34
-import { ConnectionData } from '../types/connectedAccountAuthStates.types';
35
-import { AuthSchemeTypes } from '../types/authConfigs.types';
36
-
37
-export class CustomTools {
38
- private readonly client: ComposioClient;
39
- private readonly customToolsRegistry: CustomToolRegistry;
40
-
41
- constructor(client: ComposioClient) {
42
- if (!client) {
43
- throw new ComposioError('ComposioClient is required');
44
- }
45
- this.client = client;
46
- this.customToolsRegistry = new Map();
47
- telemetry.instrument(this, 'CustomTools');
48
- }
49
-
50
- /**
51
- * Create a custom tool and registers it in the registry.
52
- * This is just an in memory registry and is not persisted.
53
- * @param {CustomToolOptions} toolOptions CustomToolOptions
54
- * @returns {Tool} The tool created
55
- *
56
- * @example
57
- * ```typescript
58
- * // Create a custom tool with input parameters
59
- * const customTool = await composio.customTools.createTool({
60
- * name: 'My Custom Tool',
61
- * description: 'A tool that performs a custom operation',
62
- * slug: 'MY_CUSTOM_TOOL',
63
- * inputParams: z.object({
64
- * query: z.string().describe('The search query'),
65
- * limit: z.number().optional().describe('Maximum number of results')
66
- * }),
67
- * execute: async (input, connectionConfig, executeToolRequest) => {
68
- * // Custom implementation logic
69
- * return {
70
- * data: { results: ['result1', 'result2'] }
71
- * };
72
- * }
73
- * });
74
- * ```
75
- */
76
- async createTool<T extends CustomToolInputParameter>(
77
- toolOptions: CustomToolOptions<T>
78
- ): Promise<Tool> {
79
- const { slug, execute, inputParams, name, description } = toolOptions;
80
- if (!slug || !execute || !inputParams || !name) {
81
- throw new Error('Invalid tool options');
82
- }
83
- // generate the input parameters schema
84
- const paramsSchema: InputParamsSchema = zodToJsonSchema.default(inputParams, {
85
- name: 'input',
86
- }) as InputParamsSchema;
87
- const paramsSchemaJson = paramsSchema.definitions.input;
88
- const toolSchema: Tool = {
89
- name: name,
90
- slug: slug,
91
- description: description,
92
- inputParameters: {
93
- title: name,
94
- type: 'object',
95
- description: description,
96
- properties: paramsSchemaJson.properties,
97
- required: paramsSchemaJson.required,
98
- },
99
- // the output parameters are not used yet
100
- outputParameters: {
101
- type: 'object',
102
- title: `Response for ${name}`,
103
- properties: {},
104
- },
105
- tags: [],
106
- // this is never set to the user provided toolkitslug so that we can differentiate
107
- // the toolkitslug is used via the execute function.
108
- toolkit: { name: 'custom', slug: 'custom' },
109
- };
110
-
111
- this.customToolsRegistry.set(slug.toLowerCase(), {
112
- options: toolOptions as unknown as CustomToolOptions<CustomToolInputParameter>,
113
- schema: toolSchema,
114
- });
115
- return toolSchema;
116
- }
117
-
118
- /**
119
- * Get all the custom tools from the registry.
120
- * @param {string[]} param0.toolSlugs The slugs of the tools to get
121
- * @returns {ToolList} The list of tools
122
- *
123
- * @example
124
- * ```typescript
125
- * // Get all custom tools
126
- * const allTools = await composio.customTools.getCustomTools({});
127
- *
128
- * // Get specific custom tools by slug
129
- * const specificTools = await composio.customTools.getCustomTools({
130
- * toolSlugs: ['MY_CUSTOM_TOOL', 'ANOTHER_CUSTOM_TOOL']
131
- * });
132
- * ```
133
- */
134
- async getCustomTools({ toolSlugs }: { toolSlugs?: string[] }): Promise<ToolList> {
135
- const tools: Tool[] = [];
136
-
137
- if (toolSlugs) {
138
- // If specific slugs are provided, only return those tools
139
- for (const slug of toolSlugs) {
140
- const tool = this.customToolsRegistry.get(slug.toLowerCase());
141
- if (tool) {
142
- tools.push(tool.schema);
143
- }
144
- }
145
- } else {
146
- // If no slugs provided, return all tools
147
- return Array.from(this.customToolsRegistry.values()).map(tool => tool.schema);
148
- }
149
-
150
- return tools;
151
- }
152
-
153
- /**
154
- * Get a custom tool by slug from the registry.
155
- * @param {string} slug The slug of the tool to get
156
- * @returns {Tool} The tool
157
- *
158
- * @example
159
- * ```typescript
160
- * // Get a specific custom tool by its slug
161
- * const myTool = await composio.customTools.getCustomToolBySlug('MY_CUSTOM_TOOL');
162
- * if (myTool) {
163
- * console.log(`Found tool: ${myTool.name}`);
164
- * } else {
165
- * console.log('Tool not found');
166
- * }
167
- * ```
168
- */
169
- async getCustomToolBySlug(slug: string): Promise<Tool | undefined> {
170
- try {
171
- const tool = this.customToolsRegistry.get(slug.toLowerCase());
172
- return tool?.schema;
173
- } catch (error) {
174
- logger.error(`Error getting custom tool: ${error}`);
175
- return undefined;
176
- }
177
- }
178
-
179
- /**
180
- * Get the connected account for the user and toolkit.
181
- * @param {string} toolkitSlug The slug of the toolkit
182
- * @param {ExecuteMetadata} metadata The metadata of the execution
183
- * @returns {ConnectedAccount} The connected account
184
- */
185
- private async getConnectedAccountForToolkit(
186
- toolkitSlug: string,
187
- userId: string,
188
- connectedAccountId?: string
189
- ): Promise<ConnectedAccountRetrieveResponse | null> {
190
- try {
191
- await this.client.toolkits.retrieve(toolkitSlug);
192
- // check if the toolkit is a no auth toolkit
193
- const toolkit = await this.client.toolkits.retrieve(toolkitSlug);
194
- const isNoAuthToolkit = toolkit.auth_config_details?.some(
195
- details => details.mode === AuthSchemeTypes.NO_AUTH
196
- );
197
- if (isNoAuthToolkit) {
198
- return null;
199
- }
200
- } catch (error) {
201
- throw new ComposioToolNotFoundError(`Toolkit with slug ${toolkitSlug} not found`, {
202
- cause: error,
203
- });
204
- }
205
- const connectedAccounts = await this.client.connectedAccounts.list({
206
- toolkit_slugs: [toolkitSlug],
207
- user_ids: [userId],
208
- });
209
-
210
- if (!connectedAccounts.items.length) {
211
- throw new ComposioConnectedAccountNotFoundError(
212
- `No connected accounts found for toolkit ${toolkitSlug}`
213
- );
214
- }
215
- // if a connected account id is provided, use it, otherwise use the first connected account
216
- const connectedAccount = connectedAccountId
217
- ? connectedAccounts.items.find(item => item.id === connectedAccountId)
218
- : connectedAccounts.items[0];
219
-
220
- if (!connectedAccount) {
221
- throw new ComposioConnectedAccountNotFoundError(
222
- `Connected account not found for toolkit ${toolkitSlug} for user ${userId}`
223
- );
224
- }
225
-
226
- return transformConnectedAccountResponse(connectedAccount);
227
- }
228
-
229
- /**
230
- * Execute a custom tool
231
- *
232
- * @description If a toolkit is used, the connected account id is used to execute the tool.
233
- * If a connected account id is provided, it is used to execute the tool.
234
- * If a connected account id is not provided, the first connected account for the toolkit is used.
235
- *
236
- * @param {slug} slug The slug of the tool to execute
237
- * @param {Record<string, unknown>} inputParams The input parameters for the tool
238
- * @param {ExecuteMetadata} metadata The metadata of the execution
239
- * @returns {Promise<ToolExecuteResponse>} The response from the tool
240
- */
241
- async executeCustomTool(slug: string, body: ToolExecuteParams): Promise<ToolExecuteResponse> {
242
- const tool = this.customToolsRegistry.get(slug.toLowerCase());
243
- if (!tool) {
244
- throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);
245
- }
246
-
247
- let connectionConfig: ConnectionData | null = null;
248
- const { toolkitSlug, execute, inputParams } = tool.options;
249
- // if a toolkit is used, get the connected account, and auth credentials
250
- let connectedAccountId: string | undefined = body.connectedAccountId;
251
- // if a toolkit is used, and a userId is provided, get the connected account
252
- if (toolkitSlug && toolkitSlug !== 'custom' && body.userId) {
253
- const connectedAccount = await this.getConnectedAccountForToolkit(
254
- toolkitSlug,
255
- body.userId,
256
- body.connectedAccountId
257
- );
258
- logger.debug(
259
- `[CustomTool] Connected account for ${toolkitSlug} found for user ${body.userId}`,
260
- JSON.stringify(connectedAccount, null, 2)
261
- );
262
- if (!connectedAccount) {
263
- throw new ComposioConnectedAccountNotFoundError(
264
- `Connected account not found for toolkit ${toolkitSlug} for user ${body.userId}`,
265
- {
266
- meta: {
267
- toolkitSlug,
268
- userId: body.userId,
269
- },
270
- }
271
- );
272
- }
273
- connectionConfig = connectedAccount.state ?? null;
274
- connectedAccountId = connectedAccount.id;
275
- }
276
-
277
- if (typeof execute !== 'function') {
278
- throw new ComposioInvalidExecuteFunctionError('Invalid execute function', {
279
- meta: {
280
- toolSlug: slug,
281
- },
282
- });
283
- }
284
- // create a tool proxy request for users to execute in case of a toolkit being used
285
- const executeToolRequest = async (data: ToolProxyParams): Promise<ToolExecuteResponse> => {
286
- // if the toolkit is custom, throw an error while trying to execute the tool by user
287
- if (toolkitSlug && toolkitSlug === 'custom') {
288
- throw new ComposioInvalidExecuteFunctionError(
289
- 'Custom tools without a toolkit cannot be executed using the executeToolRequest function',
290
- {
291
- possibleFixes: [
292
- 'Please manually execute the tool using your logic.',
293
- 'Pass a toolkit slug to execute the tool on behalf of a toolkit credentials',
294
- ],
295
- }
296
- );
297
- }
298
- // map the parameters to the composio format
299
- const parameters = data.parameters?.map(param => ({
300
- name: param.name,
301
- type: param.in,
302
- value: param.value.toString(),
303
- }));
304
-
305
- // execute the tool
306
- const response = await this.client.tools.proxy({
307
- endpoint: data.endpoint,
308
- method: data.method,
309
- parameters: parameters,
310
- body: data.body,
311
- connected_account_id: connectedAccountId,
312
- /**
313
- * @deprecated
314
- * @description
315
- * This parameter is deprecated and will be removed in the future.
316
- * Please use custom_auth_params instead.
317
- *
318
- */
319
- // @ts-ignore
320
- custom_connection_data: data.customConnectionData,
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
-
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, connectionConfig, executeToolRequest);
341
- }
342
-}