@devries-cameron20 / composio-1 / commits / ead47955a
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.

Add tests and abilities for file upload/download

haxzie committed Jun 20, 2025 at 12:16 UTC ead47955a448c65fc3ea600fbf948bb7e819886c
12 files changed +565 -69
ts/docs/advanced/auto-upload-download.md new
+201
@@ -0,0 +1,201 @@
1 +# Auto Upload and Download Files
2 +
3 +Composio SDK includes an automatic file handling system that manages file uploads and downloads when executing tools. This guide explains how the system works, how to configure it, and how to handle files manually when auto-handling is disabled.
4 +
5 +## Overview
6 +
7 +The file handling system in Composio SDK is:
8 +
9 +- **Opt-out**: Enabled by default but can be disabled
10 +- **Automatic**: Handles file uploads and downloads transparently
11 +- **Configurable**: Can be disabled for manual file handling
12 +
13 +## How It Works
14 +
15 +### File Upload
16 +
17 +When a tool's input parameter is marked with `file_uploadable: true`, the SDK will:
18 +
19 +1. Automatically detect file paths in the input
20 +2. Upload the file to Composio's secure storage
21 +3. Replace the file path with file metadata in the tool execution
22 +
23 +Example tool schema with file upload:
24 +
25 +```typescript
26 +const toolSchema = {
27 + inputParameters: {
28 + type: 'object',
29 + properties: {
30 + file: {
31 + type: 'string',
32 + file_uploadable: true
33 + }
34 + }
35 + }
36 +}
37 +```
38 +
39 +When executing a tool with file upload:
40 +
41 +```typescript
42 +// With auto upload enabled (default)
43 +const result = await composio.tools.execute('your-tool', {
44 + arguments: {
45 + file: '/path/to/local/file.txt' // Local file path
46 + // or
47 + file: 'https://example.com/file.txt' // Remote URL
48 + }
49 +});
50 +
51 +// The SDK automatically:
52 +// 1. Reads the file content
53 +// 2. Uploads it to S3
54 +// 3. Replaces the path with metadata:
55 +// {
56 +// name: string; // The original filename
57 +// mimetype: string; // The file's mime type
58 +// s3key: string; // The S3 key for the uploaded file
59 +// }
60 +```
61 +
62 +### File Download
63 +
64 +When a tool's output contains an S3 URL and mimetype, the SDK will:
65 +
66 +1. Automatically detect file URLs in the response
67 +2. Download the file to a local temporary directory
68 +3. Replace the S3 URL with local file information
69 +
70 +Example tool response with file download:
71 +
72 +```typescript
73 +// Original response from tool
74 +{
75 + data: {
76 + file: {
77 + s3url: 'https://s3.example.com/file.txt',
78 + mimetype: 'text/plain'
79 + }
80 + }
81 +}
82 +
83 +// After auto-download
84 +{
85 + data: {
86 + file: {
87 + uri: '/path/to/local/file.txt',
88 + file_downloaded: true,
89 + s3url: 'https://s3.example.com/file.txt',
90 + mimeType: 'text/plain'
91 + }
92 + }
93 +}
94 +```
95 +
96 +## Disabling Auto File Handling
97 +
98 +You can disable automatic file handling when initializing the SDK:
99 +
100 +```typescript
101 +import { Composio } from '@composio/core';
102 +
103 +const composio = new Composio({
104 + apiKey: 'your-api-key',
105 + autoUploadDownloadFiles: false
106 +});
107 +```
108 +
109 +## Manual File Handling
110 +
111 +When auto file handling is disabled, you'll need to handle the file operations yourself using the `composio.files` API:
112 +
113 +### Manual Upload
114 +
115 +When auto-upload is disabled, you need to handle file uploads manually:
116 +
117 +```typescript
118 +// Upload file manually
119 +const fileData = await composio.files.upload({
120 + filePath: '/path/to/file.txt', // Local path or URL
121 + toolSlug: 'your-tool', // Tool slug
122 + toolkitSlug: 'your-toolkit' // Toolkit slug
123 +});
124 +
125 +// Execute tool with file data
126 +const result = await composio.tools.execute('your-tool', {
127 + arguments: {
128 + file: fileData // Contains name, mimetype, and s3key
129 + }
130 +});
131 +```
132 +
133 +### Manual Download
134 +
135 +When auto-download is disabled, you'll need to handle file downloads manually:
136 +
137 +```typescript
138 +// Execute tool
139 +const result = await composio.tools.execute('your-tool', {
140 + arguments: {
141 + // your arguments
142 + }
143 +});
144 +
145 +// Download file manually if response contains S3 URL
146 +if (result.data.file?.s3url) {
147 + const downloadedFile = await composio.files.download({
148 + s3Url: result.data.file.s3url,
149 + toolSlug: 'your-tool',
150 + mimeType: result.data.file.mimetype || 'application/txt'
151 + });
152 +
153 + // downloadedFile contains:
154 + // {
155 + // name: string; // Generated filename (toolSlug_timestamp.ext)
156 + // mimeType: string; // The file's mime type
157 + // s3Url: string; // The original S3 URL
158 + // filePath: string; // Local path to the downloaded file
159 + // }
160 +}
161 +```
162 +
163 +## File Storage Location
164 +
165 +Downloaded files are stored in a temporary directory:
166 +
167 +- Location: `~/.composio/files/` (user's home directory)
168 +- Files are named using the pattern: `{toolSlug}_{timestamp}.{extension}`
169 +- The directory is created automatically when needed
170 +- File extensions are derived from the MIME type
171 +
172 +## Error Handling
173 +
174 +The SDK includes specific error types for file operations:
175 +
176 +```typescript
177 +import { ComposioFileUploadError } from '@composio/core';
178 +
179 +try {
180 + await composio.tools.execute('your-tool', {
181 + arguments: {
182 + file: '/path/to/file.txt'
183 + }
184 + });
185 +} catch (error) {
186 + if (error instanceof ComposioFileUploadError) {
187 + console.error('File upload failed:', error.message);
188 + // Handle file upload error
189 + // Possible fixes will be included in error.possibleFixes
190 + }
191 + throw error;
192 +}
193 +```
194 +
195 +## Additional Features
196 +
197 +- **URL Support**: The file upload system supports both local file paths and URLs
198 +- **MIME Type Detection**: Automatically detects MIME types from files and URLs
199 +- **Automatic Directory Creation**: Creates necessary directories for file storage
200 +- **Error Recovery**: Provides graceful error handling with helpful error messages
201 +- **MD5 Checksum**: Generates MD5 checksums for file integrity verification
ts/docs/advanced/telemetry.md
-1
@@ -219,7 +219,6 @@ interface TelemetryMetadata {
219 source: string; // The runtime environment
220 version: string; // The SDK version
221 isBrowser: boolean; // Whether the SDK is running in a browser
222 - sessionId: string; // A random session ID (changes each init)
222 }
223 ```
224
ts/docs/api/composio.md
+21 -10
@@ -11,9 +11,8 @@ const composio = new Composio({
11 apiKey: 'your-api-key',
12 baseURL: 'https://api.composio.dev', // Optional: Custom API endpoint
13 allowTracking: true, // Optional: Enable/disable telemetry
14 - allowTracing: true, // Optional: Enable/disable tracing
14 + autoUploadDownloadFiles: true, // Optional: Enable/disable automatic file handling
15 provider: new OpenAIProvider(), // Optional: Custom provider
16 - telemetryTransport: customTransport, // Optional: Custom telemetry transport
16 });
17 ```
18
@@ -21,14 +20,13 @@ const composio = new Composio({
20
21 The `Composio` constructor accepts a configuration object with the following properties:
22
24 -| Property | Type | Required | Default | Description |
25 -| -------------------- | ------------------------ | -------- | -------------------------- | ---------------------------------------------- |
26 -| `apiKey` | string | Yes | - | Your Composio API key |
27 -| `baseURL` | string | No | `https://api.composio.dev` | The base URL for the Composio API |
28 -| `allowTracking` | boolean | No | `true` | Whether to allow analytics/tracking |
29 -| `allowTracing` | boolean | No | `true` | Whether to allow tracing |
30 -| `provider` | `BaseComposioProvider` | No | `new OpenAIProvider()` | The provider to use for this Composio instance |
31 -| `telemetryTransport` | `BaseTelemetryTransport` | No | - | Custom transport for telemetry data |
23 +| Property | Type | Required | Default | Description |
24 +| ----------------------- | ------------------------ | -------- | -------------------------- | ---------------------------------------------- |
25 +| `apiKey` | string | Yes | - | Your Composio API key |
26 +| `baseURL` | string | No | `https://api.composio.dev` | The base URL for the Composio API |
27 +| `allowTracking` | boolean | No | `true` | Whether to allow analytics/tracking |
28 +| `autoUploadDownloadFiles`| boolean | No | `true` | Whether to automatically handle file operations |
29 +| `provider` | `BaseComposioProvider` | No | `new OpenAIProvider()` | The provider to use for this Composio instance |
30
31 ## Properties
32
@@ -41,8 +39,10 @@ The `Composio` class provides access to the following core models:
39 | `triggers` | `Triggers` | Access to triggers functionality |
40 | `authConfigs` | `AuthConfigs` | Access to auth configs functionality |
41 | `connectedAccounts` | `ConnectedAccounts` | Access to connected accounts functionality |
42 +| `files` | `Files` | Access to file upload/download functionality|
43 | `provider` | `BaseComposioProvider` | The provider being used |
44
45 +
46 ## Methods
47
48 ### getClient()
@@ -92,3 +92,14 @@ const composio = new Composio({
92 allowTracking: false,
93 });
94 ```
95 +
96 +### Disable Automatic File Handling
97 +
98 +```typescript
99 +import { Composio } from '@composio/core';
100 +
101 +const composio = new Composio({
102 + apiKey: process.env.COMPOSIO_API_KEY,
103 + autoUploadDownloadFiles: false,
104 +});
105 +```
ts/examples/tools/src/index.ts
+2 -2
@@ -17,8 +17,7 @@ import path from 'path';
17 */
18 const composio = new Composio({
19 apiKey: process.env.COMPOSIO_API_KEY,
20 - allowTracking: false,
21 - allowTracing: false,
20 + allowTracking: false
21 });
22
23 /**
@@ -42,6 +41,7 @@ async function main() {
41 });
42
43 console.log(JSON.stringify(result, null, 2));
44 +
45 } catch (error) {
46 console.error('❌ Error running example:', error);
47 }
ts/packages/core/src/composio.ts
+8 -10
@@ -13,10 +13,9 @@ import { COMPOSIO_LOG_LEVEL, IS_DEVELOPMENT_OR_CI } from './utils/constants';
13 import { checkForLatestVersionFromNPM } from './utils/version';
14 import { OpenAIProvider } from './provider/OpenAIProvider';
15 import { version } from '../package.json';
16 -import { getRandomUUID } from './utils/uuid';
16 import type { ComposioRequestHeaders } from './types/composio.types';
17 import { McpServerGetResponse } from './types/mcp.types';
19 -import { getEnvVariable } from './utils/env';
18 +import { Files } from './models/Files';
19
20 export type ComposioConfig<
21 TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider,
@@ -38,11 +37,11 @@ export type ComposioConfig<
37 */
38 allowTracking?: boolean;
39 /**
41 - * Whether to allow tracing for the Composio instance.
40 + * Whether to automatically upload and download files during tool execution.
41 * @example true, false
42 * @default true
43 */
45 - allowTracing?: boolean;
44 + autoUploadDownloadFiles?: boolean;
45 /**
46 * The tool provider to use for this Composio instance.
47 * @example new OpenAIProvider()
@@ -101,6 +100,7 @@ export class Composio<
100 toolkits: Toolkits;
101 triggers: Triggers;
102 provider: TProvider;
103 + files: Files;
104 // auth configs
105 authConfigs: AuthConfigs;
106 // connected accounts
@@ -118,7 +118,6 @@ export class Composio<
118 * @param {string} [config.apiKey] - The API key for authenticating with the Composio API
119 * @param {string} [config.baseURL] - The base URL for the Composio API (defaults to production URL)
120 * @param {boolean} [config.allowTracking=true] - Whether to allow anonymous usage analytics
121 - * @param {boolean} [config.allowTracing=true] - Whether to allow request tracing for debugging
121 * @param {TProvider} [config.provider] - The provider to use for this Composio instance (defaults to OpenAIProvider)
122 *
123 * @example
@@ -167,19 +166,21 @@ export class Composio<
166 this.config = {
167 ...config,
168 allowTracking: config?.allowTracking ?? true,
170 - allowTracing: config?.allowTracing ?? true,
169 };
170
171 /**
172 * Set the default provider, if not provided by the user.
173 */
174 this.provider = (config?.provider ?? new OpenAIProvider()) as TProvider;
177 - this.tools = new Tools(this.client, this.provider);
175 + this.tools = new Tools(this.client, this.provider, {
176 + autoUploadDownloadFiles: config?.autoUploadDownloadFiles ?? true,
177 + });
178 this.mcp = new MCP(this.client, this.provider);
179
180 this.toolkits = new Toolkits(this.client);
181 this.triggers = new Triggers(this.client);
182 this.authConfigs = new AuthConfigs(this.client);
183 + this.files = new Files(this.client);
184
185 // Initialize the connected accounts model.
186 this.connectedAccounts = new ConnectedAccounts(this.client);
@@ -196,9 +197,6 @@ export class Composio<
197 isBrowser: typeof window !== 'undefined',
198 provider: this.provider?.name ?? 'openai',
199 host: this.config.host,
199 - // @TODO: Users might want to pass their own session id
200 - // @TODO: We shouldn't be doing this as people might always have one session id throughout the process in server
201 - sessionId: this.config.allowTracing ? getRandomUUID() : undefined, // @TODO: get the session id
200 });
201 }
202 telemetry.instrument(this);
ts/packages/core/src/models/Files.ts new
+53
@@ -0,0 +1,53 @@
1 +import ComposioClient from '@composio/client';
2 +import { FileDownloadData, FileUploadData } from '../types/files.types';
3 +import { downloadFileFromS3, getFileDataAfterUploadingToS3 } from '../utils/fileUtils';
4 +import { telemetry } from '../telemetry/Telemetry';
5 +
6 +export class Files {
7 + constructor(private readonly client: ComposioClient) {
8 + telemetry.instrument(this);
9 + }
10 +
11 + /**
12 + * Upload a file to S3 and return the file data.
13 + * @param filePath - The path to the file to upload or a URL of the file to upload.
14 + * @param toolSlug - The slug of the tool that is uploading the file.
15 + * @param toolkitSlug - The slug of the toolkit that is uploading the file.
16 + * @returns The file data.
17 + */
18 + async upload({
19 + filePath,
20 + toolSlug,
21 + toolkitSlug,
22 + }: {
23 + filePath: string;
24 + toolSlug: string;
25 + toolkitSlug: string;
26 + }): Promise<FileUploadData> {
27 + const fileData = await getFileDataAfterUploadingToS3({
28 + path: filePath,
29 + toolSlug,
30 + toolkitSlug,
31 + client: this.client,
32 + });
33 + return fileData;
34 + }
35 +
36 + /**
37 + * Download a file from S3 and return the file data.
38 + * @param s3key - The S3 key of the file to download.
39 + * @returns The file data.
40 + */
41 + async download({
42 + toolSlug,
43 + s3Url,
44 + mimeType,
45 + }: {
46 + s3Url: string;
47 + toolSlug: string;
48 + mimeType: string;
49 + }): Promise<FileDownloadData> {
50 + const fileDownloadData = await downloadFileFromS3({ toolSlug, s3Url, mimeType });
51 + return fileDownloadData;
52 + }
53 +}
ts/packages/core/src/models/Tools.ts
+38 -19
@@ -56,8 +56,13 @@ export class Tools<
56 private client: ComposioClient;
57 private readonly customTools: CustomTools;
58 private provider: TProvider;
59 + private autoUploadDownloadFiles: boolean;
60
60 - constructor(client: ComposioClient, provider: TProvider) {
61 + constructor(
62 + client: ComposioClient,
63 + provider: TProvider,
64 + options?: { autoUploadDownloadFiles: boolean }
65 + ) {
66 if (!client) {
67 throw new Error('ComposioClient is required');
68 }
@@ -68,6 +73,7 @@ export class Tools<
73 this.client = client;
74 this.customTools = new CustomTools(client);
75 this.provider = provider;
76 + this.autoUploadDownloadFiles = options?.autoUploadDownloadFiles ?? true;
77 // Bind the execute method to ensure correct 'this' context
78 this.execute = this.execute.bind(this);
79 // Set the execute method for the provider
@@ -227,12 +233,16 @@ export class Tools<
233 * @returns The tools with the default schema modifiers applied
234 */
235 private async applyDefaultSchemaModifiers(tools: Tool[]): Promise<Tool[]> {
230 - const fileToolModifier = new FileToolModifier(this.client);
231 - return await Promise.all(
232 - tools.map(tool =>
233 - fileToolModifier.modifyToolSchema(tool.slug, tool.toolkit?.slug ?? 'unknown', tool)
234 - )
235 - );
236 + if (this.autoUploadDownloadFiles) {
237 + const fileToolModifier = new FileToolModifier(this.client);
238 + return await Promise.all(
239 + tools.map(tool =>
240 + fileToolModifier.modifyToolSchema(tool.slug, tool.toolkit?.slug ?? 'unknown', tool)
241 + )
242 + );
243 + } else {
244 + return tools;
245 + }
246 }
247
248 /**
@@ -256,8 +266,17 @@ export class Tools<
266 },
267 modifier?: beforeExecuteModifier
268 ): Promise<ToolExecuteParams> {
259 - const fileToolModifier = new FileToolModifier(this.client);
269 let modifiedParams = params;
270 + // if auto upload download files is enabled, upload the files to the Composio API
271 + if (this.autoUploadDownloadFiles) {
272 + const fileToolModifier = new FileToolModifier(this.client);
273 + modifiedParams = await fileToolModifier.fileUploadModifier(tool, {
274 + toolSlug,
275 + toolkitSlug,
276 + params: modifiedParams,
277 + });
278 + }
279 + // apply the before execute modifiers
280 if (modifier) {
281 if (typeof modifier === 'function') {
282 modifiedParams = await modifier({
@@ -269,11 +288,6 @@ export class Tools<
288 throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
289 }
290 }
272 - modifiedParams = await fileToolModifier.fileUploadModifier(tool, {
273 - toolSlug,
274 - toolkitSlug,
275 - params: modifiedParams,
276 - });
291 return modifiedParams;
292 }
293
@@ -298,8 +312,17 @@ export class Tools<
312 },
313 modifier?: afterExecuteModifier
314 ): Promise<ToolExecuteResponse> {
301 - const fileToolModifier = new FileToolModifier(this.client);
315 let modifiedResult = result;
316 + // if auto upload download files is enabled, download the files from the Composio API
317 + if (this.autoUploadDownloadFiles) {
318 + const fileToolModifier = new FileToolModifier(this.client);
319 + modifiedResult = await fileToolModifier.fileDownloadModifier(tool, {
320 + toolSlug,
321 + toolkitSlug,
322 + result: modifiedResult,
323 + });
324 + }
325 + // apply the after execute modifiers
326 if (modifier) {
327 if (typeof modifier === 'function') {
328 modifiedResult = await modifier({
@@ -311,11 +334,7 @@ export class Tools<
334 throw new ComposioInvalidModifierError('Invalid afterExecute modifier. Not a function.');
335 }
336 }
314 - modifiedResult = await fileToolModifier.fileDownloadModifier(tool, {
315 - toolSlug,
316 - toolkitSlug,
317 - result: modifiedResult,
318 - });
337 +
338 return modifiedResult;
339 }
340
ts/packages/core/src/types/files.types.ts new
+12
@@ -0,0 +1,12 @@
1 +export type FileUploadData = {
2 + name: string;
3 + mimetype: string;
4 + s3key: string;
5 +};
6 +
7 +export type FileDownloadData = {
8 + name: string;
9 + mimeType: string;
10 + s3Url: string;
11 + filePath: string;
12 +};
ts/packages/core/src/types/telemetry.types.ts
-1
@@ -41,7 +41,6 @@ export type TelemetryMetadata = {
41 * @example 'openai', 'anthropic', 'google', 'azure', 'composio'
42 */
43 provider?: string;
44 - sessionId?: string;
44 isBrowser?: boolean;
45 };
46
ts/packages/core/src/utils/fileUtils.ts
+14 -12
@@ -3,6 +3,7 @@ import pathModule from 'path';
3 import ComposioClient from '@composio/client';
4 import { COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME } from './constants';
5 import logger from './logger';
6 +import { FileDownloadData, FileUploadData } from '../types/files.types';
7
8 const readFileContent = async (path: string): Promise<{ content: string; mimeType: string }> => {
9 try {
@@ -76,16 +77,17 @@ const uploadFileToS3 = async (
77 return key;
78 };
79
79 -export const getFileDataAfterUploadingToS3 = async (
80 - path: string,
81 - toolSlug: string,
82 - toolkitSlug: string,
83 - client: ComposioClient
84 -): Promise<{
85 - name: string;
86 - mimetype: string;
87 - s3key: string;
88 -}> => {
80 +export const getFileDataAfterUploadingToS3 = async ({
81 + path,
82 + toolSlug,
83 + toolkitSlug,
84 + client,
85 +}: {
86 + path: string;
87 + toolSlug: string;
88 + toolkitSlug: string;
89 + client: ComposioClient;
90 +}): Promise<FileUploadData> => {
91 const isURL = path.startsWith('http');
92 const fileData = isURL ? await readFileContentFromURL(path) : await readFileContent(path);
93 logger.debug(`Uploading file to S3: ${path}`);
@@ -115,7 +117,7 @@ export const downloadFileFromS3 = async ({
117 toolSlug: string;
118 s3Url: string;
119 mimeType: string;
118 -}) => {
120 +}): Promise<FileDownloadData> => {
121 const response = await fetch(s3Url);
122 if (!response.ok) {
123 throw new Error(`Failed to download file: ${response.statusText}`);
@@ -128,7 +130,7 @@ export const downloadFileFromS3 = async ({
130 return {
131 name: fileName,
132 mimeType: mimeType,
131 - s3Key: s3Url,
133 + s3Url: s3Url,
134 filePath: filePath,
135 };
136 };
ts/packages/core/src/utils/modifiers/FileToolModifier.ts
+6 -6
@@ -92,12 +92,12 @@ export class FileToolModifier {
92 if (toolProperty?.file_uploadable) {
93 logger.debug(`Processing file upload for: ${key}`);
94 try {
95 - const fileData = await getFileDataAfterUploadingToS3(
96 - args[key] as string,
97 - options.toolSlug,
98 - options.toolkitSlug ?? 'unknown',
99 - this.client
100 - );
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}`, {
ts/packages/core/test/tools/fileModifiers.test.ts
+210 -8
@@ -1,9 +1,15 @@
1 import { describe, it, expect, vi, beforeEach } from 'vitest';
2 import { FileToolModifier } from '../../src/utils/modifiers/FileToolModifier';
3 import ComposioClient from '@composio/client';
4 -import { Tool } from '../../src/types/tool.types';
4 +import { Tool, ToolExecuteResponse } from '../../src/types/tool.types';
5 import { ComposioFileUploadError } from '../../src/errors/FileModifierErrors';
6 import * as fileUtils from '../../src/utils/fileUtils';
7 +import { Tools } from '../../src/models/Tools';
8 +import { BaseComposioProvider } from '../../src/provider/BaseProvider';
9 +import { createTestContext, setupTest, mockToolExecution } from '../utils/toolExecuteUtils';
10 +import { mockClient } from '../utils/mocks/client.mock';
11 +import { toolMocks } from '../utils/mocks/data.mock';
12 +import { ToolExecuteResponse as ComposioToolExecuteResponse } from '@composio/client/resources/tools';
13
14 // Mock the fileUtils module
15 vi.mock('../../src/utils/fileUtils', () => ({
@@ -105,12 +111,12 @@ describe('FileToolModifier', () => {
111 params,
112 });
113
108 - expect(fileUtils.getFileDataAfterUploadingToS3).toHaveBeenCalledWith(
109 - '/path/to/file.txt',
110 - 'test-tool',
111 - 'test-toolkit',
112 - mockClient
113 - );
114 + expect(fileUtils.getFileDataAfterUploadingToS3).toHaveBeenCalledWith({
115 + path: '/path/to/file.txt',
116 + toolSlug: 'test-tool',
117 + toolkitSlug: 'test-toolkit',
118 + client: mockClient,
119 + });
120 expect(result.arguments?.file).toEqual(mockFileData);
121 expect(result.arguments?.text).toBe('some text');
122 });
@@ -149,7 +155,7 @@ describe('FileToolModifier', () => {
155 const mockDownloadResult = {
156 name: 'file.txt',
157 mimeType: 'text/plain',
152 - s3Key: 'downloads/file.txt',
158 + s3Url: 'downloads/file.txt',
159 filePath: '/downloaded/file.txt',
160 };
161 vi.mocked(fileUtils.downloadFileFromS3).mockResolvedValue(mockDownloadResult);
@@ -236,3 +242,199 @@ describe('FileToolModifier', () => {
242 });
243 });
244 });
245 +
246 +describe('Tools with autoUploadDownloadFiles', () => {
247 + const context = createTestContext();
248 + setupTest(context);
249 +
250 + const mockToolWithFileUpload: Tool = {
251 + slug: 'COMPOSIO_TOOL',
252 + name: 'Composio Tool',
253 + description: 'A test tool',
254 + tags: ['test'],
255 + toolkit: {
256 + slug: 'test-toolkit',
257 + name: 'Test Toolkit',
258 + },
259 + inputParameters: {
260 + type: 'object' as const,
261 + properties: {
262 + file: {
263 + type: 'string',
264 + file_uploadable: true,
265 + },
266 + },
267 + additionalProperties: false,
268 + },
269 + outputParameters: {
270 + type: 'object' as const,
271 + properties: {
272 + file: {
273 + type: 'object',
274 + properties: {
275 + s3url: {
276 + type: 'string',
277 + },
278 + mimetype: {
279 + type: 'string',
280 + },
281 + },
282 + },
283 + },
284 + additionalProperties: false,
285 + },
286 + };
287 +
288 + const mockRawToolWithFileUpload = {
289 + slug: 'COMPOSIO_TOOL',
290 + name: 'Composio Tool',
291 + description: 'A test tool',
292 + tags: ['test'],
293 + toolkit: {
294 + slug: 'test-toolkit',
295 + name: 'Test Toolkit',
296 + },
297 + input_parameters: {
298 + type: 'object',
299 + properties: {
300 + file: {
301 + type: 'string',
302 + file_uploadable: true,
303 + },
304 + },
305 + additionalProperties: false,
306 + },
307 + output_parameters: {
308 + type: 'object',
309 + properties: {
310 + file: {
311 + type: 'object',
312 + properties: {
313 + s3url: {
314 + type: 'string',
315 + },
316 + mimetype: {
317 + type: 'string',
318 + },
319 + },
320 + },
321 + },
322 + additionalProperties: false,
323 + },
324 + };
325 +
326 + describe('when autoUploadDownloadFiles is false', () => {
327 + beforeEach(async () => {
328 + context.tools = new Tools(mockClient as unknown as ComposioClient, context.mockProvider, {
329 + autoUploadDownloadFiles: false,
330 + });
331 +
332 + // Mock the tool execution
333 + const { getRawComposioToolBySlugSpy } = await mockToolExecution(context.tools);
334 + getRawComposioToolBySlugSpy.mockReset();
335 + getRawComposioToolBySlugSpy.mockResolvedValue(mockToolWithFileUpload);
336 +
337 + // Mock the client's tools.list method
338 + mockClient.tools.list.mockResolvedValue({
339 + items: [mockRawToolWithFileUpload],
340 + totalPages: 1,
341 + });
342 +
343 + // Mock the file upload and download utilities
344 + vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockResolvedValue({
345 + name: 'file.txt',
346 + mimetype: 'text/plain',
347 + s3key: 'uploads/file.txt',
348 + });
349 +
350 + vi.mocked(fileUtils.downloadFileFromS3).mockResolvedValue({
351 + name: 'file.txt',
352 + mimeType: 'text/plain',
353 + s3Url: 'downloads/file.txt',
354 + filePath: '/path/to/downloaded/file.txt',
355 + });
356 +
357 + // Mock the provider's wrapTools method
358 + context.mockProvider.wrapTools.mockImplementation(tools => tools);
359 + });
360 +
361 + it('should not modify tool schema for file upload', async () => {
362 + const result = await context.tools.getRawComposioTools({ tools: ['COMPOSIO_TOOL'] });
363 + expect(result[0].inputParameters?.properties?.file).not.toHaveProperty('format');
364 + expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
365 + });
366 +
367 + it('should not upload files during execution', async () => {
368 + // Mock getRawComposioToolBySlug for this test
369 + vi.spyOn(context.tools, 'getRawComposioToolBySlug').mockResolvedValueOnce(
370 + mockToolWithFileUpload
371 + );
372 +
373 + await context.tools.execute('COMPOSIO_TOOL', {
374 + arguments: {
375 + file: '/path/to/file.txt',
376 + },
377 + userId: 'test-user',
378 + });
379 +
380 + expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
381 + expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {
382 + arguments: {
383 + file: '/path/to/file.txt',
384 + },
385 + allow_tracing: undefined,
386 + connected_account_id: undefined,
387 + custom_auth_params: undefined,
388 + text: undefined,
389 + user_id: 'test-user',
390 + version: undefined,
391 + });
392 + });
393 +
394 + it('should not download files from execution results', async () => {
395 + // Mock getRawComposioToolBySlug for this test
396 + vi.spyOn(context.tools, 'getRawComposioToolBySlug').mockResolvedValueOnce(
397 + mockToolWithFileUpload
398 + );
399 +
400 + // Mock the response data structure correctly
401 + const mockResponse = {
402 + data: {
403 + file: {
404 + s3url: 'https://s3.example.com/file.txt',
405 + mimetype: 'text/plain',
406 + },
407 + },
408 + error: null,
409 + successful: true,
410 + log_id: '123',
411 + session_info: {},
412 + };
413 +
414 + // Mock the client's execute method to return the raw response
415 + mockClient.tools.execute.mockResolvedValueOnce(mockResponse);
416 +
417 + // Mock transformToolExecuteResponse to return the same data structure
418 + vi.spyOn(context.tools as any, 'transformToolExecuteResponse').mockReturnValue({
419 + data: mockResponse.data,
420 + error: mockResponse.error,
421 + successful: mockResponse.successful,
422 + logId: mockResponse.log_id,
423 + sessionInfo: mockResponse.session_info,
424 + });
425 +
426 + const result = await context.tools.execute('COMPOSIO_TOOL', {
427 + arguments: {
428 + file: '/path/to/file.txt',
429 + },
430 + userId: 'test-user',
431 + });
432 +
433 + expect(fileUtils.downloadFileFromS3).not.toHaveBeenCalled();
434 + expect(result.data.file).toEqual({
435 + s3url: 'https://s3.example.com/file.txt',
436 + mimetype: 'text/plain',
437 + });
438 + });
439 + });
440 +});