@devries-cameron20 / composio-1 / commits / 4c53ab0c0
Fork 0

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 upload/download

haxzie committed Jun 20, 2025 at 16:21 UTC 4c53ab0c054c19416a75a7eda078845af7fdb08d
5 files changed +360 -215
ts/examples/connected-accounts/src/magic-flow-demo.ts
+4
@@ -24,6 +24,8 @@ console.log(`Redirect the user to ${redirectUrl}`);
24 // Wait for the user to connect the account / singin to GitHub
25 const connectedAccount = await connectionRequest.waitForConnection();
26
27 +console.log(`Connected account created: ${JSON.stringify(connectedAccount, null, 2)}`);
28 +
29 // ------------------------------------------------------------
30 // 2. Get the GitHub tools
31 // ------------------------------------------------------------
@@ -47,3 +49,5 @@ const response = await openai.chat.completions.create({
49 tools: tools,
50 tool_choice: 'auto',
51 });
52 +
53 +console.log(`Response: ${JSON.stringify(response, null, 2)}`);
ts/examples/tools/src/index.ts
+14 -9
@@ -25,23 +25,28 @@ const composio = new Composio({
25 */
26 async function main() {
27 try {
28 - console.log('🚀 Starting Tools Example...');
29 -
30 - const tools = await composio.tools.getRawComposioTools({
31 - tools: ['GOOGLEDRIVE_UPLOAD_FILE'],
32 - });
33 -
34 - console.log(JSON.stringify(tools, null, 2));
28 + console.log('🚀 Starting Upload file Example...');
29
30 + console.log('🔄 Uploading file...');
31 const result = await composio.tools.execute('GOOGLEDRIVE_UPLOAD_FILE', {
32 arguments: {
33 file_to_upload: path.join(__dirname, 'image.png'),
34 },
35 userId: 'default',
36 });
42 -
37 + console.log('✅ File uploaded successfully...');
38 console.log(JSON.stringify(result, null, 2));
44 -
39 +
40 + console.log('🔄 Downloading file...');
41 + const result2 = await composio.tools.execute('GOOGLEDRIVE_DOWNLOAD_FILE', {
42 + arguments: {
43 + file_id: (result.data.response_data as unknown as { id: string }).id,
44 + },
45 + userId: 'default',
46 + });
47 + console.log('✅ File downloaded successfully...');
48 + console.log(JSON.stringify(result2, null, 2));
49 +
50 } catch (error) {
51 console.error('❌ Error running example:', error);
52 }
ts/packages/core/src/models/Toolkits.ts
+31 -25
@@ -380,20 +380,6 @@ export class Toolkits {
380 const authConfig = await composioAuthConfig.list({
381 toolkit: toolkitSlug,
382 });
383 - if (authConfig.items?.length === 0) {
384 - throw new ComposioAuthConfigNotFoundError(
385 - `No auth configs found for toolkit ${toolkitSlug}`,
386 - {
387 - meta: {
388 - toolkitSlug,
389 - },
390 - possibleFixes: [
391 - `Please Create an auth config for the toolkit ${toolkitSlug} via the dashboard`,
392 - ],
393 - }
394 - );
395 - }
396 -
383 // pick the first auth config
384 authConfigIdToUse = authConfig.items[0]?.id;
385
@@ -401,20 +387,40 @@ export class Toolkits {
387 if (!authConfigIdToUse) {
388 // create authConfig using composioManagedAuthSchemes
389 if (toolkit.authConfigDetails && toolkit.authConfigDetails.length > 0) {
404 - const authConfig = await composioAuthConfig.create(toolkitSlug, {
405 - type: 'use_composio_managed_auth',
406 - name: `${toolkit.name} Auth Config`,
407 - });
408 - authConfigIdToUse = authConfig.id;
390 + try {
391 + const authConfig = await composioAuthConfig.create(toolkitSlug, {
392 + type: 'use_composio_managed_auth',
393 + name: `${toolkit.name} Auth Config`,
394 + });
395 + authConfigIdToUse = authConfig.id;
396 + } catch (error) {
397 + if (error instanceof ComposioClient.APIError && error.status === 400) {
398 + throw new ComposioAuthConfigNotFoundError(
399 + `No Default auth config found for toolkit ${toolkitSlug}`,
400 + {
401 + meta: {
402 + toolkitSlug,
403 + },
404 + cause: error,
405 + possibleFixes: [
406 + `Please Create an auth config for the toolkit ${toolkitSlug} via the dashboard`,
407 + ],
408 + }
409 + );
410 + }
411 + throw error;
412 + }
413 } else {
410 - throw new ComposioAuthConfigNotFoundError('No auth config found for toolkit', {
411 - meta: {
412 - toolkitSlug,
413 - },
414 - });
414 + throw new ComposioAuthConfigNotFoundError(
415 + `No auth configs found for toolkit ${toolkitSlug}`,
416 + {
417 + meta: {
418 + toolkitSlug,
419 + },
420 + }
421 + );
422 }
423 }
417 -
424 // create the auth config
425 const composioConnectedAccount = new ConnectedAccounts(this.client);
426 return await composioConnectedAccount.initiate(userId, authConfigIdToUse, {
ts/packages/core/src/utils/modifiers/FileToolModifier.ts
+190 -70
@@ -21,19 +21,173 @@ const transformProperties = (properties: JSONSchemaProperty): JSONSchemaProperty
21 const newProperties: JSONSchemaProperty = {};
22
23 for (const [key, property] of Object.entries(properties) as [string, JSONSchemaProperty][]) {
24 - if (!property.file_uploadable) {
24 + if (property.file_uploadable) {
25 + // Transform file-uploadable property
26 + newProperties[key] = {
27 + title: property.title,
28 + description: property.description,
29 + format: 'path',
30 + type: 'string',
31 + file_uploadable: true,
32 + };
33 + } else if (property.type === 'object' && property.properties) {
34 + // Recursively transform nested properties
35 + newProperties[key] = {
36 + ...property,
37 + properties: transformProperties(property.properties),
38 + };
39 + } else {
40 + // Copy the property as-is
41 newProperties[key] = property;
26 - continue;
42 }
28 - newProperties[key] = {
29 - ...property,
30 - format: 'path',
31 - };
43 }
44
45 return newProperties;
46 };
47
48 +/**
49 + * Recursively walks a runtime value and its matching JSON-Schema node,
50 + * uploading any string path whose schema node has `file_uploadable: true`.
51 + * The function returns a **new** value with all substitutions applied;
52 + * nothing is mutated in-place.
53 + */
54 +const hydrateFiles = async (
55 + value: unknown,
56 + schema: JSONSchemaProperty | undefined,
57 + ctx: {
58 + toolSlug: string;
59 + toolkitSlug: string;
60 + client: ComposioClient;
61 + }
62 +): Promise<unknown> => {
63 + // ──────────────────────────────────────────────────────────────────────────
64 + // 1. Direct file upload
65 + // ──────────────────────────────────────────────────────────────────────────
66 + if (schema?.file_uploadable) {
67 + // Upload only if the runtime value is a string (i.e., a local path)
68 + if (typeof value !== 'string') return value;
69 +
70 + logger.debug(`Uploading file "${value}"`);
71 + return getFileDataAfterUploadingToS3({
72 + path: value,
73 + toolSlug: ctx.toolSlug,
74 + toolkitSlug: ctx.toolkitSlug,
75 + client: ctx.client,
76 + });
77 + }
78 +
79 + // ──────────────────────────────────────────────────────────────────────────
80 + // 2. Object → traverse each property
81 + // ──────────────────────────────────────────────────────────────────────────
82 + if (schema?.type === 'object' && schema.properties && isPlainObject(value)) {
83 + const transformed: Record<string, unknown> = {};
84 +
85 + for (const [k, v] of Object.entries(value)) {
86 + transformed[k] = await hydrateFiles(v, schema.properties[k], ctx);
87 + }
88 + return transformed;
89 + }
90 +
91 + // ──────────────────────────────────────────────────────────────────────────
92 + // 3. Array → traverse each item
93 + // ──────────────────────────────────────────────────────────────────────────
94 + if (schema?.type === 'array' && schema.items && Array.isArray(value)) {
95 + // `items` can be a single schema or an array of schemas; we handle both.
96 + const itemSchema = Array.isArray(schema.items) ? schema.items[0] : schema.items;
97 +
98 + return Promise.all(
99 + value.map(item => hydrateFiles(item, itemSchema as JSONSchemaProperty, ctx))
100 + );
101 + }
102 +
103 + // ──────────────────────────────────────────────────────────────────────────
104 + // 4. Primitive or schema-less branch → return unchanged
105 + // ──────────────────────────────────────────────────────────────────────────
106 + return value;
107 +};
108 +
109 +/**
110 + * Recursively walks an arbitrary value and its matching JSON-Schema node.
111 + * Whenever it encounters an object that represents a file reference
112 + * (i.e. has an `s3url`), it downloads the file and returns a replacement:
113 + * {
114 + * uri: "<local-path>",
115 + * file_downloaded: true | false,
116 + * s3url: "<original S3 URL>",
117 + * mimeType: "<detected-or-fallback-mime-type>"
118 + * }
119 + *
120 + * The function is side-effect-free: it never mutates the input value.
121 + */
122 +/**
123 + * Walk a value (object, array, primitive).
124 + * Wherever an object contains a string `s3url`, download the file and
125 + * return a replacement object:
126 + * {
127 + * uri: "<local path>",
128 + * file_downloaded: true|false,
129 + * s3url: "<original url>",
130 + * mimeType: "<detected-or-fallback>"
131 + * }
132 + */
133 +const hydrateDownloads = async (value: unknown, ctx: { toolSlug: string }): Promise<unknown> => {
134 + // ─────────────────────────────── 1. direct S3 ref ─────────────────────────
135 + if (isPlainObject(value) && typeof value.s3url === 'string') {
136 + const { s3url, mimetype } = value as {
137 + s3url: string;
138 + mimetype?: string;
139 + };
140 +
141 + try {
142 + logger.debug(`Downloading from S3: ${s3url}`);
143 +
144 + const dl = await downloadFileFromS3({
145 + toolSlug: ctx.toolSlug,
146 + s3Url: s3url,
147 + mimeType: mimetype ?? 'application/octet-stream',
148 + });
149 +
150 + logger.debug(`Downloaded → ${dl.filePath}`);
151 +
152 + return {
153 + uri: dl.filePath,
154 + file_downloaded: true,
155 + s3url,
156 + mimeType: dl.mimeType,
157 + };
158 + } catch (err) {
159 + logger.error(`Download failed: ${s3url}`, { cause: err });
160 + return {
161 + uri: '',
162 + file_downloaded: false,
163 + s3url,
164 + mimeType: mimetype ?? 'application/octet-stream',
165 + };
166 + }
167 + }
168 +
169 + // ─────────────────────────────── 2. object branch ─────────────────────────
170 + if (isPlainObject(value)) {
171 + const pairs = await Promise.all(
172 + Object.entries(value).map(async ([k, v]) => [k, await hydrateDownloads(v, ctx)])
173 + );
174 + return Object.fromEntries(pairs);
175 + }
176 +
177 + // ─────────────────────────────── 3. array branch ──────────────────────────
178 + if (Array.isArray(value)) {
179 + return Promise.all(value.map(item => hydrateDownloads(item, ctx)));
180 + }
181 +
182 + // ─────────────────────────────── 4. primitive ─────────────────────────────
183 + return value; // leave unchanged
184 +};
185 +
186 +// Small helper to recognise plain objects
187 +function isPlainObject(val: unknown): val is Record<string, unknown> {
188 + return typeof val === 'object' && val !== null && !Array.isArray(val);
189 +}
190 +
191 export class FileToolModifier {
192 private client: ComposioClient;
193
@@ -78,35 +232,30 @@ export class FileToolModifier {
232 */
233 async fileUploadModifier(
234 tool: Tool,
81 - options: { toolSlug: string; toolkitSlug: string; params: ToolExecuteParams }
82 - ): Promise<ToolExecuteParams> {
83 - const { arguments: args } = options.params;
84 - if (!args) {
85 - return options.params;
235 + options: {
236 + toolSlug: string;
237 + toolkitSlug?: string;
238 + params: ToolExecuteParams;
239 }
87 - // Check if the arguments is an object
88 - for (const key of Object.keys(args)) {
89 - // Check if the key ends with _schema_parsed_file and is a string
90 - const toolProperty = tool.inputParameters?.properties?.[key];
91 -
92 - if (toolProperty?.file_uploadable) {
93 - logger.debug(`Processing file upload for: ${key}`);
94 - try {
95 - const fileData = await getFileDataAfterUploadingToS3({
96 - path: args[key] as string,
97 - toolSlug: options.toolSlug,
98 - toolkitSlug: options.toolkitSlug ?? 'unknown',
99 - client: this.client,
100 - });
101 - args[key] = fileData;
102 - } catch (error) {
103 - throw new ComposioFileUploadError(`Failed to upload file: ${key}`, {
104 - cause: error,
105 - });
106 - }
107 - }
240 + ): Promise<ToolExecuteParams> {
241 + const { params, toolSlug, toolkitSlug = 'unknown' } = options;
242 + const { arguments: args } = params;
243 +
244 + if (!args || typeof args !== 'object') return params;
245 +
246 + // Recursively transform the arguments tree without mutating the caller’s copy
247 + try {
248 + const newArgs = await hydrateFiles(args, tool.inputParameters, {
249 + toolSlug,
250 + toolkitSlug,
251 + client: this.client,
252 + });
253 + return { ...params, arguments: newArgs as ToolExecuteParams['arguments'] };
254 + } catch (error) {
255 + throw new ComposioFileUploadError('Failed to upload file', {
256 + cause: error,
257 + });
258 }
109 - return options.params;
259 }
260
261 /**
@@ -120,47 +269,18 @@ export class FileToolModifier {
269 * @returns The result with the file download URL included.
270 */
271 async fileDownloadModifier(
123 - tool: Tool,
272 + _tool: Tool, // no longer needed for the traversal itself
273 options: {
274 toolSlug: string;
126 - toolkitSlug: string;
275 + toolkitSlug: string; // kept for API parity, unused here
276 result: ToolExecuteResponse;
277 }
278 ): Promise<ToolExecuteResponse> {
130 - for (const [key, value] of Object.entries(options.result?.data)) {
131 - const fileData = value as { s3url?: string; mimetype?: string };
132 -
133 - if (!fileData?.s3url) continue;
134 -
135 - logger.debug(`Downloading file from S3: ${fileData.s3url}`);
136 -
137 - try {
138 - const downloadedFile = await downloadFileFromS3({
139 - toolSlug: options.toolSlug,
140 - s3Url: fileData.s3url,
141 - mimeType: fileData.mimetype || 'application/txt',
142 - });
143 -
144 - logger.debug(`Downloaded file from S3: ${downloadedFile.filePath}`);
145 -
146 - options.result.data[key] = {
147 - uri: downloadedFile.filePath,
148 - file_downloaded: true,
149 - s3url: fileData.s3url,
150 - mimeType: downloadedFile.mimeType,
151 - };
152 - } catch (error) {
153 - logger.error(`Failed to download file from S3: ${fileData.s3url}`, {
154 - cause: error,
155 - });
156 - options.result.data[key] = {
157 - uri: '',
158 - file_downloaded: false,
159 - s3url: fileData.s3url,
160 - mimeType: fileData.mimetype || 'application/txt',
161 - };
162 - }
163 - }
164 - return options.result;
279 + const { result, toolSlug } = options;
280 +
281 + // Walk result.data without mutating the original
282 + const dataWithDownloads = await hydrateDownloads(result.data, { toolSlug });
283 +
284 + return { ...result, data: dataWithDownloads as typeof result.data };
285 }
286 }
ts/packages/core/test/models/toolkits.test.ts
+121 -111
@@ -221,219 +221,229 @@ describe('Toolkits', () => {
221 });
222
223 describe('authorize', () => {
224 - it('should create auth config and initiate connection request when no auth config exists', async () => {
225 - const userId = 'user_123';
226 - const toolkitSlug = 'test-toolkit';
227 - const options = {
228 - callbackUrl: 'https://example.com/callback',
229 - };
230 -
231 - // Mock toolkit response
232 - mockClient.toolkits.retrieve.mockResolvedValueOnce({
233 - slug: toolkitSlug,
234 - name: 'Test Toolkit',
235 - meta: {
236 - created_at: new Date().toISOString(),
237 - updated_at: new Date().toISOString(),
238 - tools_count: 1,
239 - triggers_count: 0,
240 - },
241 - is_local_toolkit: false,
242 - auth_config_details: [
243 - {
244 - name: 'oauth2',
245 - mode: 'oauth2',
246 - fields: {
247 - auth_config_creation: {
248 - optional: [],
249 - required: [],
250 - },
251 - connected_account_initiation: {
252 - optional: [],
253 - required: [],
254 - },
224 + const userId = 'user_123';
225 + const toolkitSlug = 'test-toolkit';
226 + const mockToolkitResponse = {
227 + slug: toolkitSlug,
228 + name: 'Test Toolkit',
229 + meta: {
230 + created_at: new Date().toISOString(),
231 + updated_at: new Date().toISOString(),
232 + tools_count: 1,
233 + triggers_count: 0,
234 + },
235 + is_local_toolkit: false,
236 + auth_config_details: [
237 + {
238 + name: 'oauth2',
239 + mode: 'OAUTH2',
240 + fields: {
241 + auth_config_creation: {
242 + optional: [],
243 + required: [],
244 + },
245 + connected_account_initiation: {
246 + optional: [],
247 + required: [],
248 },
249 },
257 - ],
258 - });
250 + },
251 + ],
252 + };
253 +
254 + it('should create auth config and initiate connection when no auth config exists', async () => {
255 + // Mock toolkit retrieval
256 + mockClient.toolkits.retrieve.mockResolvedValueOnce(mockToolkitResponse);
257
260 - // Mock auth config list response
258 + // Mock empty auth config list
259 mockClient.authConfigs.list.mockResolvedValueOnce({
260 items: [],
263 - next_cursor: 'next-cursor',
261 + next_cursor: null,
262 total_pages: 1,
263 });
264
267 - // Mock auth config create response
265 + // Mock auth config creation
266 mockClient.authConfigs.create.mockResolvedValueOnce({
267 toolkit: {
268 slug: toolkitSlug,
269 },
270 auth_config: {
271 id: 'auth_config_123',
274 - auth_scheme: 'oauth2',
272 + auth_scheme: 'OAUTH2',
273 is_composio_managed: true,
274 is_disabled: false,
275 + name: 'Test Toolkit Auth Config',
276 + no_of_connections: 0,
277 + status: 'ENABLED',
278 + uuid: 'uuid-1',
279 toolkit: {
278 - slug: toolkitSlug,
280 logo: 'https://example.com/logo.png',
281 + slug: toolkitSlug,
282 },
283 },
284 });
285
284 - // Mock connected accounts list response
286 + // Mock connected accounts list
287 mockClient.connectedAccounts.list.mockResolvedValueOnce({
288 items: [],
289 next_cursor: null,
290 total_pages: 1,
291 });
292
291 - // Mock connected account create response
293 + // Mock connection initiation
294 mockClient.connectedAccounts.create.mockResolvedValueOnce({
295 id: 'conn_123',
296 connectionData: {
297 val: {
296 - authScheme: 'OAUTH2',
298 status: 'INITIALIZING',
299 redirectUrl: 'https://auth.example.com/connect',
300 + authScheme: 'OAUTH2',
301 },
302 },
303 });
304
305 const connectionRequest = await toolkits.authorize(userId, toolkitSlug);
306
307 + // Verify the flow
308 + expect(mockClient.toolkits.retrieve).toHaveBeenCalledWith(toolkitSlug);
309 + expect(mockClient.authConfigs.list).toHaveBeenCalledWith({
310 + toolkit_slug: toolkitSlug,
311 + });
312 expect(mockClient.authConfigs.create).toHaveBeenCalledWith({
306 - toolkit: { slug: toolkitSlug },
313 + toolkit: {
314 + slug: toolkitSlug,
315 + },
316 auth_config: {
317 type: 'use_composio_managed_auth',
318 name: 'Test Toolkit Auth Config',
319 },
320 });
312 -
321 + expect(mockClient.connectedAccounts.create).toHaveBeenCalledWith({
322 + auth_config: {
323 + id: 'auth_config_123',
324 + },
325 + connection: {
326 + user_id: userId,
327 + },
328 + });
329 expect(connectionRequest).toBeInstanceOf(ConnectionRequest);
330 + expect(connectionRequest.redirectUrl).toBe('https://auth.example.com/connect');
331 });
332
316 - it('should use existing auth config to initiate connection request', async () => {
317 - const userId = 'user_123';
318 - const toolkitSlug = 'test-toolkit';
319 - const options = {
320 - callbackUrl: 'https://example.com/callback',
321 - };
322 -
323 - // Mock toolkit response
324 - mockClient.toolkits.retrieve.mockResolvedValueOnce({
325 - slug: toolkitSlug,
326 - name: 'Test Toolkit',
327 - meta: {
328 - created_at: new Date().toISOString(),
329 - updated_at: new Date().toISOString(),
330 - tools_count: 1,
331 - triggers_count: 0,
332 - },
333 - is_local_toolkit: false,
334 - auth_config_details: [
335 - {
336 - name: 'oauth2',
337 - mode: 'OAUTH2',
338 - fields: {
339 - auth_config_creation: {
340 - optional: [],
341 - required: [],
342 - },
343 - connected_account_initiation: {
344 - optional: [],
345 - required: [],
346 - },
347 - },
348 - },
349 - ],
350 - });
333 + it('should use existing auth config to initiate connection', async () => {
334 + // Mock toolkit retrieval
335 + mockClient.toolkits.retrieve.mockResolvedValueOnce(mockToolkitResponse);
336
352 - // Mock auth config list response
337 + // Mock existing auth config
338 mockClient.authConfigs.list.mockResolvedValueOnce({
339 items: [
340 {
356 - id: 'auth_config_123',
341 + id: 'existing_auth_123',
342 auth_scheme: 'OAUTH2',
343 is_composio_managed: true,
344 is_disabled: false,
360 - name: 'Test Toolkit Auth Config',
361 - no_of_connections: 0,
345 + name: 'Existing Auth Config',
346 + no_of_connections: 1,
347 status: 'ENABLED',
348 + uuid: 'uuid-1',
349 toolkit: {
350 logo: 'https://example.com/logo.png',
351 slug: toolkitSlug,
352 },
367 - uuid: 'uuid-1',
368 - credentials: {},
369 - expected_input_fields: [],
370 - created_by: 'user-1',
371 - created_at: new Date().toISOString(),
372 - last_updated_at: new Date().toISOString(),
353 },
354 ],
355 next_cursor: null,
356 total_pages: 1,
357 });
358
379 - // Mock connected accounts list response
359 + // Mock connected accounts list
360 mockClient.connectedAccounts.list.mockResolvedValueOnce({
361 items: [],
362 next_cursor: null,
363 total_pages: 1,
364 });
365
386 - // Mock connected account create response
366 + // Mock connection initiation
367 mockClient.connectedAccounts.create.mockResolvedValueOnce({
368 id: 'conn_123',
369 connectionData: {
370 val: {
391 - authScheme: AuthSchemeTypes.OAUTH2,
371 status: 'INITIALIZING',
372 redirectUrl: 'https://auth.example.com/connect',
373 + authScheme: 'OAUTH2',
374 },
375 },
376 });
377
378 const connectionRequest = await toolkits.authorize(userId, toolkitSlug);
379
380 + // Verify the flow
381 + expect(mockClient.toolkits.retrieve).toHaveBeenCalledWith(toolkitSlug);
382 + expect(mockClient.authConfigs.list).toHaveBeenCalledWith({
383 + toolkit_slug: toolkitSlug,
384 + });
385 expect(mockClient.authConfigs.create).not.toHaveBeenCalled();
386 + expect(mockClient.connectedAccounts.create).toHaveBeenCalledWith({
387 + auth_config: {
388 + id: 'existing_auth_123',
389 + },
390 + connection: {
391 + user_id: userId,
392 + },
393 + });
394 expect(connectionRequest).toBeInstanceOf(ConnectionRequest);
395 + expect(connectionRequest.redirectUrl).toBe('https://auth.example.com/connect');
396 });
397
398 it('should throw ComposioAuthConfigNotFoundError when toolkit has no auth config details', async () => {
399 // Mock toolkit retrieval with no auth config details
406 - mockClient.toolkits.retrieve.mockResolvedValue({
407 - name: 'Test Toolkit',
408 - slug: 'test-toolkit',
409 - meta: {
410 - created_at: new Date().toISOString(),
411 - updated_at: new Date().toISOString(),
412 - tools_count: 1,
413 - triggers_count: 0,
414 - },
415 - is_local_toolkit: false,
416 - auth_config_details: [],
400 + mockClient.toolkits.retrieve.mockResolvedValueOnce({
401 + ...mockToolkitResponse,
402 + auth_config_details: [], // Empty auth config details
403 + });
404 +
405 + // Mock empty auth config list
406 + mockClient.authConfigs.list.mockResolvedValueOnce({
407 + items: [],
408 + next_cursor: null,
409 + total_pages: 1,
410 });
411
412 + const promise = toolkits.authorize(userId, toolkitSlug);
413 +
414 + await expect(promise).rejects.toThrow(ComposioAuthConfigNotFoundError);
415 + await expect(promise).rejects.toThrow(`No auth configs found for toolkit ${toolkitSlug}`);
416 + expect(mockClient.authConfigs.create).not.toHaveBeenCalled();
417 + expect(mockClient.connectedAccounts.create).not.toHaveBeenCalled();
418 + });
419 +
420 + it('should throw ComposioAuthConfigNotFoundError when auth config creation fails', async () => {
421 + // Mock toolkit retrieval
422 + mockClient.toolkits.retrieve.mockResolvedValueOnce(mockToolkitResponse);
423 +
424 // Mock empty auth config list
420 - mockClient.authConfigs.list.mockResolvedValue({
425 + mockClient.authConfigs.list.mockResolvedValueOnce({
426 items: [],
427 next_cursor: null,
428 total_pages: 1,
429 });
430
426 - // Mock the error to be thrown
427 - mockClient.authConfigs.create.mockRejectedValue(
428 - new ComposioAuthConfigNotFoundError('No auth config found for toolkit')
431 + // Mock auth config creation failure with ComposioClient.APIError
432 + const apiError = new ComposioClient.APIError(
433 + 400,
434 + 'Bad Request',
435 + 'Bad Request',
436 + new Headers()
437 );
438 + mockClient.authConfigs.create.mockRejectedValueOnce(apiError);
439
431 - const promise = toolkits.authorize('user-123', 'test-toolkit');
440 + const promise = toolkits.authorize(userId, toolkitSlug);
441
442 await expect(promise).rejects.toThrow(ComposioAuthConfigNotFoundError);
434 - await expect(promise).rejects.toThrow('No auth config found for toolkit');
435 - expect(mockClient.authConfigs.create).not.toHaveBeenCalled();
436 - expect(mockClient.connectedAccounts.initiate).not.toHaveBeenCalled();
443 + await expect(promise).rejects.toThrow(
444 + `No Default auth config found for toolkit ${toolkitSlug}`
445 + );
446 + expect(mockClient.connectedAccounts.create).not.toHaveBeenCalled();
447 });
448
449 it('should throw ComposioToolkitNotFoundError when toolkit does not exist', async () => {
@@ -446,7 +456,7 @@ describe('Toolkits', () => {
456 await expect(promise).rejects.toThrow("Couldn't fetch Toolkit with slug: non-existent");
457 expect(mockClient.authConfigs.list).not.toHaveBeenCalled();
458 expect(mockClient.authConfigs.create).not.toHaveBeenCalled();
449 - expect(mockClient.connectedAccounts.initiate).not.toHaveBeenCalled();
459 + expect(mockClient.connectedAccounts.create).not.toHaveBeenCalled();
460 });
461 });
462