Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Fix toolkit tests
haxzie committed
Jun 11, 2025 at 13:52 UTC
c7ff44c5b0fbe965193fc616b1b7a732498017f8
4 files changed
+481
-18
package.json
+3
-2
@@ -11,6 +11,7 @@
11
],
12
"scripts": {
13
"build": "turbo build",
14
+ "build:packages": "turbo build --filter=./packages/**",
15
"test": "turbo test --filter=./packages/**",
16
"test:ui": "vitest --ui",
17
"lint": "eslint . --ext .ts,.tsx",
@@ -23,10 +24,10 @@
24
"create:example": "bash scripts/create-example.sh",
25
"check:peer-deps": "tsx scripts/check-peer-deps.ts",
26
"update:peer-deps": "tsx scripts/update-peer-deps.ts",
26
- "prepublish": "pnpm run build",
27
+ "prepublish": "pnpm run build:packages",
28
"changeset": "changeset",
29
"changeset:version": "changeset version",
29
- "changeset:release": "pnpm run build && changeset publish",
30
+ "changeset:release": "pnpm run build:packages && changeset publish",
31
"changeset:pre-enter": "changeset pre enter alpha",
32
"changeset:pre-exit": "changeset pre exit alpha"
33
},
packages/core/src/models/Toolkits.ts
+28
-11
@@ -58,22 +58,34 @@ export class Toolkits {
58
sort_by: parsedQuery.data.sortBy,
59
});
60
61
- const parsedResult = ToolKitListResponseSchema.safeParse({
62
- items: result.items.map(item => {
63
- const parsedItem = ToolKitItemSchema.parse({
61
+ const parsedResult = ToolKitListResponseSchema.safeParse(
62
+ result.items.map(item => {
63
+ const parsedItem = ToolKitItemSchema.safeParse({
64
name: item.name,
65
slug: item.slug,
66
- meta: item.meta,
66
+ meta: {
67
+ ...item.meta,
68
+ createdAt: item.meta.created_at,
69
+ updatedAt: item.meta.updated_at,
70
+ toolsCount: item.meta.tools_count,
71
+ triggersCount: item.meta.triggers_count,
72
+ categories: item.meta.categories,
73
+ appUrl: item.meta.app_url,
74
+ logo: item.meta.logo,
75
+ },
76
isLocalToolkit: item.is_local_toolkit,
77
authSchemes: item.auth_schemes,
78
composioManagedAuthSchemes: item.composio_managed_auth_schemes,
79
noAuth: item.no_auth,
80
});
72
- return parsedItem;
73
- }),
74
- nextCursor: result.next_cursor,
75
- totalPages: result.total_pages,
76
- });
81
+ if (!parsedItem.success) {
82
+ throw new ValidationError('Failed to parse toolkit response', {
83
+ cause: parsedItem.error,
84
+ });
85
+ }
86
+ return parsedItem.data;
87
+ })
88
+ );
89
90
if (!parsedResult.success) {
91
throw new ValidationError('Failed to parse toolkit list response', {
@@ -226,7 +238,7 @@ export class Toolkits {
238
*/
239
async listCategories(): Promise<ToolkitRetrieveCategoriesResponse> {
240
const result = await this.client.toolkits.retrieveCategories();
229
- const parsedResult = ToolkitRetrieveCategoriesResponseSchema.parse({
241
+ const parsedResult = ToolkitRetrieveCategoriesResponseSchema.safeParse({
242
items: result.items.map(item => {
243
const parsedItem = ToolkitCategorySchema.parse({
244
id: item.id,
@@ -237,7 +249,12 @@ export class Toolkits {
249
nextCursor: result.next_cursor,
250
totalPages: result.total_pages,
251
});
240
- return parsedResult;
252
+ if (!parsedResult.success) {
253
+ throw new ValidationError('Failed to parse toolkit categories response', {
254
+ cause: parsedResult.error,
255
+ });
256
+ }
257
+ return parsedResult.data;
258
}
259
260
/**
packages/core/src/types/toolkit.types.ts
+1
-5
@@ -47,11 +47,7 @@ export const ToolKitItemSchema = z.object({
47
noAuth: z.boolean().optional(),
48
});
49
50
-export const ToolKitListResponseSchema = z.object({
51
- items: z.array(ToolKitItemSchema),
52
- nextCursor: z.string().nullable(),
53
- totalPages: z.number(),
54
-});
50
+export const ToolKitListResponseSchema = z.array(ToolKitItemSchema);
51
52
export type ToolKitMeta = z.infer<typeof ToolKitMetaSchema>;
53
export type ToolKitItem = z.infer<typeof ToolKitItemSchema>;
packages/core/test/models/toolkits.test.ts
new
+449
@@ -0,0 +1,449 @@
1
+import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+import { Toolkits } from '../../src/models/toolkits';
3
+import ComposioClient from '@composio/client';
4
+import { ValidationError } from '../../src/errors/ValidationErrors';
5
+import { ComposioToolkitFetchError, ComposioToolkitNotFoundError } from '../../src/errors';
6
+import { telemetry } from '../../src/telemetry/Telemetry';
7
+import { ConnectionRequest } from '../../src/models/ConnectionRequest';
8
+import { ComposioAuthConfigNotFoundError } from '../../src/errors/AuthConfigErrors';
9
+
10
+// Mock dependencies
11
+vi.mock('../../src/telemetry/Telemetry', () => ({
12
+ telemetry: {
13
+ instrument: vi.fn(),
14
+ },
15
+}));
16
+
17
+// Create mock client with toolkit-related methods
18
+const createMockClient = () => ({
19
+ baseURL: 'https://api.composio.dev',
20
+ apiKey: 'test-api-key',
21
+ toolkits: {
22
+ list: vi.fn(),
23
+ retrieve: vi.fn(),
24
+ retrieveCategories: vi.fn(),
25
+ listCategories: vi.fn(),
26
+ authorize: vi.fn(),
27
+ },
28
+ authConfigs: {
29
+ list: vi.fn(),
30
+ create: vi.fn(),
31
+ },
32
+ connectedAccounts: {
33
+ initiate: vi.fn(),
34
+ create: vi.fn(),
35
+ },
36
+});
37
+
38
+// Mock response data
39
+const mockToolkitListResponse = {
40
+ items: [
41
+ {
42
+ name: 'GitHub',
43
+ slug: 'github',
44
+ meta: {
45
+ created_at: '2024-01-01',
46
+ updated_at: '2024-01-02',
47
+ tools_count: 10,
48
+ triggers_count: 5,
49
+ },
50
+ is_local_toolkit: false,
51
+ auth_schemes: ['oauth2'],
52
+ composio_managed_auth_schemes: ['oauth2'],
53
+ no_auth: false,
54
+ },
55
+ ],
56
+};
57
+
58
+const mockToolkitRetrieveResponse = {
59
+ name: 'GitHub',
60
+ slug: 'github',
61
+ meta: {
62
+ created_at: '2024-01-01',
63
+ updated_at: '2024-01-02',
64
+ tools_count: 10,
65
+ triggers_count: 5,
66
+ },
67
+ is_local_toolkit: false,
68
+ composio_managed_auth_schemes: ['oauth2'],
69
+ auth_config_details: [
70
+ {
71
+ name: 'oauth2',
72
+ mode: 'oauth2',
73
+ fields: {
74
+ auth_config_creation: {
75
+ optional: [],
76
+ required: [],
77
+ },
78
+ connected_account_initiation: {
79
+ optional: [],
80
+ required: [],
81
+ },
82
+ },
83
+ proxy: {
84
+ base_url: 'https://api.github.com',
85
+ },
86
+ },
87
+ ],
88
+};
89
+
90
+describe('Toolkits', () => {
91
+ let toolkits: Toolkits;
92
+ let mockClient: ReturnType<typeof createMockClient>;
93
+
94
+ beforeEach(() => {
95
+ vi.clearAllMocks();
96
+ mockClient = createMockClient();
97
+ toolkits = new Toolkits(mockClient as unknown as ComposioClient);
98
+ });
99
+
100
+ describe('constructor', () => {
101
+ it('should create an instance successfully', () => {
102
+ expect(toolkits).toBeInstanceOf(Toolkits);
103
+ expect(telemetry.instrument).toHaveBeenCalledWith(toolkits);
104
+ });
105
+
106
+ it('should store the client reference', () => {
107
+ expect(toolkits['client']).toBe(mockClient);
108
+ });
109
+ });
110
+
111
+ describe('get', () => {
112
+ it('should get a list of toolkits', async () => {
113
+ mockClient.toolkits.list.mockResolvedValue(mockToolkitListResponse);
114
+
115
+ const result = await toolkits.get({});
116
+
117
+ expect(result).toEqual([
118
+ {
119
+ name: 'GitHub',
120
+ slug: 'github',
121
+ meta: {
122
+ createdAt: '2024-01-01',
123
+ updatedAt: '2024-01-02',
124
+ toolsCount: 10,
125
+ triggersCount: 5,
126
+ },
127
+ isLocalToolkit: false,
128
+ authSchemes: ['oauth2'],
129
+ composioManagedAuthSchemes: ['oauth2'],
130
+ noAuth: false,
131
+ },
132
+ ]);
133
+ expect(mockClient.toolkits.list).toHaveBeenCalledWith({});
134
+ });
135
+
136
+ it('should get a single toolkit by slug', async () => {
137
+ mockClient.toolkits.retrieve.mockResolvedValue(mockToolkitRetrieveResponse);
138
+
139
+ const result = await toolkits.get('github');
140
+
141
+ expect(result).toEqual({
142
+ name: 'GitHub',
143
+ slug: 'github',
144
+ meta: {
145
+ createdAt: '2024-01-01',
146
+ updatedAt: '2024-01-02',
147
+ toolsCount: 10,
148
+ triggersCount: 5,
149
+ },
150
+ isLocalToolkit: false,
151
+ composioManagedAuthSchemes: ['oauth2'],
152
+ authConfigDetails: [
153
+ {
154
+ name: 'oauth2',
155
+ mode: 'oauth2',
156
+ fields: {
157
+ authConfigCreation: {
158
+ optional: [],
159
+ required: [],
160
+ },
161
+ connectedAccountInitiation: {
162
+ optional: [],
163
+ required: [],
164
+ },
165
+ },
166
+ proxy: {
167
+ baseUrl: 'https://api.github.com',
168
+ },
169
+ },
170
+ ],
171
+ });
172
+ expect(mockClient.toolkits.retrieve).toHaveBeenCalledWith('github');
173
+ });
174
+
175
+ it('should throw ValidationError for invalid list query', async () => {
176
+ const promise = toolkits.get({ category: 123 } as any);
177
+ await expect(promise).rejects.toThrowError('Failed to fetch toolkits');
178
+ });
179
+
180
+ it('should throw ComposioToolkitNotFoundError when toolkit not found', async () => {
181
+ mockClient.toolkits.retrieve.mockRejectedValue(
182
+ new Error('Toolkit with slug non-existent not found')
183
+ );
184
+
185
+ const promise = toolkits.get('non-existent');
186
+ await expect(promise).rejects.toThrowError("Couldn't fetch Toolkit with slug: non-existent");
187
+ });
188
+
189
+ it('should throw ComposioToolkitFetchError for other errors', async () => {
190
+ mockClient.toolkits.list.mockRejectedValue(new Error('Network error'));
191
+
192
+ const promise = toolkits.get({});
193
+ await expect(promise).rejects.toThrowError('Failed to fetch toolkits');
194
+ });
195
+ });
196
+
197
+ describe('listCategories', () => {
198
+ it('should list toolkit categories', async () => {
199
+ const mockResponse = {
200
+ items: [
201
+ {
202
+ id: 'cat-1',
203
+ name: 'Category 1',
204
+ },
205
+ ],
206
+ next_cursor: null,
207
+ total_pages: 1,
208
+ };
209
+
210
+ mockClient.toolkits.retrieveCategories.mockResolvedValue(mockResponse);
211
+
212
+ const result = await toolkits.listCategories();
213
+
214
+ expect(result).toEqual({
215
+ items: mockResponse.items,
216
+ nextCursor: mockResponse.next_cursor,
217
+ totalPages: mockResponse.total_pages,
218
+ });
219
+ });
220
+ });
221
+
222
+ describe('authorize', () => {
223
+ it('should create auth config and initiate connection request when no auth config exists', async () => {
224
+ // Mock toolkit retrieval
225
+ mockClient.toolkits.retrieve.mockResolvedValue({
226
+ name: 'Test Toolkit',
227
+ slug: 'test-toolkit',
228
+ meta: {
229
+ created_at: new Date().toISOString(),
230
+ updated_at: new Date().toISOString(),
231
+ tools_count: 1,
232
+ triggers_count: 0,
233
+ },
234
+ is_local_toolkit: false,
235
+ auth_config_details: [
236
+ {
237
+ name: 'OAuth2',
238
+ mode: 'OAUTH2',
239
+ fields: {
240
+ auth_config_creation: {
241
+ optional: [],
242
+ required: [],
243
+ },
244
+ connected_account_initiation: {
245
+ optional: [],
246
+ required: [],
247
+ },
248
+ },
249
+ },
250
+ ],
251
+ });
252
+
253
+ // Mock empty auth config list
254
+ mockClient.authConfigs.list.mockResolvedValue({
255
+ items: [],
256
+ next_cursor: null,
257
+ total_pages: 1,
258
+ });
259
+
260
+ // Mock auth config creation
261
+ mockClient.authConfigs.create.mockResolvedValue({
262
+ auth_config: {
263
+ id: 'new-auth-config-id',
264
+ auth_scheme: 'OAUTH2',
265
+ is_composio_managed: true,
266
+ toolkit: {
267
+ slug: 'test-toolkit',
268
+ logo: 'https://example.com/logo.png',
269
+ },
270
+ },
271
+ toolkit: {
272
+ slug: 'test-toolkit',
273
+ },
274
+ });
275
+
276
+ // Mock connection request initiation
277
+ mockClient.connectedAccounts.create.mockResolvedValue({
278
+ id: 'connection-request-id',
279
+ connectionData: {
280
+ val: {
281
+ status: 'INITIATED',
282
+ redirectUrl: 'https://auth.url',
283
+ },
284
+ },
285
+ });
286
+
287
+ const result = await toolkits.authorize('user-123', 'test-toolkit');
288
+
289
+ expect(mockClient.authConfigs.create).toHaveBeenCalledWith({
290
+ toolkit: {
291
+ slug: 'test-toolkit',
292
+ },
293
+ auth_config: {
294
+ type: 'use_composio_managed_auth',
295
+ name: 'Test Toolkit Auth Config',
296
+ },
297
+ });
298
+
299
+ expect(mockClient.connectedAccounts.create).toHaveBeenCalledWith({
300
+ auth_config: {
301
+ id: 'new-auth-config-id',
302
+ },
303
+ connection: {
304
+ user_id: 'user-123',
305
+ },
306
+ });
307
+
308
+ expect(result.toJSON()).toEqual({
309
+ id: 'connection-request-id',
310
+ status: 'INITIATED',
311
+ redirectUrl: 'https://auth.url',
312
+ });
313
+ });
314
+
315
+ it('should use existing auth config to initiate connection request', async () => {
316
+ // Mock toolkit retrieval
317
+ mockClient.toolkits.retrieve.mockResolvedValue({
318
+ name: 'Test Toolkit',
319
+ slug: 'test-toolkit',
320
+ meta: {
321
+ created_at: new Date().toISOString(),
322
+ updated_at: new Date().toISOString(),
323
+ tools_count: 1,
324
+ triggers_count: 0,
325
+ },
326
+ is_local_toolkit: false,
327
+ auth_config_details: [
328
+ {
329
+ name: 'OAuth2',
330
+ mode: 'OAUTH2',
331
+ fields: {
332
+ auth_config_creation: {
333
+ optional: [],
334
+ required: [],
335
+ },
336
+ connected_account_initiation: {
337
+ optional: [],
338
+ required: [],
339
+ },
340
+ },
341
+ },
342
+ ],
343
+ });
344
+
345
+ // Mock existing auth config
346
+ mockClient.authConfigs.list.mockResolvedValue({
347
+ items: [
348
+ {
349
+ id: 'existing-auth-config-id',
350
+ auth_scheme: 'OAUTH2',
351
+ is_composio_managed: true,
352
+ name: 'Existing Auth Config',
353
+ no_of_connections: 0,
354
+ status: 'ENABLED',
355
+ toolkit: {
356
+ logo: 'https://example.com/logo.png',
357
+ slug: 'test-toolkit',
358
+ },
359
+ uuid: 'uuid-1',
360
+ credentials: {},
361
+ expected_input_fields: [],
362
+ created_by: 'user-1',
363
+ created_at: new Date().toISOString(),
364
+ last_updated_at: new Date().toISOString(),
365
+ },
366
+ ],
367
+ next_cursor: null,
368
+ total_pages: 1,
369
+ });
370
+
371
+ // Mock connection request initiation
372
+ mockClient.connectedAccounts.create.mockResolvedValue({
373
+ id: 'connection-request-id',
374
+ connectionData: {
375
+ val: {
376
+ status: 'INITIATED',
377
+ redirectUrl: 'https://auth.url',
378
+ },
379
+ },
380
+ });
381
+
382
+ const result = await toolkits.authorize('user-123', 'test-toolkit');
383
+
384
+ expect(mockClient.authConfigs.create).not.toHaveBeenCalled();
385
+ expect(mockClient.connectedAccounts.create).toHaveBeenCalledWith({
386
+ auth_config: {
387
+ id: 'existing-auth-config-id',
388
+ },
389
+ connection: {
390
+ user_id: 'user-123',
391
+ },
392
+ });
393
+
394
+ expect(result.toJSON()).toEqual({
395
+ id: 'connection-request-id',
396
+ status: 'INITIATED',
397
+ redirectUrl: 'https://auth.url',
398
+ });
399
+ });
400
+
401
+ it('should throw ComposioAuthConfigNotFoundError when toolkit has no auth config details', async () => {
402
+ // Mock toolkit retrieval with no auth config details
403
+ mockClient.toolkits.retrieve.mockResolvedValue({
404
+ name: 'Test Toolkit',
405
+ slug: 'test-toolkit',
406
+ meta: {
407
+ created_at: new Date().toISOString(),
408
+ updated_at: new Date().toISOString(),
409
+ tools_count: 1,
410
+ triggers_count: 0,
411
+ },
412
+ is_local_toolkit: false,
413
+ auth_config_details: [],
414
+ });
415
+
416
+ // Mock empty auth config list
417
+ mockClient.authConfigs.list.mockResolvedValue({
418
+ items: [],
419
+ next_cursor: null,
420
+ total_pages: 1,
421
+ });
422
+
423
+ // Mock the error to be thrown
424
+ mockClient.authConfigs.create.mockRejectedValue(
425
+ new ComposioAuthConfigNotFoundError('No auth config found for toolkit')
426
+ );
427
+
428
+ const promise = toolkits.authorize('user-123', 'test-toolkit');
429
+
430
+ await expect(promise).rejects.toThrow(ComposioAuthConfigNotFoundError);
431
+ await expect(promise).rejects.toThrow('No auth config found for toolkit');
432
+ expect(mockClient.authConfigs.create).not.toHaveBeenCalled();
433
+ expect(mockClient.connectedAccounts.initiate).not.toHaveBeenCalled();
434
+ });
435
+
436
+ it('should throw ComposioToolkitNotFoundError when toolkit does not exist', async () => {
437
+ mockClient.toolkits.retrieve.mockRejectedValue(
438
+ new Error('Toolkit with slug non-existent not found')
439
+ );
440
+
441
+ const promise = toolkits.authorize('user-123', 'non-existent');
442
+
443
+ await expect(promise).rejects.toThrow("Couldn't fetch Toolkit with slug: non-existent");
444
+ expect(mockClient.authConfigs.list).not.toHaveBeenCalled();
445
+ expect(mockClient.authConfigs.create).not.toHaveBeenCalled();
446
+ expect(mockClient.connectedAccounts.initiate).not.toHaveBeenCalled();
447
+ });
448
+ });
449
+});