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 type issues
haxzie committed
May 20, 2025 at 18:49 UTC
9f716864ea78be27eb1f44d92b20d57c32e770b2
10 files changed
+905
-162
packages/core/src/errors/ValidationError.ts
+1
@@ -41,5 +41,6 @@ export class ValidationError extends ComposioError {
41
cause: zodErrorInstance,
42
});
43
this.zodError = zodErrorInstance;
44
+ this.name = 'ValidationError';
45
}
46
}
packages/core/src/models/AuthConfigs.ts
+145
-30
@@ -50,6 +50,18 @@ export class AuthConfigs {
50
return this.client;
51
}
52
53
+ /**
54
+ * Transforms an auth config response from API format to SDK format.
55
+ *
56
+ * This method converts property names from snake_case to camelCase and reorganizes
57
+ * the data structure to match the SDK's standardized format for auth configurations.
58
+ *
59
+ * @param {ComposioAuthConfigRetrieveResponse} authConfig - The raw API response to transform
60
+ * @returns {AuthConfigRetrieveResponse} The transformed auth config data
61
+ * @throws {ValidationError} If the response fails validation against the expected schema
62
+ *
63
+ * @private
64
+ */
65
private parseAuthConfigRetrieveResponse(
66
authConfig: ComposioAuthConfigRetrieveResponse
67
): AuthConfigRetrieveResponse {
@@ -78,10 +90,30 @@ export class AuthConfigs {
90
}
91
92
/**
81
- * List all auth configs
82
- * @param {AuthConfigListParams} query - Query parameters for filtering auth configs
83
- * @param {RequestOptions} options - Request options
84
- * @returns {Promise<AuthConfigListResponse>} List of auth configs
93
+ * Lists authentication configurations based on provided filter criteria.
94
+ *
95
+ * This method retrieves auth configs from the Composio API, transforms them to the SDK format,
96
+ * and supports filtering by various parameters.
97
+ *
98
+ * @param {AuthConfigListParams} [query] - Optional query parameters for filtering auth configs
99
+ * @returns {Promise<AuthConfigListResponse>} A paginated list of auth configurations
100
+ * @throws {ValidationError} If the query parameters or response fail validation
101
+ *
102
+ * @example
103
+ * ```typescript
104
+ * // List all auth configs
105
+ * const allConfigs = await composio.authConfigs.list();
106
+ *
107
+ * // List auth configs for a specific toolkit
108
+ * const githubConfigs = await composio.authConfigs.list({
109
+ * toolkitSlug: 'github'
110
+ * });
111
+ *
112
+ * // List Composio-managed auth configs
113
+ * const managedConfigs = await composio.authConfigs.list({
114
+ * isComposioManaged: true
115
+ * });
116
+ * ```
117
*/
118
async list(query?: AuthConfigListParams): Promise<AuthConfigListResponse> {
119
const parsedQuery = query ? AuthConfigListParamsSchema.parse(query) : undefined;
@@ -147,10 +179,23 @@ export class AuthConfigs {
179
}
180
181
/**
150
- * Get an auth config by nanoid
151
- * @param {string} nanoid - Unique identifier of the auth config
152
- * @param {RequestOptions} options - Request options
153
- * @returns {Promise<AuthConfigRetrieveResponse>} Auth config details
182
+ * Retrieves a specific authentication configuration by its ID.
183
+ *
184
+ * This method fetches detailed information about a single auth config
185
+ * and transforms the response to the SDK's standardized format.
186
+ *
187
+ * @param {string} nanoid - The unique identifier of the auth config to retrieve
188
+ * @returns {Promise<AuthConfigRetrieveResponse>} The auth config details
189
+ * @throws {Error} If the auth config cannot be found or an API error occurs
190
+ * @throws {ValidationError} If the response fails validation
191
+ *
192
+ * @example
193
+ * ```typescript
194
+ * // Get an auth config by ID
195
+ * const authConfig = await composio.authConfigs.get('auth_abc123');
196
+ * console.log(authConfig.name); // e.g., 'GitHub Auth'
197
+ * console.log(authConfig.toolkit.slug); // e.g., 'github'
198
+ * ```
199
*/
200
async get(nanoid: string): Promise<AuthConfigRetrieveResponse> {
201
const result = await this.client.authConfigs.retrieve(nanoid);
@@ -158,11 +203,34 @@ export class AuthConfigs {
203
}
204
205
/**
161
- * Update an auth config
162
- * @param {string} nanoid - Unique identifier of the auth config to update
163
- * @param {AuthConfigUpdateParams} data - Data to update
164
- * @param {RequestOptions} options - Request options
165
- * @returns {Promise<AuthConfigUpdateResponse>} Updated auth config
206
+ * Updates an existing authentication configuration.
207
+ *
208
+ * This method allows you to modify properties of an auth config such as credentials,
209
+ * scopes, or tool restrictions. The update type (custom or default) determines which
210
+ * fields can be updated.
211
+ *
212
+ * @param {string} nanoid - The unique identifier of the auth config to update
213
+ * @param {AuthConfigUpdateParams} data - The data to update, which can be either custom or default type
214
+ * @returns {Promise<AuthConfigUpdateResponse>} The updated auth config
215
+ * @throws {ValidationError} If the update parameters are invalid
216
+ * @throws {Error} If the auth config cannot be found or updated
217
+ *
218
+ * @example
219
+ * ```typescript
220
+ * // Update a custom auth config with new credentials
221
+ * const updatedConfig = await composio.authConfigs.update('auth_abc123', {
222
+ * type: 'custom',
223
+ * credentials: {
224
+ * apiKey: 'new-api-key-value'
225
+ * }
226
+ * });
227
+ *
228
+ * // Update a default auth config with new scopes
229
+ * const updatedConfig = await composio.authConfigs.update('auth_abc123', {
230
+ * type: 'default',
231
+ * scopes: ['read:user', 'repo']
232
+ * });
233
+ * ```
234
*/
235
async update(nanoid: string, data: AuthConfigUpdateParams): Promise<AuthConfigUpdateResponse> {
236
const parsedData = AuthConfigUpdateParamsSchema.safeParse(data);
@@ -186,21 +254,46 @@ export class AuthConfigs {
254
}
255
256
/**
189
- * Delete an auth config
190
- * @param {string} nanoid - Unique identifier of the auth config to delete
191
- * @param {RequestOptions} options - Request options
192
- * @returns {Promise<AuthConfigDeleteResponse>} Response from deletion
257
+ * Deletes an authentication configuration.
258
+ *
259
+ * This method permanently removes an auth config from the Composio platform.
260
+ * This action cannot be undone and will prevent any connected accounts that use
261
+ * this auth config from functioning.
262
+ *
263
+ * @param {string} nanoid - The unique identifier of the auth config to delete
264
+ * @returns {Promise<AuthConfigDeleteResponse>} The deletion response
265
+ * @throws {Error} If the auth config doesn't exist or cannot be deleted
266
+ *
267
+ * @example
268
+ * ```typescript
269
+ * // Delete an auth config
270
+ * await composio.authConfigs.delete('auth_abc123');
271
+ * ```
272
*/
273
async delete(nanoid: string): Promise<AuthConfigDeleteResponse> {
274
return this.client.authConfigs.delete(nanoid);
275
}
276
277
/**
199
- * Update the status of an auth config
200
- * @param {string} status - The status to update the auth config to
201
- * @param {string} nanoid - Unique identifier of the auth config
202
- * @param {RequestOptions} options - Request options
203
- * @returns {Promise<AuthConfigUpdateStatusResponse>} Updated auth config details
278
+ * Updates the status of an authentication configuration.
279
+ *
280
+ * This method allows you to enable or disable an auth config. When disabled,
281
+ * the auth config cannot be used to create new connected accounts or authenticate
282
+ * with third-party services.
283
+ *
284
+ * @param {string} status - The status to set ('ENABLED' or 'DISABLED')
285
+ * @param {string} nanoid - The unique identifier of the auth config
286
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
287
+ * @throws {Error} If the auth config cannot be found or the status cannot be updated
288
+ *
289
+ * @example
290
+ * ```typescript
291
+ * // Disable an auth config
292
+ * await composio.authConfigs.updateStatus('DISABLED', 'auth_abc123');
293
+ *
294
+ * // Enable an auth config
295
+ * await composio.authConfigs.updateStatus('ENABLED', 'auth_abc123');
296
+ * ```
297
*/
298
async updateStatus(
299
status: 'ENABLED' | 'DISABLED',
@@ -210,20 +303,42 @@ export class AuthConfigs {
303
}
304
305
/**
213
- * Enable an auth config
214
- * @param {string} nanoid - Unique identifier of the auth config
215
- * @param {RequestOptions} options - Request options
216
- * @returns {Promise<AuthConfigUpdateStatusResponse>} Updated auth config details
306
+ * Enables an authentication configuration.
307
+ *
308
+ * This is a convenience method that calls updateStatus with 'ENABLED'.
309
+ * When enabled, the auth config can be used to create new connected accounts
310
+ * and authenticate with third-party services.
311
+ *
312
+ * @param {string} nanoid - The unique identifier of the auth config to enable
313
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
314
+ * @throws {Error} If the auth config cannot be found or enabled
315
+ *
316
+ * @example
317
+ * ```typescript
318
+ * // Enable an auth config
319
+ * await composio.authConfigs.enable('auth_abc123');
320
+ * ```
321
*/
322
async enable(nanoid: string): Promise<AuthConfigUpdateStatusResponse> {
323
return this.client.authConfigs.updateStatus('ENABLED', { nanoid });
324
}
325
326
/**
223
- * Disable an auth config
224
- * @param {string} nanoid - Unique identifier of the auth config
225
- * @param {RequestOptions} options - Request options
226
- * @returns {Promise<AuthConfigUpdateStatusResponse>} Updated auth config details
327
+ * Disables an authentication configuration.
328
+ *
329
+ * This is a convenience method that calls updateStatus with 'DISABLED'.
330
+ * When disabled, the auth config cannot be used to create new connected accounts
331
+ * or authenticate with third-party services, but existing connections may continue to work.
332
+ *
333
+ * @param {string} nanoid - The unique identifier of the auth config to disable
334
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
335
+ * @throws {Error} If the auth config cannot be found or disabled
336
+ *
337
+ * @example
338
+ * ```typescript
339
+ * // Disable an auth config
340
+ * await composio.authConfigs.disable('auth_abc123');
341
+ * ```
342
*/
343
async disable(nanoid: string): Promise<AuthConfigUpdateStatusResponse> {
344
return this.client.authConfigs.updateStatus('DISABLED', { nanoid });
packages/core/src/models/ConnectedAccounts.ts
+150
-32
@@ -7,18 +7,22 @@
7
*/
8
import ComposioClient from '@composio/client';
9
import {
10
- ConnectedAccountListParams,
11
- ConnectedAccountListResponse,
10
ConnectedAccountDeleteResponse,
11
ConnectedAccountRefreshResponse,
12
ConnectedAccountUpdateStatusParams,
13
ConnectedAccountUpdateStatusResponse,
14
+ ConnectedAccountListParams as ConnectedAccountListParamsRaw,
15
ConnectedAccountRetrieveResponse as ConnectedAccountRetrieveResponseRaw,
16
+ ConnectedAccountListResponse as ConnectedAccountListResponseRaw,
17
} from '@composio/client/resources/connected-accounts';
18
import {
19
CreateConnectedAccountOptions,
20
ConnectedAccountRetrieveResponse,
21
ConnectedAccountRetrieveResponseSchema,
22
+ ConnectedAccountListParams,
23
+ ConnectedAccountListParamsSchema,
24
+ ConnectedAccountListResponse,
25
+ ConnectedAccountListResponseSchema,
26
} from '../types/connectedAccounts.types';
27
import { ConnectionRequest } from './ConnectionRequest';
28
import { ValidationError } from '../errors/ValidationError';
@@ -36,23 +40,8 @@ export class ConnectedAccounts {
40
this.client = client;
41
}
42
39
- /**
40
- * List all connected accounts
41
- * @param {ConnectedAccountListParams} query - Query parameters for filtering connected accounts
42
- * @param {RequestOptions} options - Request options
43
- * @returns {Promise<ConnectedAccountListResponse>} List of connected accounts
44
- */
45
- async list(query?: ConnectedAccountListParams): Promise<ConnectedAccountListResponse> {
46
- return this.client.connectedAccounts.list(query);
47
- }
48
-
49
- /**
50
- * Transform the raw response from the API to the expected format
51
- * @param {ConnectedAccountRetrieveResponseRaw} response - Raw response from the API
52
- * @returns {ConnectedAccountRetrieveResponse} Transformed response
53
- */
54
- transformConnectedAccountResponse(
55
- response: ConnectedAccountRetrieveResponseRaw
43
+ transformConnectedAccountRetrieveResponse(
44
+ response: ConnectedAccountRetrieveResponseRaw | ConnectedAccountListResponseRaw['items'][0]
45
): ConnectedAccountRetrieveResponse {
46
const result = ConnectedAccountRetrieveResponseSchema.safeParse({
47
...response,
@@ -69,12 +58,87 @@ export class ConnectedAccounts {
58
updatedAt: response.updated_at,
59
testRequestEndpoint: response.test_request_endpoint,
60
});
72
- if (result.error) {
61
+ if (!result.success) {
62
throw new ValidationError(result.error);
63
}
64
return result.data;
65
}
66
67
+ /**
68
+ * Lists all connected accounts based on provided filter criteria.
69
+ *
70
+ * This method retrieves connected accounts from the Composio API with optional filtering.
71
+ *
72
+ * @param {ConnectedAccountListParams} [query] - Optional query parameters for filtering connected accounts
73
+ * @returns {Promise<ConnectedAccountListResponse>} A paginated list of connected accounts
74
+ * @throws {ValidationError} If the query fails validation against the expected schema
75
+ * @example
76
+ * ```typescript
77
+ * // List all connected accounts
78
+ * const allAccounts = await composio.connectedAccounts.list();
79
+ *
80
+ * // List accounts for a specific user
81
+ * const userAccounts = await composio.connectedAccounts.list({
82
+ * userIds: ['user123']
83
+ * });
84
+ *
85
+ * // List accounts for a specific toolkit
86
+ * const githubAccounts = await composio.connectedAccounts.list({
87
+ * toolkitSlugs: ['github']
88
+ * });
89
+ * ```
90
+ */
91
+ async list(query?: ConnectedAccountListParams): Promise<ConnectedAccountListResponse> {
92
+ let rawQuery: ConnectedAccountListParamsRaw | undefined = undefined;
93
+
94
+ if (query) {
95
+ const parsedQuery = ConnectedAccountListParamsSchema.safeParse(query);
96
+ if (!parsedQuery.success) {
97
+ throw new ValidationError(parsedQuery.error);
98
+ }
99
+ rawQuery = {
100
+ auth_config_ids: parsedQuery.data.authConfigIds,
101
+ cursor: parsedQuery.data.cursor,
102
+ labels: parsedQuery.data.labels,
103
+ limit: parsedQuery.data.limit,
104
+ order_by: parsedQuery.data.orderBy,
105
+ statuses: parsedQuery.data.statuses,
106
+ toolkit_slugs: parsedQuery.data.toolkitSlugs,
107
+ user_ids: parsedQuery.data.userIds,
108
+ };
109
+ }
110
+
111
+ const result = await this.client.connectedAccounts.list(rawQuery);
112
+
113
+ const parsedResponse = ConnectedAccountListResponseSchema.safeParse({
114
+ items: result.items.map(this.transformConnectedAccountRetrieveResponse),
115
+ nextCursor: result.next_cursor,
116
+ totalPages: result.total_pages,
117
+ });
118
+ if (!parsedResponse.success) {
119
+ throw new ValidationError(parsedResponse.error);
120
+ }
121
+ return parsedResponse.data;
122
+ }
123
+
124
+ /**
125
+ * Transforms connected account data from API format to SDK format.
126
+ *
127
+ * This method converts property names from snake_case to camelCase and reorganizes
128
+ * the data structure to match the SDK's standardized format for connected accounts.
129
+ *
130
+ * @param {ConnectedAccountRetrieveResponseRaw} response - The raw API response to transform
131
+ * @returns {ConnectedAccountRetrieveResponse} The transformed connected account data
132
+ * @throws {ValidationError} If the response fails validation against the expected schema
133
+ *
134
+ * @private
135
+ */
136
+ transformConnectedAccountResponse(
137
+ response: ConnectedAccountRetrieveResponseRaw
138
+ ): ConnectedAccountRetrieveResponse {
139
+ return this.transformConnectedAccountRetrieveResponse(response);
140
+ }
141
+
142
/**
143
* Compound function to create a new connected account.
144
* This function creates a new connected account and returns a connection request.
@@ -111,6 +175,28 @@ export class ConnectedAccounts {
175
return new ConnectionRequest(this.client, response.id, response.status, response.redirect_uri);
176
}
177
178
+ /**
179
+ * Waits for a connection request to complete and become active.
180
+ *
181
+ * This method continuously polls the Composio API to check the status of a connection
182
+ * until it either becomes active, enters a terminal error state, or times out.
183
+ *
184
+ * @param {string} connectedAccountId - The ID of the connected account to wait for
185
+ * @param {number} [timeout=60000] - Maximum time to wait in milliseconds (default: 60 seconds)
186
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The finalized connected account data
187
+ * @throws {ComposioConnectedAccountNotFoundError} If the connected account cannot be found
188
+ * @throws {ConnectionRequestFailedError} If the connection enters a failed, expired, or deleted state
189
+ * @throws {ConnectionRequestTimeoutError} If the connection does not complete within the timeout period
190
+ *
191
+ * @example
192
+ * ```typescript
193
+ * // Wait for a connection to complete with default timeout
194
+ * const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc');
195
+ *
196
+ * // Wait with a custom timeout of 2 minutes
197
+ * const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc', 120000);
198
+ * ```
199
+ */
200
async waitForConnection(
201
connectedAccountId: string,
202
timeout: number = 60000
@@ -120,10 +206,22 @@ export class ConnectedAccounts {
206
}
207
208
/**
123
- * Get a connected account by nanoid
124
- * @param {string} nanoid - Unique identifier of the connected account
125
- * @param {RequestOptions} options - Request options
126
- * @returns {Promise<ConnectedAccountRetrieveResponse>} Connected account details
209
+ * Retrieves a specific connected account by its ID.
210
+ *
211
+ * This method fetches detailed information about a single connected account
212
+ * and transforms the response to the SDK's standardized format.
213
+ *
214
+ * @param {string} nanoid - The unique identifier of the connected account
215
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The connected account details
216
+ * @throws {Error} If the connected account cannot be found or an API error occurs
217
+ *
218
+ * @example
219
+ * ```typescript
220
+ * // Get a connected account by ID
221
+ * const account = await composio.connectedAccounts.get('conn_abc123');
222
+ * console.log(account.status); // e.g., 'ACTIVE'
223
+ * console.log(account.toolkit.slug); // e.g., 'github'
224
+ * ```
225
*/
226
async get(nanoid: string): Promise<ConnectedAccountRetrieveResponse> {
227
const response = await this.client.connectedAccounts.retrieve(nanoid);
@@ -131,20 +229,40 @@ export class ConnectedAccounts {
229
}
230
231
/**
134
- * Delete a connected account
135
- * @param {string} nanoid - Unique identifier of the connected account to delete
136
- * @param {RequestOptions} options - Request options
137
- * @returns {Promise<ConnectedAccountDeleteResponse>} Response from deletion
232
+ * Deletes a connected account.
233
+ *
234
+ * This method permanently removes a connected account from the Composio platform.
235
+ * This action cannot be undone and will revoke any access tokens associated with the account.
236
+ *
237
+ * @param {string} nanoid - The unique identifier of the connected account to delete
238
+ * @returns {Promise<ConnectedAccountDeleteResponse>} The deletion response
239
+ * @throws {Error} If the account doesn't exist or cannot be deleted
240
+ *
241
+ * @example
242
+ * ```typescript
243
+ * // Delete a connected account
244
+ * await composio.connectedAccounts.delete('conn_abc123');
245
+ * ```
246
*/
247
async delete(nanoid: string): Promise<ConnectedAccountDeleteResponse> {
248
return this.client.connectedAccounts.delete(nanoid);
249
}
250
251
/**
144
- * Refresh a connected account's credentials
145
- * @param {string} nanoid - Unique identifier of the connected account to refresh
146
- * @param {RequestOptions} options - Request options
147
- * @returns {Promise<ConnectedAccountRefreshResponse>} Refreshed connected account details
252
+ * Refreshes a connected account's authentication credentials.
253
+ *
254
+ * This method attempts to refresh OAuth tokens or other credentials associated with
255
+ * the connected account. This is useful when a token has expired or is about to expire.
256
+ *
257
+ * @param {string} nanoid - The unique identifier of the connected account to refresh
258
+ * @returns {Promise<ConnectedAccountRefreshResponse>} The response containing the refreshed account details
259
+ * @throws {Error} If the account doesn't exist or credentials cannot be refreshed
260
+ *
261
+ * @example
262
+ * ```typescript
263
+ * // Refresh a connected account's credentials
264
+ * const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123');
265
+ * ```
266
*/
267
async refresh(nanoid: string): Promise<ConnectedAccountRefreshResponse> {
268
return this.client.connectedAccounts.refresh(nanoid);
packages/core/src/models/ConnectionRequest.ts
+34
-7
@@ -39,9 +39,16 @@ export class ConnectionRequest {
39
}
40
41
/**
42
- * Transform the response from the Composio API to the SDK format
43
- * @param response
44
- * @returns
42
+ * Transforms the raw connected account response from the Composio API to the SDK format.
43
+ *
44
+ * This method converts property names from snake_case to camelCase and reorganizes
45
+ * the data structure to match the SDK's standardized format.
46
+ *
47
+ * @param {OriginalConnectedAccountResponse} response - The raw API response to transform
48
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The transformed response
49
+ * @throws {ZodError} If the response fails validation against the expected schema
50
+ *
51
+ * @private
52
*/
53
private async transformResponse(
54
response: OriginalConnectedAccountResponse
@@ -73,10 +80,30 @@ export class ConnectionRequest {
80
}
81
82
/**
76
- * Wait for the connection to be established.
77
- * The function will poll the Composio API every second until the connection is established or the timeout is reached.
78
- * @param {number} timeout - The time in milliseconds to wait for the connection to be established. Default is 30 seconds.
79
- * @returns
83
+ * Waits for the connection request to complete and become active.
84
+ *
85
+ * This method continuously polls the Composio API to check the status of the connection request
86
+ * until it either becomes active, enters a terminal error state, or times out.
87
+ *
88
+ * @param {number} [timeout=60000] - Maximum time to wait in milliseconds before timing out (default: 60 seconds)
89
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The final connected account response when successful
90
+ * @throws {ComposioConnectedAccountNotFoundError} If the connected account cannot be found
91
+ * @throws {ConnectionRequestFailedError} If the connection enters a failed, expired, or deleted state
92
+ * @throws {ConnectionRequestTimeoutError} If the connection request does not complete within the timeout period
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * // Wait for connection with default timeout (60 seconds)
97
+ * try {
98
+ * const connection = await connectionRequest.waitForConnection();
99
+ * console.log('Connection established:', connection.id);
100
+ * } catch (error) {
101
+ * console.error('Connection failed:', error.message);
102
+ * }
103
+ *
104
+ * // Wait for connection with custom timeout (2 minutes)
105
+ * const connection = await connectionRequest.waitForConnection(120000);
106
+ * ```
107
*/
108
async waitForConnection(timeout: number = 60000): Promise<ConnectedAccountRetrieveResponse> {
109
try {
packages/core/src/models/CustomTools.ts
+2
-2
@@ -140,8 +140,8 @@ export class CustomTools {
140
});
141
}
142
const connectedAccounts = await this.client.connectedAccounts.list({
143
- toolkit_slug: toolkitSlug,
144
- user_id: metadata.userId,
143
+ toolkit_slugs: [toolkitSlug],
144
+ user_ids: [metadata.userId],
145
});
146
147
if (!connectedAccounts.items.length) {
packages/core/src/models/Toolkits.ts
+89
-40
@@ -33,9 +33,15 @@ export class Toolkits {
33
this.authorize = this.authorize.bind(this);
34
}
35
/**
36
- * List all toolkits available in the Composio SDK.
37
- * This method fetches the toolkits from the Composio API.
38
- * @returns {Promise<Toolkit[]>} List of toolkits
36
+ * Retrieves a list of toolkits based on the provided query parameters.
37
+ *
38
+ * This method fetches toolkits from the Composio API and transforms the response
39
+ * from snake_case to camelCase format for consistency with JavaScript/TypeScript conventions.
40
+ *
41
+ * @param {ToolkitListParams} query - The query parameters to filter toolkits
42
+ * @returns {Promise<ToolKitListResponse>} The transformed list of toolkits
43
+ *
44
+ * @private
45
*/
46
private async getToolkits(query: ToolkitListParams): Promise<ToolKitListResponse> {
47
const parsedQuery = ToolkitsListParamsSchema.parse(query);
@@ -67,11 +73,73 @@ export class Toolkits {
73
}
74
75
/**
70
- * Fetches a toolkit by its Slug.
71
- * This method retrieves the toolkit from the Composio API.
72
- * @param slug - The ID of the toolkit to be retrieved
73
- * @param options - Request options
74
- * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
76
+ * Retrieves a specific toolkit by its slug identifier.
77
+ *
78
+ * @param {string} slug - The unique slug identifier of the toolkit to retrieve
79
+ * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object with detailed information
80
+ * @throws {ComposioToolNotFoundError} If no toolkit with the given slug exists
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * // Get a specific toolkit
85
+ * const githubToolkit = await composio.toolkits.get('github');
86
+ * console.log(githubToolkit.name); // GitHub
87
+ * console.log(githubToolkit.authConfigDetails); // Authentication configuration details
88
+ * ```
89
+ */
90
+ async get(slug: string): Promise<ToolkitRetrieveResponse>;
91
+
92
+ /**
93
+ * Retrieves a list of toolkits based on the provided query parameters.
94
+ *
95
+ * @param {ToolkitListParams} query - The query parameters to filter toolkits
96
+ * @returns {Promise<ToolKitListResponse>} A paginated list of toolkits matching the query criteria
97
+ *
98
+ * @example
99
+ * ```typescript
100
+ * // Get all toolkits
101
+ * const allToolkits = await composio.toolkits.get({});
102
+ *
103
+ * // Get toolkits by category
104
+ * const devToolkits = await composio.toolkits.get({
105
+ * category: 'developer-tools'
106
+ * });
107
+ *
108
+ * // Get local toolkits
109
+ * const localToolkits = await composio.toolkits.get({
110
+ * isLocal: true
111
+ * });
112
+ * ```
113
+ */
114
+ async get(query: ToolkitListParams): Promise<ToolKitListResponse>;
115
+
116
+ /**
117
+ * Implementation method that handles both overloads for retrieving toolkits.
118
+ *
119
+ * @param {string | ToolkitListParams} arg - Either a toolkit slug or query parameters
120
+ * @returns {Promise<ToolkitRetrieveResponse | ToolKitListResponse>} The toolkit or list of toolkits
121
+ */
122
+ async get(
123
+ arg: string | ToolkitListParams
124
+ ): Promise<ToolkitRetrieveResponse | ToolKitListResponse> {
125
+ if (typeof arg === 'string') {
126
+ return this.getToolkitBySlug(arg);
127
+ }
128
+ return this.getToolkits(arg);
129
+ }
130
+
131
+ /**
132
+ * Retrieves a specific toolkit by its slug identifier.
133
+ *
134
+ * This method fetches a single toolkit from the Composio API and transforms
135
+ * the response to use camelCase property naming consistent with JavaScript/TypeScript conventions.
136
+ *
137
+ * @param {string} slug - The unique slug identifier of the toolkit to retrieve
138
+ * @returns {Promise<ToolkitRetrieveResponse>} The transformed toolkit object
139
+ * @throws {ValidationError} If the response cannot be properly parsed
140
+ * @throws {ComposioToolNotFoundError} If no toolkit with the given slug exists
141
+ *
142
+ * @private
143
*/
144
private async getToolkitBySlug(slug: string): Promise<ToolkitRetrieveResponse> {
145
try {
@@ -113,38 +181,19 @@ export class Toolkits {
181
}
182
183
/**
116
- * @overload
117
- * Fetches a toolkit by its Slug or a list of toolkits.
118
- * @param slug - The ID of the toolkit to be retrieved
119
- * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
120
- */
121
- async get(slug: string): Promise<ToolkitRetrieveResponse>;
122
- /**
123
- * @overload
124
- * Fetches a list of toolkits.
125
- * @param query - The parameters to fetch the toolkits
126
- * @returns {Promise<ToolKitListResponse>} The list of toolkits
127
- */
128
- async get(query: ToolkitListParams): Promise<ToolKitListResponse>;
129
- /**
130
- * Fetches a toolkit by its Slug or a list of toolkits.
131
- * This method retrieves the toolkit from the Composio API.
132
- * @param arg - The ID of the toolkit to be retrieved or a list of parameters
133
- * @returns {Promise<ToolkitRetrieveResponse | ToolKitListResponse>} The toolkit object or a list of toolkits
134
- */
135
- async get(
136
- arg: string | ToolkitListParams
137
- ): Promise<ToolkitRetrieveResponse | ToolKitListResponse> {
138
- if (typeof arg === 'string') {
139
- return this.getToolkitBySlug(arg);
140
- }
141
- return this.getToolkits(arg);
142
- }
143
-
144
- /**
145
- * Fetches all categories available in the Composio SDK
184
+ * Retrieves all toolkit categories available in the Composio SDK.
185
+ *
186
+ * This method fetches the complete list of categories from the Composio API
187
+ * and transforms the response to use camelCase property naming.
188
*
147
- * @returns {Promise<ToolkitRetrieveCategoriesResponse>} List of categories
189
+ * @returns {Promise<ToolkitRetrieveCategoriesResponse>} The list of toolkit categories
190
+ *
191
+ * @example
192
+ * ```typescript
193
+ * // Get all toolkit categories
194
+ * const categories = await composio.toolkits.listCategories();
195
+ * console.log(categories.items); // Array of category objects
196
+ * ```
197
*/
198
async listCategories(): Promise<ToolkitRetrieveCategoriesResponse> {
199
const result = await this.client.toolkits.retrieveCategories();
@@ -168,7 +217,7 @@ export class Toolkits {
217
* @param {string} userId - The user id of the user to authorize
218
* @param {string} toolkitSlug - The slug of the toolkit to authorize
219
* @returns {Promise<ConnectionRequest>} The connection request object
171
- *
220
+ *
221
* @example
222
* ```typescript
223
* const connectionRequest = await composio.toolkits.authorize(userId, 'github');
packages/core/src/models/Tools.ts
+154
-33
@@ -73,9 +73,15 @@ export class Tools<
73
}
74
75
/**
76
- * Transform the tool cases
77
- * @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool to transform
78
- * @returns {Tool} The transformed tool
76
+ * Transforms tool data from snake_case API format to camelCase for internal SDK use.
77
+ *
78
+ * This method standardizes the property naming convention for tools retrieved from the Composio API,
79
+ * making them more consistent with JavaScript/TypeScript conventions.
80
+ *
81
+ * @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool object to transform
82
+ * @returns {Tool} The transformed tool with camelCase properties
83
+ *
84
+ * @private
85
*/
86
private transformToolCases(
87
tool: ToolRetrieveResponse | ComposioToolListResponse['items'][0]
@@ -88,9 +94,15 @@ export class Tools<
94
}
95
96
/**
91
- * Transform the tool execute response to camelcase
92
- * @param {ComposioToolExecuteResponse} response - The response to transform
93
- * @returns {ToolExecuteResponse} The transformed response
97
+ * Transforms tool execution response from snake_case API format to camelCase.
98
+ *
99
+ * This method converts the response received from the Composio API to a standardized format
100
+ * with consistent property naming that follows JavaScript/TypeScript conventions.
101
+ *
102
+ * @param {ComposioToolExecuteResponse} response - The raw API response to transform
103
+ * @returns {ToolExecuteResponse} The transformed response with camelCase properties
104
+ *
105
+ * @private
106
*/
107
private transformToolExecuteResponse(response: ComposioToolExecuteResponse): ToolExecuteResponse {
108
return ToolExecuteResponseSchema.parse({
@@ -202,9 +214,35 @@ export class Tools<
214
}
215
216
/**
205
- * Lists all tools available in the Composio SDK as well as custom tools.
206
- * This method fetches the tools from the Composio API in the raw format.
207
- * @returns {ToolList} List of tools
217
+ * Lists all tools available in the Composio SDK including custom tools.
218
+ *
219
+ * This method fetches tools from the Composio API in raw format and combines them with
220
+ * any registered custom tools. The response can be filtered and modified as needed.
221
+ *
222
+ * @param {string} userId - The user ID for whom to fetch the tools
223
+ * @param {ToolListParams} [query={}] - Optional query parameters to filter the tools
224
+ * @param {TransformToolSchemaModifier} [modifier] - Optional function to transform tool schemas
225
+ * @returns {Promise<ToolList>} List of tools matching the query criteria
226
+ *
227
+ * @example
228
+ * ```typescript
229
+ * // Get all tools
230
+ * const tools = await composio.tools.getRawComposioTools('default');
231
+ *
232
+ * // Get tools with filters
233
+ * const githubTools = await composio.tools.getRawComposioTools('default', {
234
+ * toolkits: ['github'],
235
+ * important: true
236
+ * });
237
+ *
238
+ * // Get tools with schema transformation
239
+ * const tools = await composio.tools.getRawComposioTools('default', {},
240
+ * (toolSlug, toolkitSlug, tool) => {
241
+ * // Add custom properties to tool schema
242
+ * return {...tool, customProperty: 'value'};
243
+ * }
244
+ * );
245
+ * ```
246
*/
247
async getRawComposioTools(
248
userId: string,
@@ -300,16 +338,26 @@ export class Tools<
338
}
339
340
/**
303
- * Get a list of tools from composio based on filters
304
- * @param userId - The user id
305
- * @param filters - The filters for the tools
306
- * @param options - The options for the tools
307
- * @returns The tools
341
+ * Get a list of tools from Composio based on filters.
342
+ * This method fetches the tools from the Composio API and wraps them using the provider.
343
+ *
344
+ * @param {string} userId - The user id to get the tools for
345
+ * @param {ToolListParams} filters - The filters to apply when fetching tools
346
+ * @param {ProviderOptions<TProvider>} [options] - Optional provider options including modifiers
347
+ * @returns {Promise<ReturnType<T['wrapTools']>>} The wrapped tools collection
348
*
349
* @example
310
- * ```ts
350
+ * ```typescript
351
+ * // Get tools from the GitHub toolkit
352
* const tools = await composio.tools.get('default', {
353
* toolkits: ['github'],
354
+ * limit: 10
355
+ * });
356
+ *
357
+ * // Get tools with search
358
+ * const tools = await composio.tools.get('default', {
359
+ * search: 'user',
360
+ * important: true
361
* });
362
* ```
363
*/
@@ -320,15 +368,26 @@ export class Tools<
368
): Promise<ReturnType<T['wrapTools']>>;
369
370
/**
323
- * Get a tool by its slug
324
- * @param userId - The user id
325
- * @param slug - The slug of the tool
326
- * @param options - The options for the tool
327
- * @returns The tool
371
+ * Get a specific tool by its slug.
372
+ * This method fetches the tool from the Composio API and wraps it using the provider.
373
+ *
374
+ * @param {string} userId - The user id to get the tool for
375
+ * @param {string} slug - The slug of the tool to fetch
376
+ * @param {ProviderOptions<TProvider>} [options] - Optional provider options including modifiers
377
+ * @returns {Promise<ReturnType<T['wrapTools']>>} The wrapped tool
378
*
379
* @example
330
- * ```ts
331
- * const tool = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
380
+ * ```typescript
381
+ * // Get a specific tool by slug
382
+ * const hackerNewsUserTool = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
383
+ *
384
+ * // Get a tool with schema modifications
385
+ * const tool = await composio.tools.get('default', 'GITHUB_GET_REPOS', {
386
+ * modifyToolSchema: (toolSlug, toolkitSlug, schema) => {
387
+ * // Customize the tool schema
388
+ * return {...schema, description: 'Custom description'};
389
+ * }
390
+ * });
391
* ```
392
*/
393
async get<T extends TProvider>(
@@ -338,11 +397,13 @@ export class Tools<
397
): Promise<ReturnType<T['wrapTools']>>;
398
399
/**
341
- * Get a tool by its slug
342
- * @param userId - The user id
343
- * @param arg2 - The slug of the tool or the filters for the tools
344
- * @param options - The options for the tools
345
- * @returns The tool or the tools
400
+ * Get a tool or list of tools based on the provided arguments.
401
+ * This is an implementation method that handles both overloads.
402
+ *
403
+ * @param {string} userId - The user id to get the tool(s) for
404
+ * @param {ToolListParams | string} arg2 - Either a slug string or filters object
405
+ * @param {ProviderOptions<TProvider>} [options] - Optional provider options
406
+ * @returns {Promise<TToolCollection>} The tool collection
407
*/
408
async get(
409
userId: string,
@@ -480,13 +541,43 @@ export class Tools<
541
}
542
543
/**
483
- * Exectes a given tool with the provided parameters.
544
+ * Executes a given tool with the provided parameters.
545
*
485
- * This method calls the Composio API to execute the tool and returns the response.
546
+ * This method calls the Composio API or a custom tool handler to execute the tool and returns the response.
547
+ * It automatically determines whether to use a custom tool or a Composio API tool based on the slug.
548
*
487
- * @param {string} slug - The ID of the tool to be executed
549
+ * @param {string} slug - The slug/ID of the tool to be executed
550
* @param {ToolExecuteParams} body - The parameters to be passed to the tool
551
+ * @param {ExecuteToolModifiers} [modifiers] - Optional modifiers to transform the request or response
552
* @returns {Promise<ToolExecuteResponse>} - The response from the tool execution
553
+ *
554
+ * @throws {ComposioCustomToolsNotInitializedError} If the CustomTools instance is not initialized
555
+ * @throws {ComposioToolNotFoundError} If the tool with the given slug is not found
556
+ * @throws {ComposioToolExecutionError} If there is an error during tool execution
557
+ *
558
+ * @example
559
+ * ```typescript
560
+ * // Execute a Composio API tool
561
+ * const result = await composio.tools.execute('HACKERNEWS_GET_USER', {
562
+ * userId: 'default',
563
+ * arguments: { userId: 'pg' }
564
+ * });
565
+ *
566
+ * // Execute with modifiers
567
+ * const result = await composio.tools.execute('GITHUB_GET_ISSUES', {
568
+ * userId: 'default',
569
+ * arguments: { owner: 'composio', repo: 'sdk' }
570
+ * }, {
571
+ * beforeToolExecute: (toolSlug, toolkitSlug, params) => {
572
+ * // Modify params before execution
573
+ * return params;
574
+ * },
575
+ * afterToolExecute: (toolSlug, toolkitSlug, result) => {
576
+ * // Transform result after execution
577
+ * return result;
578
+ * }
579
+ * });
580
+ * ```
581
*/
582
async execute(
583
slug: string,
@@ -554,9 +645,39 @@ export class Tools<
645
}
646
647
/**
557
- * Execute a custom tool
558
- * @param body
559
- * @returns
648
+ * Creates a custom tool that can be used within the Composio SDK.
649
+ *
650
+ * Custom tools allow you to extend the functionality of Composio with your own implementations
651
+ * while keeping a consistent interface for both built-in and custom tools.
652
+ *
653
+ * @param {CustomToolOptions} body - The configuration for the custom tool
654
+ * @returns {Promise<Tool>} The created custom tool
655
+ *
656
+ * @example
657
+ * ```typescript
658
+ * const customTool = await composio.tools.createCustomTool({
659
+ * name: 'My Custom Tool',
660
+ * description: 'A custom tool that does something specific',
661
+ * slug: 'MY_CUSTOM_TOOL',
662
+ * inputParameters: {
663
+ * param1: {
664
+ * type: 'string',
665
+ * description: 'First parameter',
666
+ * required: true
667
+ * }
668
+ * },
669
+ * outputParameters: {
670
+ * result: {
671
+ * type: 'string',
672
+ * description: 'The result of the operation'
673
+ * }
674
+ * },
675
+ * handler: async (params, context) => {
676
+ * // Custom logic here
677
+ * return { data: { result: 'Success!' } };
678
+ * }
679
+ * });
680
+ * ```
681
*/
682
async createCustomTool(body: CustomToolOptions): Promise<Tool> {
683
return this.customTools.createTool(body);
packages/core/src/types/connectedAccounts.types.ts
+57
-1
@@ -109,7 +109,7 @@ export const ConnectedAccountRetrieveResponseSchema = z.object({
109
authConfig: ConnectedAccountAuthConfigSchema,
110
userId: z.string(),
111
data: z.record(z.string(), z.unknown()),
112
- params: z.record(z.string(), z.unknown()),
112
+ params: z.record(z.string(), z.unknown()).optional(),
113
status: ConnectedAccountStatusSchema,
114
statusReason: z.string().nullable(),
115
toolkit: z.object({
@@ -120,6 +120,62 @@ export const ConnectedAccountRetrieveResponseSchema = z.object({
120
createdAt: z.string(),
121
updatedAt: z.string(),
122
});
123
+// for some reason the list item doesn't have params
124
+export const ConnectedAccountListResponseItemSchema = ConnectedAccountAuthConfigSchema;
125
export type ConnectedAccountRetrieveResponse = z.infer<
126
typeof ConnectedAccountRetrieveResponseSchema
127
>;
128
+
129
+/**
130
+ * Type for list response item that doesn't include params
131
+ */
132
+export type ConnectedAccountListResponseItem = Omit<ConnectedAccountRetrieveResponse, 'params'>;
133
+
134
+export const ConnectedAccountListParamsSchema = z.object({
135
+ authConfigIds: z
136
+ .array(z.string())
137
+ .nullable()
138
+ .optional()
139
+ .describe('The auth config ids of the connected accounts'),
140
+ cursor: z
141
+ .number()
142
+ .nullable()
143
+ .optional()
144
+ .describe('The cursor to paginate through the connected accounts'),
145
+ labels: z
146
+ .array(z.string())
147
+ .nullable()
148
+ .optional()
149
+ .describe('The labels of the connected accounts'),
150
+ limit: z.number().nullable().optional().describe('The limit of the connected accounts to return'),
151
+ orderBy: z
152
+ .enum(['created_at', 'updated_at'])
153
+ .optional()
154
+ .describe('The order by of the connected accounts'),
155
+ statuses: z
156
+ .array(ConnectedAccountStatusSchema)
157
+ .nullable()
158
+ .optional()
159
+ .describe('The statuses of the connected accounts'),
160
+ toolkitSlugs: z
161
+ .array(z.string())
162
+ .nullable()
163
+ .optional()
164
+ .describe('The toolkit slugs of the connected accounts'),
165
+ userIds: z
166
+ .array(z.string())
167
+ .nullable()
168
+ .optional()
169
+ .describe('The user ids of the connected accounts'),
170
+});
171
+export type ConnectedAccountListParams = z.infer<typeof ConnectedAccountListParamsSchema>;
172
+
173
+export const ConnectedAccountListResponseSchema = z.object({
174
+ items: z.array(ConnectedAccountRetrieveResponseSchema).describe('The list of connected accounts'),
175
+ nextCursor: z
176
+ .string()
177
+ .nullable()
178
+ .describe('The next cursor to paginate through the connected accounts'),
179
+ totalPages: z.number().describe('The total number of pages of connected accounts'),
180
+});
181
+export type ConnectedAccountListResponse = z.infer<typeof ConnectedAccountListResponseSchema>;
packages/core/src/types/modifiers.types.ts
+261
-13
@@ -2,8 +2,51 @@ import { BaseAgenticProvider, BaseComposioProvider } from '../provider/BaseProvi
2
import { ToolExecuteParams, ToolExecuteResponse, Tool } from './tool.types';
3
4
/**
5
- * Modifier for altering the tool execute params
6
- * Called before the tool execute call
5
+ * Modifier for altering the tool execute parameters before execution.
6
+ *
7
+ * This function allows you to intercept and modify the parameters being passed to a tool
8
+ * before the actual execution happens. Common use cases include:
9
+ * - Adding or modifying authentication parameters
10
+ * - Transforming input data to match expected formats
11
+ * - Adding contextual information to the request
12
+ * - Implementing request validation or normalization
13
+ *
14
+ * @param {string} toolSlug - The slug identifier of the tool being executed
15
+ * @param {string} toolkitSlug - The slug identifier of the toolkit containing the tool
16
+ * @param {ToolExecuteParams} toolExecuteParams - The original execution parameters
17
+ * @returns {ToolExecuteParams} The modified execution parameters
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * // Add authentication headers to all tool requests
22
+ * const beforeToolExecute = (toolSlug, toolkitSlug, params) => {
23
+ * return {
24
+ * ...params,
25
+ * customAuthParams: {
26
+ * ...params.customAuthParams,
27
+ * headers: {
28
+ * ...params.customAuthParams?.headers,
29
+ * 'X-API-Key': 'my-api-key'
30
+ * }
31
+ * }
32
+ * };
33
+ * };
34
+ *
35
+ * // Transform input parameters for a specific tool
36
+ * const beforeToolExecute = (toolSlug, toolkitSlug, params) => {
37
+ * if (toolSlug === 'GITHUB_SEARCH_REPOS') {
38
+ * // Convert simple query to structured query format
39
+ * return {
40
+ * ...params,
41
+ * arguments: {
42
+ * ...params.arguments,
43
+ * q: `${params.arguments.query} in:name,description`
44
+ * }
45
+ * };
46
+ * }
47
+ * return params;
48
+ * };
49
+ * ```
50
*/
51
export type BeforeToolExecuteModifier = (
52
toolSlug: string,
@@ -12,8 +55,54 @@ export type BeforeToolExecuteModifier = (
55
) => ToolExecuteParams;
56
57
/**
15
- * Modifier for altering the tool execute response
16
- * Called after the tool execute call
58
+ * Modifier for altering the tool execution response after execution completes.
59
+ *
60
+ * This function allows you to intercept and modify the response returned from a tool
61
+ * after its execution has completed. Common use cases include:
62
+ * - Transforming response data into a more convenient format
63
+ * - Handling or enhancing error responses
64
+ * - Adding additional context or derived data to successful responses
65
+ * - Implementing cross-cutting concerns like logging or analytics
66
+ *
67
+ * @param {string} toolSlug - The slug identifier of the tool that was executed
68
+ * @param {string} toolkitSlug - The slug identifier of the toolkit containing the tool
69
+ * @param {ToolExecuteResponse} toolExecuteResponse - The original execution response
70
+ * @returns {ToolExecuteResponse} The modified execution response
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * // Transform the response data format
75
+ * const afterToolExecute = (toolSlug, toolkitSlug, response) => {
76
+ * if (toolSlug === 'GITHUB_LIST_REPOS' && response.successful) {
77
+ * // Transform the returned repos into a simpler format
78
+ * return {
79
+ * ...response,
80
+ * data: {
81
+ * repositories: response.data.items.map(repo => ({
82
+ * name: repo.name,
83
+ * url: repo.html_url,
84
+ * stars: repo.stargazers_count
85
+ * }))
86
+ * }
87
+ * };
88
+ * }
89
+ * return response;
90
+ * };
91
+ *
92
+ * // Add error handling with custom messages
93
+ * const afterToolExecute = (toolSlug, toolkitSlug, response) => {
94
+ * if (!response.successful) {
95
+ * return {
96
+ * ...response,
97
+ * error: {
98
+ * message: `Error using ${toolSlug}: ${response.error?.message || 'Unknown error'}`,
99
+ * code: response.error?.code || 'UNKNOWN_ERROR'
100
+ * }
101
+ * };
102
+ * }
103
+ * return response;
104
+ * };
105
+ * ```
106
*/
107
export type AfterToolExecuteModifier = (
108
toolSlug: string,
@@ -22,8 +111,63 @@ export type AfterToolExecuteModifier = (
111
) => ToolExecuteResponse;
112
113
/**
25
- * Modifier for altering the tool schema
26
- * Called after the tool schema is retrieved
114
+ * Modifier for altering the tool schema before it's exposed to consumers.
115
+ *
116
+ * This function allows you to customize the metadata, parameters, and behavior definitions
117
+ * of tools before they are used. Common use cases include:
118
+ * - Customizing input parameter definitions or descriptions
119
+ * - Adding, removing, or modifying parameters to match your application's needs
120
+ * - Changing the name or description of tools to better fit your context
121
+ * - Implementing versioning or feature flagging for tool schemas
122
+ *
123
+ * @param {string} toolSlug - The slug identifier of the tool being modified
124
+ * @param {string} toolkitSlug - The slug identifier of the toolkit containing the tool
125
+ * @param {Tool} toolSchema - The original tool schema
126
+ * @returns {Tool} The modified tool schema
127
+ *
128
+ * @example
129
+ * ```typescript
130
+ * // Modify the input parameters for a specific tool
131
+ * const modifyToolSchema = (toolSlug, toolkitSlug, toolSchema) => {
132
+ * if (toolSlug === 'HACKERNEWS_GET_USER') {
133
+ * return {
134
+ * ...toolSchema,
135
+ * inputParameters: {
136
+ * ...toolSchema.inputParameters,
137
+ * userId: {
138
+ * type: 'string',
139
+ * description: 'The HackerNews username to retrieve information for',
140
+ * required: true
141
+ * }
142
+ * }
143
+ * };
144
+ * }
145
+ * return toolSchema;
146
+ * };
147
+ *
148
+ * // Add custom descriptions to all tools in a toolkit
149
+ * const modifyToolSchema = (toolSlug, toolkitSlug, toolSchema) => {
150
+ * if (toolkitSlug === 'github') {
151
+ * return {
152
+ * ...toolSchema,
153
+ * description: `Company GitHub tool: ${toolSchema.description}`,
154
+ * important: true
155
+ * };
156
+ * }
157
+ * return toolSchema;
158
+ * };
159
+ *
160
+ * // Simplify tool schemas for a specific consumer
161
+ * const modifyToolSchema = (toolSlug, toolkitSlug, toolSchema) => {
162
+ * // Remove advanced or complex parameters
163
+ * const { complexParam1, complexParam2, ...simpleInputParams } = toolSchema.inputParameters;
164
+ *
165
+ * return {
166
+ * ...toolSchema,
167
+ * inputParameters: simpleInputParams
168
+ * };
169
+ * };
170
+ * ```
171
*/
172
export type TransformToolSchemaModifier = (
173
toolSlug: string,
@@ -32,34 +176,138 @@ export type TransformToolSchemaModifier = (
176
) => Tool;
177
178
/**
35
- * Non Agentic tool options. These are used by Non-Agentic toolsets
179
+ * Options for non-agentic tool configuration.
180
+ *
181
+ * These options are used when working with non-agentic tool providers to
182
+ * customize the behavior of tools through schema transformation.
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * // Configure tools with schema modification
187
+ * const tools = await composio.tools.get('default', {
188
+ * toolkits: ['github']
189
+ * }, {
190
+ * modifyToolSchema: (toolSlug, toolkitSlug, schema) => {
191
+ * // Custom schema modifications
192
+ * return schema;
193
+ * }
194
+ * });
195
+ * ```
196
*/
197
export type ToolOptions = {
198
/**
39
- * Transform tool schema modifier
199
+ * Function to transform tool schemas before they're exposed to consumers.
200
+ * This allows customizing input/output parameters, descriptions, and other metadata.
201
*/
202
modifyToolSchema?: TransformToolSchemaModifier;
203
};
204
205
/**
45
- * Modifiers for the tool execution
46
- * This is used by execute call and handleToolCall of Non-Agentic toolsets
206
+ * Options for configuring tool execution behavior.
207
+ *
208
+ * These modifiers allow you to intercept and modify tool execution at both
209
+ * the request and response stages, enabling custom behavior, data transformation,
210
+ * error handling, and more.
211
+ *
212
+ * @example
213
+ * ```typescript
214
+ * // Execute a tool with request and response modifications
215
+ * const result = await composio.tools.execute('GITHUB_GET_REPOS', {
216
+ * userId: 'default',
217
+ * arguments: { owner: 'composio' }
218
+ * }, {
219
+ * beforeToolExecute: (toolSlug, toolkitSlug, params) => {
220
+ * console.log(`Executing ${toolSlug} from ${toolkitSlug}`);
221
+ * return params;
222
+ * },
223
+ * afterToolExecute: (toolSlug, toolkitSlug, response) => {
224
+ * if (response.successful) {
225
+ * console.log(`Successfully executed ${toolSlug}`);
226
+ * }
227
+ * return response;
228
+ * }
229
+ * });
230
+ * ```
231
*/
232
export type ExecuteToolModifiers = {
233
/**
50
- * Before tool execute modifier
234
+ * Function to intercept and modify tool execution parameters before the tool is executed.
235
+ * This allows customizing the request based on tool-specific needs.
236
*/
237
beforeToolExecute?: BeforeToolExecuteModifier;
238
+
239
/**
54
- * After tool execute modifier
240
+ * Function to intercept and modify tool execution responses after the tool has executed.
241
+ * This allows transforming the response or implementing custom error handling.
242
*/
243
afterToolExecute?: AfterToolExecuteModifier;
244
};
245
246
/**
60
- * Agentic tool options. These are used by Agentic toolsets
247
+ * Options for agentic tool configuration.
248
+ *
249
+ * These options combine schema modification capabilities with execution behavior
250
+ * customization, providing full control over both the definition and execution
251
+ * of tools in agentic contexts (like LLM providers).
252
+ *
253
+ * @example
254
+ * ```typescript
255
+ * // Configure agentic tools with schema and execution modifications
256
+ * const agenticTools = await vercel.tools.get('default', 'GITHUB_GET_REPOS', {
257
+ * modifyToolSchema: (toolSlug, toolkitSlug, schema) => {
258
+ * return {
259
+ * ...schema,
260
+ * description: `Enhanced ${toolSlug} for better context`
261
+ * };
262
+ * },
263
+ *
264
+ * // Intercept before execution
265
+ * beforeToolExecute: (toolSlug, toolkitSlug, params) => {
266
+ * // Add analytics tracking
267
+ * trackToolUsage(toolSlug);
268
+ * return params;
269
+ * },
270
+ *
271
+ * // Transform after execution
272
+ * afterToolExecute: (toolSlug, toolkitSlug, response) => {
273
+ * // Log results and handle errors
274
+ * if (!response.successful) {
275
+ * logToolError(toolSlug, response.error);
276
+ * }
277
+ * return response;
278
+ * }
279
+ * });
280
+ * ```
281
*/
282
export type AgenticToolOptions = ToolOptions & ExecuteToolModifiers;
283
284
+/**
285
+ * Provider-specific options determined by the type of provider being used.
286
+ *
287
+ * This type automatically resolves to either AgenticToolOptions or ToolOptions
288
+ * based on whether the provider is agentic (like OpenAI or Vercel) or non-agentic.
289
+ *
290
+ * @template T - The provider type
291
+ *
292
+ * @example
293
+ * ```typescript
294
+ * // With standard provider (non-agentic)
295
+ * const tools = await composio.tools.get('default', 'GITHUB_GET_REPOS', {
296
+ * modifyToolSchema: (toolSlug, toolkitSlug, schema) => schema
297
+ * });
298
+ *
299
+ * // With agentic provider (e.g., VercelProvider)
300
+ * const vercel = new Composio({
301
+ * apiKey: process.env.COMPOSIO_API_KEY,
302
+ * provider: new VercelProvider()
303
+ * });
304
+ *
305
+ * const agenticTools = await vercel.tools.get('default', 'GITHUB_GET_REPOS', {
306
+ * modifyToolSchema: (toolSlug, toolkitSlug, schema) => schema,
307
+ * beforeToolExecute: (toolSlug, toolkitSlug, params) => params,
308
+ * afterToolExecute: (toolSlug, toolkitSlug, response) => response
309
+ * });
310
+ * ```
311
+ */
312
export type ProviderOptions<T extends BaseComposioProvider<unknown, unknown>> =
313
T extends BaseAgenticProvider<unknown, unknown> ? AgenticToolOptions : ToolOptions;
packages/core/test/connectedAccounts/connectedAccounts.test.ts
+12
-4
@@ -42,25 +42,33 @@ describe('ConnectedAccounts', () => {
42
describe('list', () => {
43
it('should call client.connectedAccounts.list with the provided query', async () => {
44
const query = { limit: 10 };
45
- const mockResponse = { items: [], totalPages: 0 };
45
+ const mockResponse = { items: [], next_cursor: null, total_pages: 0 };
46
47
extendedMockClient.connectedAccounts.list.mockResolvedValueOnce(mockResponse);
48
49
const result = await connectedAccounts.list(query);
50
51
expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(query);
52
- expect(result).toEqual(mockResponse);
52
+ expect(result).toEqual({
53
+ items: [],
54
+ nextCursor: null,
55
+ totalPages: 0,
56
+ });
57
});
58
59
it('should call client.connectedAccounts.list without query if none provided', async () => {
56
- const mockResponse = { items: [], totalPages: 0 };
60
+ const mockResponse = { items: [], total_pages: 0, next_cursor: null };
61
62
extendedMockClient.connectedAccounts.list.mockResolvedValueOnce(mockResponse);
63
64
const result = await connectedAccounts.list();
65
66
expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(undefined);
63
- expect(result).toEqual(mockResponse);
67
+ expect(result).toEqual({
68
+ items: [],
69
+ nextCursor: null,
70
+ totalPages: 0,
71
+ });
72
});
73
});
74