Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Add tests and abilities for file upload/download
haxzieead47955a448
diff --git a/ts/docs/advanced/auto-upload-download.md b/ts/docs/advanced/auto-upload-download.mdnew file mode 100644index 000000000..7416afe6d--- /dev/null+++ b/ts/docs/advanced/auto-upload-download.md@@ -0,0 +1,201 @@+# Auto Upload and Download Files++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.++## Overview++The file handling system in Composio SDK is:++- **Opt-out**: Enabled by default but can be disabled+- **Automatic**: Handles file uploads and downloads transparently+- **Configurable**: Can be disabled for manual file handling++## How It Works++### File Upload++When a tool's input parameter is marked with `file_uploadable: true`, the SDK will:++1. Automatically detect file paths in the input+2. Upload the file to Composio's secure storage+3. Replace the file path with file metadata in the tool execution++Example tool schema with file upload:++```typescript+const toolSchema = {+ inputParameters: {+ type: 'object',+ properties: {+ file: {+ type: 'string',+ file_uploadable: true+ }+ }+ }+}+```++When executing a tool with file upload:++```typescript+// With auto upload enabled (default)+const result = await composio.tools.execute('your-tool', {+ arguments: {+ file: '/path/to/local/file.txt' // Local file path+ // or+ file: 'https://example.com/file.txt' // Remote URL+ }+});++// The SDK automatically:+// 1. Reads the file content+// 2. Uploads it to S3+// 3. Replaces the path with metadata:+// {+// name: string; // The original filename+// mimetype: string; // The file's mime type+// s3key: string; // The S3 key for the uploaded file+// }+```++### File Download++When a tool's output contains an S3 URL and mimetype, the SDK will:++1. Automatically detect file URLs in the response+2. Download the file to a local temporary directory+3. Replace the S3 URL with local file information++Example tool response with file download:++```typescript+// Original response from tool+{+ data: {+ file: {+ s3url: 'https://s3.example.com/file.txt',+ mimetype: 'text/plain'+ }+ }+}++// After auto-download+{+ data: {+ file: {+ uri: '/path/to/local/file.txt',+ file_downloaded: true,+ s3url: 'https://s3.example.com/file.txt',+ mimeType: 'text/plain'+ }+ }+}+```++## Disabling Auto File Handling++You can disable automatic file handling when initializing the SDK:++```typescript+import { Composio } from '@composio/core';++const composio = new Composio({+ apiKey: 'your-api-key',+ autoUploadDownloadFiles: false+});+```++## Manual File Handling++When auto file handling is disabled, you'll need to handle the file operations yourself using the `composio.files` API:++### Manual Upload++When auto-upload is disabled, you need to handle file uploads manually:++```typescript+// Upload file manually+const fileData = await composio.files.upload({+ filePath: '/path/to/file.txt', // Local path or URL+ toolSlug: 'your-tool', // Tool slug+ toolkitSlug: 'your-toolkit' // Toolkit slug+});++// Execute tool with file data+const result = await composio.tools.execute('your-tool', {+ arguments: {+ file: fileData // Contains name, mimetype, and s3key+ }+});+```++### Manual Download++When auto-download is disabled, you'll need to handle file downloads manually:++```typescript+// Execute tool+const result = await composio.tools.execute('your-tool', {+ arguments: {+ // your arguments+ }+});++// Download file manually if response contains S3 URL+if (result.data.file?.s3url) {+ const downloadedFile = await composio.files.download({+ s3Url: result.data.file.s3url,+ toolSlug: 'your-tool',+ mimeType: result.data.file.mimetype || 'application/txt'+ });++ // downloadedFile contains:+ // {+ // name: string; // Generated filename (toolSlug_timestamp.ext)+ // mimeType: string; // The file's mime type+ // s3Url: string; // The original S3 URL+ // filePath: string; // Local path to the downloaded file+ // }+}+```++## File Storage Location++Downloaded files are stored in a temporary directory:++- Location: `~/.composio/files/` (user's home directory)+- Files are named using the pattern: `{toolSlug}_{timestamp}.{extension}`+- The directory is created automatically when needed+- File extensions are derived from the MIME type++## Error Handling++The SDK includes specific error types for file operations:++```typescript+import { ComposioFileUploadError } from '@composio/core';++try {+ await composio.tools.execute('your-tool', {+ arguments: {+ file: '/path/to/file.txt'+ }+ });+} catch (error) {+ if (error instanceof ComposioFileUploadError) {+ console.error('File upload failed:', error.message);+ // Handle file upload error+ // Possible fixes will be included in error.possibleFixes+ }+ throw error;+}+```++## Additional Features++- **URL Support**: The file upload system supports both local file paths and URLs+- **MIME Type Detection**: Automatically detects MIME types from files and URLs+- **Automatic Directory Creation**: Creates necessary directories for file storage+- **Error Recovery**: Provides graceful error handling with helpful error messages+- **MD5 Checksum**: Generates MD5 checksums for file integrity verificationdiff --git a/ts/docs/advanced/telemetry.md b/ts/docs/advanced/telemetry.mdindex d0a7a5979..1ef9fd431 100644--- a/ts/docs/advanced/telemetry.md+++ b/ts/docs/advanced/telemetry.md@@ -219,7 +219,6 @@ interface TelemetryMetadata {source: string; // The runtime environmentversion: string; // The SDK versionisBrowser: boolean; // Whether the SDK is running in a browser- sessionId: string; // A random session ID (changes each init)}```diff --git a/ts/docs/api/composio.md b/ts/docs/api/composio.mdindex 00e8c8dfe..5d3a314ee 100644--- a/ts/docs/api/composio.md+++ b/ts/docs/api/composio.md@@ -11,9 +11,8 @@ const composio = new Composio({apiKey: 'your-api-key',baseURL: 'https://api.composio.dev', // Optional: Custom API endpointallowTracking: true, // Optional: Enable/disable telemetry- allowTracing: true, // Optional: Enable/disable tracing+ autoUploadDownloadFiles: true, // Optional: Enable/disable automatic file handlingprovider: new OpenAIProvider(), // Optional: Custom provider- telemetryTransport: customTransport, // Optional: Custom telemetry transport});```@@ -21,14 +20,13 @@ const composio = new Composio({The `Composio` constructor accepts a configuration object with the following properties:-| Property | Type | Required | Default | Description |-| -------------------- | ------------------------ | -------- | -------------------------- | ---------------------------------------------- |-| `apiKey` | string | Yes | - | Your Composio API key |-| `baseURL` | string | No | `https://api.composio.dev` | The base URL for the Composio API |-| `allowTracking` | boolean | No | `true` | Whether to allow analytics/tracking |-| `allowTracing` | boolean | No | `true` | Whether to allow tracing |-| `provider` | `BaseComposioProvider` | No | `new OpenAIProvider()` | The provider to use for this Composio instance |-| `telemetryTransport` | `BaseTelemetryTransport` | No | - | Custom transport for telemetry data |+| Property | Type | Required | Default | Description |+| ----------------------- | ------------------------ | -------- | -------------------------- | ---------------------------------------------- |+| `apiKey` | string | Yes | - | Your Composio API key |+| `baseURL` | string | No | `https://api.composio.dev` | The base URL for the Composio API |+| `allowTracking` | boolean | No | `true` | Whether to allow analytics/tracking |+| `autoUploadDownloadFiles`| boolean | No | `true` | Whether to automatically handle file operations |+| `provider` | `BaseComposioProvider` | No | `new OpenAIProvider()` | The provider to use for this Composio instance |## Properties@@ -41,8 +39,10 @@ The `Composio` class provides access to the following core models:| `triggers` | `Triggers` | Access to triggers functionality || `authConfigs` | `AuthConfigs` | Access to auth configs functionality || `connectedAccounts` | `ConnectedAccounts` | Access to connected accounts functionality |+| `files` | `Files` | Access to file upload/download functionality|| `provider` | `BaseComposioProvider` | The provider being used |+## Methods### getClient()@@ -92,3 +92,14 @@ const composio = new Composio({allowTracking: false,});```++### Disable Automatic File Handling++```typescript+import { Composio } from '@composio/core';++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+ autoUploadDownloadFiles: false,+});+```diff --git a/ts/examples/tools/src/index.ts b/ts/examples/tools/src/index.tsindex 1a4bcf02c..e2bb271cc 100644--- a/ts/examples/tools/src/index.ts+++ b/ts/examples/tools/src/index.ts@@ -17,8 +17,7 @@ import path from 'path';*/const composio = new Composio({apiKey: process.env.COMPOSIO_API_KEY,- allowTracking: false,- allowTracing: false,+ allowTracking: false});/**@@ -42,6 +41,7 @@ async function main() {});console.log(JSON.stringify(result, null, 2));+} catch (error) {console.error('❌ Error running example:', error);}diff --git a/ts/packages/core/src/composio.ts b/ts/packages/core/src/composio.tsindex 37a3ff449..2b0854ba1 100644--- a/ts/packages/core/src/composio.ts+++ b/ts/packages/core/src/composio.ts@@ -13,10 +13,9 @@ import { COMPOSIO_LOG_LEVEL, IS_DEVELOPMENT_OR_CI } from './utils/constants';import { checkForLatestVersionFromNPM } from './utils/version';import { OpenAIProvider } from './provider/OpenAIProvider';import { version } from '../package.json';-import { getRandomUUID } from './utils/uuid';import type { ComposioRequestHeaders } from './types/composio.types';import { McpServerGetResponse } from './types/mcp.types';-import { getEnvVariable } from './utils/env';+import { Files } from './models/Files';export type ComposioConfig<TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider,@@ -38,11 +37,11 @@ export type ComposioConfig<*/allowTracking?: boolean;/**- * Whether to allow tracing for the Composio instance.+ * Whether to automatically upload and download files during tool execution.* @example true, false* @default true*/- allowTracing?: boolean;+ autoUploadDownloadFiles?: boolean;/*** The tool provider to use for this Composio instance.* @example new OpenAIProvider()@@ -101,6 +100,7 @@ export class Composio<toolkits: Toolkits;triggers: Triggers;provider: TProvider;+ files: Files;// auth configsauthConfigs: AuthConfigs;// connected accounts@@ -118,7 +118,6 @@ export class Composio<* @param {string} [config.apiKey] - The API key for authenticating with the Composio API* @param {string} [config.baseURL] - The base URL for the Composio API (defaults to production URL)* @param {boolean} [config.allowTracking=true] - Whether to allow anonymous usage analytics- * @param {boolean} [config.allowTracing=true] - Whether to allow request tracing for debugging* @param {TProvider} [config.provider] - The provider to use for this Composio instance (defaults to OpenAIProvider)** @example@@ -167,19 +166,21 @@ export class Composio<this.config = {...config,allowTracking: config?.allowTracking ?? true,- allowTracing: config?.allowTracing ?? true,};/*** Set the default provider, if not provided by the user.*/this.provider = (config?.provider ?? new OpenAIProvider()) as TProvider;- this.tools = new Tools(this.client, this.provider);+ this.tools = new Tools(this.client, this.provider, {+ autoUploadDownloadFiles: config?.autoUploadDownloadFiles ?? true,+ });this.mcp = new MCP(this.client, this.provider);this.toolkits = new Toolkits(this.client);this.triggers = new Triggers(this.client);this.authConfigs = new AuthConfigs(this.client);+ this.files = new Files(this.client);// Initialize the connected accounts model.this.connectedAccounts = new ConnectedAccounts(this.client);@@ -196,9 +197,6 @@ export class Composio<isBrowser: typeof window !== 'undefined',provider: this.provider?.name ?? 'openai',host: this.config.host,- // @TODO: Users might want to pass their own session id- // @TODO: We shouldn't be doing this as people might always have one session id throughout the process in server- sessionId: this.config.allowTracing ? getRandomUUID() : undefined, // @TODO: get the session id});}telemetry.instrument(this);diff --git a/ts/packages/core/src/models/Files.ts b/ts/packages/core/src/models/Files.tsnew file mode 100644index 000000000..ff9dd0572--- /dev/null+++ b/ts/packages/core/src/models/Files.ts@@ -0,0 +1,53 @@+import ComposioClient from '@composio/client';+import { FileDownloadData, FileUploadData } from '../types/files.types';+import { downloadFileFromS3, getFileDataAfterUploadingToS3 } from '../utils/fileUtils';+import { telemetry } from '../telemetry/Telemetry';++export class Files {+ constructor(private readonly client: ComposioClient) {+ telemetry.instrument(this);+ }++ /**+ * Upload a file to S3 and return the file data.+ * @param filePath - The path to the file to upload or a URL of the file to upload.+ * @param toolSlug - The slug of the tool that is uploading the file.+ * @param toolkitSlug - The slug of the toolkit that is uploading the file.+ * @returns The file data.+ */+ async upload({+ filePath,+ toolSlug,+ toolkitSlug,+ }: {+ filePath: string;+ toolSlug: string;+ toolkitSlug: string;+ }): Promise<FileUploadData> {+ const fileData = await getFileDataAfterUploadingToS3({+ path: filePath,+ toolSlug,+ toolkitSlug,+ client: this.client,+ });+ return fileData;+ }++ /**+ * Download a file from S3 and return the file data.+ * @param s3key - The S3 key of the file to download.+ * @returns The file data.+ */+ async download({+ toolSlug,+ s3Url,+ mimeType,+ }: {+ s3Url: string;+ toolSlug: string;+ mimeType: string;+ }): Promise<FileDownloadData> {+ const fileDownloadData = await downloadFileFromS3({ toolSlug, s3Url, mimeType });+ return fileDownloadData;+ }+}diff --git a/ts/packages/core/src/models/Tools.ts b/ts/packages/core/src/models/Tools.tsindex d21f5771c..605d8b27c 100644--- a/ts/packages/core/src/models/Tools.ts+++ b/ts/packages/core/src/models/Tools.ts@@ -56,8 +56,13 @@ export class Tools<private client: ComposioClient;private readonly customTools: CustomTools;private provider: TProvider;+ private autoUploadDownloadFiles: boolean;- constructor(client: ComposioClient, provider: TProvider) {+ constructor(+ client: ComposioClient,+ provider: TProvider,+ options?: { autoUploadDownloadFiles: boolean }+ ) {if (!client) {throw new Error('ComposioClient is required');}@@ -68,6 +73,7 @@ export class Tools<this.client = client;this.customTools = new CustomTools(client);this.provider = provider;+ this.autoUploadDownloadFiles = options?.autoUploadDownloadFiles ?? true;// Bind the execute method to ensure correct 'this' contextthis.execute = this.execute.bind(this);// Set the execute method for the provider@@ -227,12 +233,16 @@ export class Tools<* @returns The tools with the default schema modifiers applied*/private async applyDefaultSchemaModifiers(tools: Tool[]): Promise<Tool[]> {- const fileToolModifier = new FileToolModifier(this.client);- return await Promise.all(- tools.map(tool =>- fileToolModifier.modifyToolSchema(tool.slug, tool.toolkit?.slug ?? 'unknown', tool)- )- );+ if (this.autoUploadDownloadFiles) {+ const fileToolModifier = new FileToolModifier(this.client);+ return await Promise.all(+ tools.map(tool =>+ fileToolModifier.modifyToolSchema(tool.slug, tool.toolkit?.slug ?? 'unknown', tool)+ )+ );+ } else {+ return tools;+ }}/**@@ -256,8 +266,17 @@ export class Tools<},modifier?: beforeExecuteModifier): Promise<ToolExecuteParams> {- const fileToolModifier = new FileToolModifier(this.client);let modifiedParams = params;+ // if auto upload download files is enabled, upload the files to the Composio API+ if (this.autoUploadDownloadFiles) {+ const fileToolModifier = new FileToolModifier(this.client);+ modifiedParams = await fileToolModifier.fileUploadModifier(tool, {+ toolSlug,+ toolkitSlug,+ params: modifiedParams,+ });+ }+ // apply the before execute modifiersif (modifier) {if (typeof modifier === 'function') {modifiedParams = await modifier({@@ -269,11 +288,6 @@ export class Tools<throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');}}- modifiedParams = await fileToolModifier.fileUploadModifier(tool, {- toolSlug,- toolkitSlug,- params: modifiedParams,- });return modifiedParams;}@@ -298,8 +312,17 @@ export class Tools<},modifier?: afterExecuteModifier): Promise<ToolExecuteResponse> {- const fileToolModifier = new FileToolModifier(this.client);let modifiedResult = result;+ // if auto upload download files is enabled, download the files from the Composio API+ if (this.autoUploadDownloadFiles) {+ const fileToolModifier = new FileToolModifier(this.client);+ modifiedResult = await fileToolModifier.fileDownloadModifier(tool, {+ toolSlug,+ toolkitSlug,+ result: modifiedResult,+ });+ }+ // apply the after execute modifiersif (modifier) {if (typeof modifier === 'function') {modifiedResult = await modifier({@@ -311,11 +334,7 @@ export class Tools<throw new ComposioInvalidModifierError('Invalid afterExecute modifier. Not a function.');}}- modifiedResult = await fileToolModifier.fileDownloadModifier(tool, {- toolSlug,- toolkitSlug,- result: modifiedResult,- });+return modifiedResult;}diff --git a/ts/packages/core/src/types/files.types.ts b/ts/packages/core/src/types/files.types.tsnew file mode 100644index 000000000..6c2a00041--- /dev/null+++ b/ts/packages/core/src/types/files.types.ts@@ -0,0 +1,12 @@+export type FileUploadData = {+ name: string;+ mimetype: string;+ s3key: string;+};++export type FileDownloadData = {+ name: string;+ mimeType: string;+ s3Url: string;+ filePath: string;+};diff --git a/ts/packages/core/src/types/telemetry.types.ts b/ts/packages/core/src/types/telemetry.types.tsindex be4360c8e..61d298588 100644--- a/ts/packages/core/src/types/telemetry.types.ts+++ b/ts/packages/core/src/types/telemetry.types.ts@@ -41,7 +41,6 @@ export type TelemetryMetadata = {* @example 'openai', 'anthropic', 'google', 'azure', 'composio'*/provider?: string;- sessionId?: string;isBrowser?: boolean;};diff --git a/ts/packages/core/src/utils/fileUtils.ts b/ts/packages/core/src/utils/fileUtils.tsindex 9ef8102eb..e17df9117 100644--- a/ts/packages/core/src/utils/fileUtils.ts+++ b/ts/packages/core/src/utils/fileUtils.ts@@ -3,6 +3,7 @@ import pathModule from 'path';import ComposioClient from '@composio/client';import { COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME } from './constants';import logger from './logger';+import { FileDownloadData, FileUploadData } from '../types/files.types';const readFileContent = async (path: string): Promise<{ content: string; mimeType: string }> => {try {@@ -76,16 +77,17 @@ const uploadFileToS3 = async (return key;};-export const getFileDataAfterUploadingToS3 = async (- path: string,- toolSlug: string,- toolkitSlug: string,- client: ComposioClient-): Promise<{- name: string;- mimetype: string;- s3key: string;-}> => {+export const getFileDataAfterUploadingToS3 = async ({+ path,+ toolSlug,+ toolkitSlug,+ client,+}: {+ path: string;+ toolSlug: string;+ toolkitSlug: string;+ client: ComposioClient;+}): Promise<FileUploadData> => {const isURL = path.startsWith('http');const fileData = isURL ? await readFileContentFromURL(path) : await readFileContent(path);logger.debug(`Uploading file to S3: ${path}`);@@ -115,7 +117,7 @@ export const downloadFileFromS3 = async ({toolSlug: string;s3Url: string;mimeType: string;-}) => {+}): Promise<FileDownloadData> => {const response = await fetch(s3Url);if (!response.ok) {throw new Error(`Failed to download file: ${response.statusText}`);@@ -128,7 +130,7 @@ export const downloadFileFromS3 = async ({return {name: fileName,mimeType: mimeType,- s3Key: s3Url,+ s3Url: s3Url,filePath: filePath,};};diff --git a/ts/packages/core/src/utils/modifiers/FileToolModifier.ts b/ts/packages/core/src/utils/modifiers/FileToolModifier.tsindex f3098f802..3e718d98c 100644--- a/ts/packages/core/src/utils/modifiers/FileToolModifier.ts+++ b/ts/packages/core/src/utils/modifiers/FileToolModifier.ts@@ -92,12 +92,12 @@ export class FileToolModifier {if (toolProperty?.file_uploadable) {logger.debug(`Processing file upload for: ${key}`);try {- const fileData = await getFileDataAfterUploadingToS3(- args[key] as string,- options.toolSlug,- options.toolkitSlug ?? 'unknown',- this.client- );+ const fileData = await getFileDataAfterUploadingToS3({+ path: args[key] as string,+ toolSlug: options.toolSlug,+ toolkitSlug: options.toolkitSlug ?? 'unknown',+ client: this.client,+ });args[key] = fileData;} catch (error) {throw new ComposioFileUploadError(`Failed to upload file: ${key}`, {diff --git a/ts/packages/core/test/tools/fileModifiers.test.ts b/ts/packages/core/test/tools/fileModifiers.test.tsindex f64f21e9c..289e03b49 100644--- a/ts/packages/core/test/tools/fileModifiers.test.ts+++ b/ts/packages/core/test/tools/fileModifiers.test.ts@@ -1,9 +1,15 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { FileToolModifier } from '../../src/utils/modifiers/FileToolModifier';import ComposioClient from '@composio/client';-import { Tool } from '../../src/types/tool.types';+import { Tool, ToolExecuteResponse } from '../../src/types/tool.types';import { ComposioFileUploadError } from '../../src/errors/FileModifierErrors';import * as fileUtils from '../../src/utils/fileUtils';+import { Tools } from '../../src/models/Tools';+import { BaseComposioProvider } from '../../src/provider/BaseProvider';+import { createTestContext, setupTest, mockToolExecution } from '../utils/toolExecuteUtils';+import { mockClient } from '../utils/mocks/client.mock';+import { toolMocks } from '../utils/mocks/data.mock';+import { ToolExecuteResponse as ComposioToolExecuteResponse } from '@composio/client/resources/tools';// Mock the fileUtils modulevi.mock('../../src/utils/fileUtils', () => ({@@ -105,12 +111,12 @@ describe('FileToolModifier', () => {params,});- expect(fileUtils.getFileDataAfterUploadingToS3).toHaveBeenCalledWith(- '/path/to/file.txt',- 'test-tool',- 'test-toolkit',- mockClient- );+ expect(fileUtils.getFileDataAfterUploadingToS3).toHaveBeenCalledWith({+ path: '/path/to/file.txt',+ toolSlug: 'test-tool',+ toolkitSlug: 'test-toolkit',+ client: mockClient,+ });expect(result.arguments?.file).toEqual(mockFileData);expect(result.arguments?.text).toBe('some text');});@@ -149,7 +155,7 @@ describe('FileToolModifier', () => {const mockDownloadResult = {name: 'file.txt',mimeType: 'text/plain',- s3Key: 'downloads/file.txt',+ s3Url: 'downloads/file.txt',filePath: '/downloaded/file.txt',};vi.mocked(fileUtils.downloadFileFromS3).mockResolvedValue(mockDownloadResult);@@ -236,3 +242,199 @@ describe('FileToolModifier', () => {});});});++describe('Tools with autoUploadDownloadFiles', () => {+ const context = createTestContext();+ setupTest(context);++ const mockToolWithFileUpload: Tool = {+ slug: 'COMPOSIO_TOOL',+ name: 'Composio Tool',+ description: 'A test tool',+ tags: ['test'],+ toolkit: {+ slug: 'test-toolkit',+ name: 'Test Toolkit',+ },+ inputParameters: {+ type: 'object' as const,+ properties: {+ file: {+ type: 'string',+ file_uploadable: true,+ },+ },+ additionalProperties: false,+ },+ outputParameters: {+ type: 'object' as const,+ properties: {+ file: {+ type: 'object',+ properties: {+ s3url: {+ type: 'string',+ },+ mimetype: {+ type: 'string',+ },+ },+ },+ },+ additionalProperties: false,+ },+ };++ const mockRawToolWithFileUpload = {+ slug: 'COMPOSIO_TOOL',+ name: 'Composio Tool',+ description: 'A test tool',+ tags: ['test'],+ toolkit: {+ slug: 'test-toolkit',+ name: 'Test Toolkit',+ },+ input_parameters: {+ type: 'object',+ properties: {+ file: {+ type: 'string',+ file_uploadable: true,+ },+ },+ additionalProperties: false,+ },+ output_parameters: {+ type: 'object',+ properties: {+ file: {+ type: 'object',+ properties: {+ s3url: {+ type: 'string',+ },+ mimetype: {+ type: 'string',+ },+ },+ },+ },+ additionalProperties: false,+ },+ };++ describe('when autoUploadDownloadFiles is false', () => {+ beforeEach(async () => {+ context.tools = new Tools(mockClient as unknown as ComposioClient, context.mockProvider, {+ autoUploadDownloadFiles: false,+ });++ // Mock the tool execution+ const { getRawComposioToolBySlugSpy } = await mockToolExecution(context.tools);+ getRawComposioToolBySlugSpy.mockReset();+ getRawComposioToolBySlugSpy.mockResolvedValue(mockToolWithFileUpload);++ // Mock the client's tools.list method+ mockClient.tools.list.mockResolvedValue({+ items: [mockRawToolWithFileUpload],+ totalPages: 1,+ });++ // Mock the file upload and download utilities+ vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockResolvedValue({+ name: 'file.txt',+ mimetype: 'text/plain',+ s3key: 'uploads/file.txt',+ });++ vi.mocked(fileUtils.downloadFileFromS3).mockResolvedValue({+ name: 'file.txt',+ mimeType: 'text/plain',+ s3Url: 'downloads/file.txt',+ filePath: '/path/to/downloaded/file.txt',+ });++ // Mock the provider's wrapTools method+ context.mockProvider.wrapTools.mockImplementation(tools => tools);+ });++ it('should not modify tool schema for file upload', async () => {+ const result = await context.tools.getRawComposioTools({ tools: ['COMPOSIO_TOOL'] });+ expect(result[0].inputParameters?.properties?.file).not.toHaveProperty('format');+ expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();+ });++ it('should not upload files during execution', async () => {+ // Mock getRawComposioToolBySlug for this test+ vi.spyOn(context.tools, 'getRawComposioToolBySlug').mockResolvedValueOnce(+ mockToolWithFileUpload+ );++ await context.tools.execute('COMPOSIO_TOOL', {+ arguments: {+ file: '/path/to/file.txt',+ },+ userId: 'test-user',+ });++ expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();+ expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {+ arguments: {+ file: '/path/to/file.txt',+ },+ allow_tracing: undefined,+ connected_account_id: undefined,+ custom_auth_params: undefined,+ text: undefined,+ user_id: 'test-user',+ version: undefined,+ });+ });++ it('should not download files from execution results', async () => {+ // Mock getRawComposioToolBySlug for this test+ vi.spyOn(context.tools, 'getRawComposioToolBySlug').mockResolvedValueOnce(+ mockToolWithFileUpload+ );++ // Mock the response data structure correctly+ const mockResponse = {+ data: {+ file: {+ s3url: 'https://s3.example.com/file.txt',+ mimetype: 'text/plain',+ },+ },+ error: null,+ successful: true,+ log_id: '123',+ session_info: {},+ };++ // Mock the client's execute method to return the raw response+ mockClient.tools.execute.mockResolvedValueOnce(mockResponse);++ // Mock transformToolExecuteResponse to return the same data structure+ vi.spyOn(context.tools as any, 'transformToolExecuteResponse').mockReturnValue({+ data: mockResponse.data,+ error: mockResponse.error,+ successful: mockResponse.successful,+ logId: mockResponse.log_id,+ sessionInfo: mockResponse.session_info,+ });++ const result = await context.tools.execute('COMPOSIO_TOOL', {+ arguments: {+ file: '/path/to/file.txt',+ },+ userId: 'test-user',+ });++ expect(fileUtils.downloadFileFromS3).not.toHaveBeenCalled();+ expect(result.data.file).toEqual({+ s3url: 'https://s3.example.com/file.txt',+ mimetype: 'text/plain',+ });+ });+ });+});