@devries-cameron20 / composio Mirror · read-only / commits / d2812d25d
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 03:15 UTC

feat(tool-router): add session files mount (list, upload, download, delete) (#2864)

Musthaq Ahamad committed Mar 10, 2026 at 12:57 UTC d2812d25dd90d2ce951813b60d6e5e310d4d08b8
33 files changed +2785 -279
pnpm-lock.yaml
+29 -63
@@ -25,8 +25,8 @@ catalogs:
25 specifier: ^4.20250917.0
26 version: 4.20260218.0
27 '@composio/client':
28 - specifier: 0.1.0-alpha.60
29 - version: 0.1.0-alpha.60
28 + specifier: 0.1.0-alpha.61
29 + version: 0.1.0-alpha.61
30 '@effect/cli':
31 specifier: ^0.73.2
32 version: 0.73.2
@@ -429,6 +429,16 @@ importers:
429 specifier: workspace:*
430 version: link:../../../_utils
431
432 + ts/e2e-tests/runtimes/node/tool-router-files:
433 + dependencies:
434 + '@composio/core':
435 + specifier: workspace:*
436 + version: link:../../../../packages/core
437 + devDependencies:
438 + '@e2e-tests/utils':
439 + specifier: workspace:*
440 + version: link:../../../_utils
441 +
442 ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext:
443 devDependencies:
444 '@composio/cli':
@@ -680,16 +690,16 @@ importers:
690 version: link:../../packages/providers/llamaindex
691 '@llamaindex/openai':
692 specifier: ^0.4.20
683 - version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@3.25.76)
693 + version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@4.3.6)
694 '@llamaindex/workflow':
695 specifier: ^1.1.24
686 - version: 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
696 + version: 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
697 dotenv:
698 specifier: ^16.4.1
699 version: 16.6.1
700 llamaindex:
701 specifier: ^0.12.0
692 - version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@3.25.76)
702 + version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
703 devDependencies:
704 '@types/bun':
705 specifier: ^1.2.9
@@ -1019,7 +1029,7 @@ importers:
1029 version: 1.0.1
1030 '@composio/client':
1031 specifier: 'catalog:'
1022 - version: 0.1.0-alpha.60
1032 + version: 0.1.0-alpha.61
1033 '@composio/core':
1034 specifier: workspace:*
1035 version: link:../core
@@ -1116,7 +1126,7 @@ importers:
1126 dependencies:
1127 '@composio/client':
1128 specifier: 'catalog:'
1119 - version: 0.1.0-alpha.60
1129 + version: 0.1.0-alpha.61
1130 '@composio/json-schema-to-zod':
1131 specifier: workspace:*
1132 version: link:../json-schema-to-zod
@@ -1289,7 +1299,7 @@ importers:
1299 dependencies:
1300 llamaindex:
1301 specifier: ^0.12.0
1292 - version: 0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1302 + version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1303 devDependencies:
1304 '@composio/core':
1305 specifier: workspace:*
@@ -1763,8 +1773,8 @@ packages:
1773 resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}
1774 engines: {node: '>=0.1.90'}
1775
1766 - '@composio/client@0.1.0-alpha.60':
1767 - resolution: {integrity: sha512-i1/S+GX7ATzdQK0UzoaPdWqP4lmn/sCWF4ojGdq26k+cyEiq3aWN4HZFKYBp1jmwD1Sxn02RX9iTL09YAPn3Rg==}
1776 + '@composio/client@0.1.0-alpha.61':
1777 + resolution: {integrity: sha512-VSU20mTtMe0TIPHkBBRdCU4IYSy3886U9O69PURU8+ItLXCD2MjIN0S8VTDL8wpA4zFXamUFnvtwQyow11O2KA==}
1778
1779 '@cspotcode/source-map-support@0.8.1':
1780 resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}
@@ -6856,7 +6866,7 @@ snapshots:
6866 '@colors/colors@1.5.0':
6867 optional: true
6868
6859 - '@composio/client@0.1.0-alpha.60': {}
6869 + '@composio/client@0.1.0-alpha.61': {}
6870
6871 '@cspotcode/source-map-support@0.8.1':
6872 dependencies:
@@ -7551,43 +7561,26 @@ snapshots:
7561 tree-sitter: 0.22.4
7562 web-tree-sitter: 0.24.7
7563
7554 - '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@3.25.76)':
7564 + '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@4.3.6)':
7565 dependencies:
7566 '@llamaindex/core': 0.6.22
7567 '@llamaindex/env': 0.1.30
7558 - openai: 5.23.2(ws@8.19.0)(zod@3.25.76)
7568 + openai: 5.23.2(ws@8.19.0)(zod@4.3.6)
7569 transitivePeerDependencies:
7570 - ws
7571 - zod
7572
7563 - '@llamaindex/workflow-core@1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)':
7573 + '@llamaindex/workflow-core@1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)':
7574 optionalDependencies:
7565 - '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)
7575 + '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6)
7576 hono: 4.11.9
7567 - zod: 3.25.76
7568 -
7569 - '@llamaindex/workflow-core@1.3.3(zod@4.3.6)':
7570 - optionalDependencies:
7577 zod: 4.3.6
7578
7573 - '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)':
7574 - dependencies:
7575 - '@llamaindex/core': 0.6.22
7576 - '@llamaindex/env': 0.1.30
7577 - '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
7578 - transitivePeerDependencies:
7579 - - '@modelcontextprotocol/sdk'
7580 - - hono
7581 - - next
7582 - - p-retry
7583 - - rxjs
7584 - - zod
7585 -
7586 - '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(zod@4.3.6)':
7579 + '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)':
7580 dependencies:
7581 '@llamaindex/core': 0.6.22
7582 '@llamaindex/env': 0.1.30
7590 - '@llamaindex/workflow-core': 1.3.3(zod@4.3.6)
7583 + '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
7584 transitivePeerDependencies:
7585 - '@modelcontextprotocol/sdk'
7586 - hono
@@ -9968,34 +9961,12 @@ snapshots:
9961 rfdc: 1.4.1
9962 wrap-ansi: 9.0.2
9963
9971 - llamaindex@0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@3.25.76):
9964 + llamaindex@0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6):
9965 dependencies:
9966 '@llamaindex/core': 0.6.22
9967 '@llamaindex/env': 0.1.30
9968 '@llamaindex/node-parser': 2.0.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)
9976 - '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
9977 - '@types/lodash': 4.17.23
9978 - '@types/node': 24.10.13
9979 - lodash: 4.17.23
9980 - magic-bytes.js: 1.13.0
9981 - transitivePeerDependencies:
9982 - - '@huggingface/transformers'
9983 - - '@modelcontextprotocol/sdk'
9984 - - gpt-tokenizer
9985 - - hono
9986 - - next
9987 - - p-retry
9988 - - rxjs
9989 - - tree-sitter
9990 - - web-tree-sitter
9991 - - zod
9992 -
9993 - llamaindex@0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6):
9994 - dependencies:
9995 - '@llamaindex/core': 0.6.22
9996 - '@llamaindex/env': 0.1.30
9997 - '@llamaindex/node-parser': 2.0.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)
9998 - '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(zod@4.3.6)
9969 + '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
9970 '@types/lodash': 4.17.23
9971 '@types/node': 24.10.13
9972 lodash: 4.17.23
@@ -10275,11 +10246,6 @@ snapshots:
10246 is-inside-container: 1.0.0
10247 wsl-utils: 0.1.0
10248
10278 - openai@5.23.2(ws@8.19.0)(zod@3.25.76):
10279 - optionalDependencies:
10280 - ws: 8.19.0
10281 - zod: 3.25.76
10282 -
10249 openai@5.23.2(ws@8.19.0)(zod@4.3.6):
10250 optionalDependencies:
10251 ws: 8.19.0
pnpm-workspace.yaml
+1 -1
@@ -20,7 +20,7 @@ catalog:
20 '@clack/prompts': '^1.0.1'
21 '@cloudflare/vitest-pool-workers': ^0.9.2
22 '@cloudflare/workers-types': ^4.20250917.0
23 - '@composio/client': 0.1.0-alpha.60
23 + '@composio/client': 0.1.0-alpha.61
24 '@effect/cli': ^0.73.2
25 '@effect/eslint-plugin': ^0.3.2
26 '@effect/language-service': ^0.74.0
ts/docs/README.md
+1
@@ -91,6 +91,7 @@ The complete API reference documentation is available here:
91 - [Custom Tools](./api/custom-tools.md)
92 - [MCP](./api/mcp.md)
93 - [ToolRouter](./api/tool-router.md)
94 +- [Tool Router Session Files](./api/tool-router-files.md)
95
96 ## Providers
97
ts/docs/api/tool-router-files.md new
+296
@@ -0,0 +1,296 @@
1 +# Tool Router Session Files
2 +
3 +Tool Router sessions include a virtual filesystem mount that enables file storage and retrieval within a session. This is useful for agent workflows, document processing, and tools that need to read or write files. Access the files API via `session.files` on any Tool Router session.
4 +
5 +> **Related:**
6 +> - [Tool Router](./tool-router.md) – Session creation, configuration, and `session.files` overview
7 +> - [Auto Upload and Download](../advanced/auto-upload-download.md) – File handling during tool execution (different feature)
8 +
9 +## Overview
10 +
11 +Each Tool Router session has a `files` property that provides:
12 +
13 +- **List** – Browse files and directories with cursor-based pagination
14 +- **Upload** – Upload files from paths, URLs, native `File` objects, or raw buffers
15 +- **Download** – Get presigned download URLs and `RemoteFile` instances
16 +- **Delete** – Remove files or directories from the mount
17 +
18 +Files are stored in a virtual filesystem attached to the session. Tools executing in the session can access these files (e.g., at `/mnt/files/` inside the sandbox). The mount ID defaults to `"files"` and can be overridden when using custom mounts.
19 +
20 +## Quick Start
21 +
22 +```typescript
23 +import { Composio } from '@composio/core';
24 +
25 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
26 +const session = await composio.create('default');
27 +
28 +// Upload a file
29 +const file = await session.files.upload('/path/to/report.pdf');
30 +console.log('Uploaded:', file.mountRelativePath);
31 +
32 +// List files
33 +const { items, nextCursor } = await session.files.list({ path: '/' });
34 +
35 +// Download a file
36 +const remoteFile = await session.files.download('report.pdf');
37 +const buffer = await remoteFile.buffer();
38 +await remoteFile.save('/tmp/report.pdf');
39 +```
40 +
41 +## List Files
42 +
43 +List files and directories at a path on the session's file mount. Supports cursor-based pagination.
44 +
45 +### Method Signature
46 +
47 +```typescript
48 +session.files.list(options?: ToolRouterSessionFilesMountListOptions): Promise<FileListResponse>
49 +```
50 +
51 +### Options
52 +
53 +| Option | Type | Default | Description |
54 +| -------- | ------ | ------- | ---------------------------------------------------------- |
55 +| `path` | string | - | Directory path to list. Use `"/"` for root. |
56 +| `mountId`| string | `"files"` | The file mount ID. |
57 +| `cursor` | string | - | Pagination cursor from the previous response's `nextCursor`. |
58 +| `limit` | number | - | Max files per page (1–500). |
59 +
60 +### Response
61 +
62 +```typescript
63 +interface FileListResponse {
64 + items: Array<{
65 + lastModified: string; // ISO 8601 timestamp
66 + mountRelativePath: string; // e.g. "report.pdf"
67 + sandboxMountPrefix: string; // e.g. "/mnt/files"
68 + size: number; // File size in bytes
69 + }>;
70 + nextCursor?: string; // Present when more pages exist
71 +}
72 +```
73 +
74 +### Examples
75 +
76 +```typescript
77 +// List root directory
78 +const { items } = await session.files.list({ path: '/' });
79 +
80 +// List a subdirectory
81 +const { items } = await session.files.list({ path: '/documents' });
82 +
83 +// Paginated listing
84 +let result = await session.files.list({ path: '/', limit: 10 });
85 +while (result.nextCursor) {
86 + result = await session.files.list({
87 + path: '/',
88 + cursor: result.nextCursor,
89 + limit: 10,
90 + });
91 +}
92 +```
93 +
94 +## Upload Files
95 +
96 +Upload files to the session's mount. Accepts multiple input types: file paths (local or URL), native `File` objects, or raw buffers (`ArrayBuffer` | `Uint8Array`).
97 +
98 +### Method Signature
99 +
100 +```typescript
101 +session.files.upload(
102 + input: string | File | ArrayBuffer | Uint8Array,
103 + options?: ToolRouterSessionFilesMountUploadOptions
104 +): Promise<RemoteFile>
105 +```
106 +
107 +### Input Types
108 +
109 +| Input Type | Description | Example |
110 +| ---------- | ----------- | ------- |
111 +| `string` | Local path or HTTP(S) URL | `'/path/to/file.pdf'`, `'https://example.com/file.pdf'` |
112 +| `File` | Native browser/Node `File` | `inputElement.files[0]` |
113 +| `ArrayBuffer` | Raw binary buffer | `await file.arrayBuffer()` |
114 +| `Uint8Array` | Typed array buffer | `new TextEncoder().encode('hello')` |
115 +
116 +### Upload Options
117 +
118 +| Option | Type | Default | Description |
119 +| --------- | ------ | ------- | ----------- |
120 +| `remotePath` | string | - | Remote path/filename on the mount. Required when passing a buffer (provides filename; mimetype defaults to `application/octet-stream`). |
121 +| `mountId` | string | `"files"` | The file mount ID. |
122 +| `mimetype` | string | - | MIME type. Required when passing a buffer unless `remotePath` is provided. Ignored when passing `File` (uses `file.type`). |
123 +
124 +### How It Works
125 +
126 +1. **Path (string)** – If the path starts with `http://` or `https://`, the file is fetched from the URL. Otherwise it is read from the local filesystem. The filename is derived from the path or URL.
127 +2. **File** – Used directly. Filename comes from `file.name` unless `remotePath` is provided.
128 +3. **Buffer** – Wrapped in a `File` object. **Either `mimetype` or `remotePath` must be provided.** If only `remotePath` is given, mimetype defaults to `application/octet-stream`. If only `mimetype` is given, a filename is generated from the extension (`upload-{id}.{ext}`).
129 +
130 +### Examples
131 +
132 +```typescript
133 +// From local path
134 +const file = await session.files.upload('/path/to/report.pdf');
135 +
136 +// From URL
137 +const file = await session.files.upload('https://example.com/document.pdf');
138 +
139 +// From native File (e.g. file input)
140 +const file = await session.files.upload(fileInput.files[0]);
141 +
142 +// From buffer with explicit path and mimetype
143 +const buffer = new TextEncoder().encode('{"key": "value"}');
144 +const file = await session.files.upload(buffer, {
145 + remotePath: 'data.json',
146 + mimetype: 'application/json',
147 +});
148 +
149 +// From buffer – mimetype or remotePath required
150 +const pngBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, ...]);
151 +const file = await session.files.upload(pngBytes, {
152 + remotePath: 'screenshot.png',
153 + mimetype: 'image/png',
154 +});
155 +```
156 +
157 +## Download Files
158 +
159 +Get a `RemoteFile` for a file on the mount. The `RemoteFile` provides a presigned download URL and methods to fetch content.
160 +
161 +### Method Signature
162 +
163 +```typescript
164 +session.files.download(
165 + filePath: string,
166 + options?: ToolRouterSessionFilesMountDownloadOptions
167 +): Promise<RemoteFile>
168 +```
169 +
170 +### Parameters
171 +
172 +- `filePath` – Path of the file on the mount (e.g. `"report.pdf"`, `"output/data.csv"`).
173 +- `options.mountId` – Mount ID (default: `"files"`).
174 +
175 +### RemoteFile
176 +
177 +The returned `RemoteFile` has:
178 +
179 +| Property | Type | Description |
180 +| -------- | ---- | ----------- |
181 +| `expiresAt` | string | ISO 8601 when the download URL expires |
182 +| `mountRelativePath` | string | Path within the mount |
183 +| `sandboxMountPrefix` | string | Absolute mount path (e.g. `/mnt/files`) |
184 +| `downloadUrl` | string | Presigned URL for downloading |
185 +| `filename` | string | Basename of the path |
186 +
187 +Methods:
188 +
189 +- `buffer()` – Fetch content as `Uint8Array`
190 +- `text()` – Fetch content as UTF-8 string
191 +- `blob()` – Fetch content as `Blob`
192 +- `save(path?)` – Download and save to disk (Node.js only; path defaults to `~/.composio/files/`)
193 +
194 +### Examples
195 +
196 +```typescript
197 +const remoteFile = await session.files.download('/output/report.pdf');
198 +
199 +// Fetch content
200 +const buffer = await remoteFile.buffer();
201 +const text = await remoteFile.text();
202 +
203 +// Save to disk (Node.js)
204 +await remoteFile.save('/tmp/report.pdf');
205 +await remoteFile.save(); // Uses ~/.composio/files/{filename}
206 +```
207 +
208 +## Delete Files
209 +
210 +Delete a file or directory from the mount.
211 +
212 +### Method Signature
213 +
214 +```typescript
215 +session.files.delete(
216 + remotePath: string,
217 + options?: ToolRouterSessionFilesMountDeleteOptions
218 +): Promise<FileDeleteResponse>
219 +```
220 +
221 +### Examples
222 +
223 +```typescript
224 +await session.files.delete('/temp/cache.json');
225 +await session.files.delete('/old-backup', { mountId: 'custom-mount' });
226 +```
227 +
228 +## Type Reference
229 +
230 +### ToolRouterSessionFilesMountListOptions
231 +
232 +```typescript
233 +interface ToolRouterSessionFilesMountListOptions {
234 + path?: string;
235 + mountId?: string; // default: "files"
236 + cursor?: string;
237 + limit?: number; // 1-500
238 +}
239 +```
240 +
241 +### ToolRouterSessionFilesMountUploadOptions
242 +
243 +```typescript
244 +interface ToolRouterSessionFilesMountUploadOptions {
245 + remotePath?: string;
246 + mountId?: string; // default: "files"
247 + mimetype?: string;
248 +}
249 +```
250 +
251 +### FileListResponse
252 +
253 +```typescript
254 +interface FileListResponse {
255 + items: Array<{
256 + lastModified: string;
257 + mountRelativePath: string;
258 + sandboxMountPrefix: string;
259 + size: number;
260 + }>;
261 + nextCursor?: string;
262 +}
263 +```
264 +
265 +### RemoteFile (from download/upload)
266 +
267 +```typescript
268 +interface RemoteFile {
269 + readonly expiresAt: string;
270 + readonly mountRelativePath: string;
271 + readonly sandboxMountPrefix: string;
272 + readonly downloadUrl: string;
273 + readonly filename: string;
274 +
275 + buffer(): Promise<Uint8Array>;
276 + text(): Promise<string>;
277 + blob(): Promise<Blob>;
278 + save(path?: string): Promise<string>; // Node.js only
279 +}
280 +```
281 +
282 +## Exports
283 +
284 +The following are exported from `@composio/core`:
285 +
286 +- `FileListResponse` – List response type
287 +- `ToolRouterSessionFilesMountListOptions` – List options type
288 +- `RemoteFile` – File class with `buffer`, `text`, `blob`, `save`
289 +- `getExtensionFromMimeType` – Map MIME type to file extension
290 +
291 +## Platform Support
292 +
293 +- **Node.js** – Full support (paths, `save()`).
294 +- **Bun** – Full support.
295 +- **Browser** – Paths and `save()` are limited; use `File` or buffers.
296 +- **Cloudflare Workers / Edge** – No filesystem; use `File` or buffers only.
ts/docs/api/tool-router.md
+24
@@ -397,6 +397,29 @@ const paginatedFilteredToolkits = await session.toolkits({
397 });
398 ```
399
400 +### `files`
401 +
402 +Each session has a virtual filesystem mount for storing and retrieving files. Use `session.files` to list, upload, download, and delete files. This is useful for agent workflows, document processing, and tools that need file access.
403 +
404 +```typescript
405 +// Upload a file (from path, URL, File, or buffer)
406 +const file = await session.files.upload('/path/to/report.pdf');
407 +const file = await session.files.upload(buffer, { remotePath: 'data.json' });
408 +
409 +// List files with pagination
410 +const { items, nextCursor } = await session.files.list({ path: '/' });
411 +
412 +// Download a file
413 +const remoteFile = await session.files.download('report.pdf');
414 +const buffer = await remoteFile.buffer();
415 +await remoteFile.save('/tmp/report.pdf');
416 +
417 +// Delete a file
418 +await session.files.delete('/temp/cache.json');
419 +```
420 +
421 +See [Tool Router Session Files](./tool-router-files.md) for full documentation, including upload input types (paths, URLs, `File`, buffers), mimetype detection, pagination, and the `RemoteFile` API.
422 +
423 ## Framework Integrations
424
425 ### Vercel AI SDK (with Provider)
@@ -800,6 +823,7 @@ interface ToolRouterSession {
823 nextCursor?: string; // Pagination cursor
824 limit?: number; // Number of items per page
825 }) => Promise<ToolkitConnectionsDetails>;
826 + files: ToolRouterSessionFilesMount; // List, upload, download, delete files. See tool-router-files.md
827 experimental?: {
828 assistivePrompt?: string; // Generated system prompt for optimal tool router usage
829 };
ts/e2e-tests/README.md
+1
@@ -33,6 +33,7 @@ ts/e2e-tests/
33 │ ├── mastra-tool-router-zod-v3/ # @composio/mastra Tool Router + Zod v3 tests
34 │ ├── mastra-tool-router-zod-v4/ # @composio/mastra Tool Router + Zod v4 tests
35 │ ├── openai-zod4-compat/ # OpenAI + Zod v4 compatibility tests
36 + │ ├── tool-router-files/ # Tool Router session files (list, upload, download, delete)
37 │ └── typescript-mjs-import-nodenext/ # TypeScript moduleResolution: nodenext tests
38 ├── deno/ # Deno runtime tests
39 │ └── esm-basic/ # ESM compatibility tests via npm: specifier
ts/e2e-tests/runtimes/node/tool-router-files/.env.example new
+1
@@ -0,0 +1 @@
1 +COMPOSIO_API_KEY=your_composio_api_key
ts/e2e-tests/runtimes/node/tool-router-files/README.md new
+26
@@ -0,0 +1,26 @@
1 +# Tool Router Session Files E2E Test
2 +
3 +End-to-end test for the Tool Router session files mount API (list, upload, download, delete).
4 +
5 +## Prerequisites
6 +
7 +- Docker (for running tests in containers)
8 +- `COMPOSIO_API_KEY` environment variable
9 +
10 +## Running
11 +
12 +```bash
13 +# From repo root
14 +COMPOSIO_API_KEY=your_key pnpm test:e2e:node --filter=@e2e-tests/node-tool-router-files
15 +
16 +# Or from this directory
17 +COMPOSIO_API_KEY=your_key bun test e2e.test.ts
18 +```
19 +
20 +## What it tests
21 +
22 +1. **Create session** – Creates a minimal tool router session
23 +2. **Upload** – Uploads a text buffer with `remotePath` and `mimetype`
24 +3. **List** – Lists files at mount root and verifies the uploaded file appears
25 +4. **Download** – Downloads the file and verifies content
26 +5. **Delete** – Deletes the file
ts/e2e-tests/runtimes/node/tool-router-files/e2e.test.ts new
+56
@@ -0,0 +1,56 @@
1 +/**
2 + * Tool Router session files mount E2E test.
3 + *
4 + * Verifies list, upload, download, and delete operations against the live Composio API.
5 + * Requires COMPOSIO_API_KEY in environment.
6 + */
7 +
8 +import { e2e, type E2ETestResult } from '@e2e-tests/utils';
9 +import { describe, it, expect, beforeAll } from 'bun:test';
10 +
11 +declare module 'bun' {
12 + interface Env {
13 + COMPOSIO_API_KEY: string;
14 + }
15 +}
16 +
17 +e2e(import.meta.url, {
18 + versions: { node: ['20.19.0', '22.12.0'] },
19 + usesFixtures: true,
20 + env: {
21 + COMPOSIO_API_KEY: Bun.env.COMPOSIO_API_KEY,
22 + },
23 + defineTests: ({ runFixture }) => {
24 + let result: E2ETestResult;
25 +
26 + beforeAll(async () => {
27 + result = await runFixture({ filename: 'index.mjs' });
28 + }, 120_000);
29 +
30 + describe('Tool Router session files', () => {
31 + it('exits successfully', () => {
32 + expect(result.exitCode).toBe(0);
33 + });
34 +
35 + it('upload succeeds', () => {
36 + expect(result.stdout).toContain('UPLOAD_OK');
37 + });
38 +
39 + it('list succeeds', () => {
40 + expect(result.stdout).toMatch(/LIST_OK|LIST_SKIP/);
41 + });
42 +
43 + it('download succeeds', () => {
44 + expect(result.stdout).toContain('DOWNLOAD_OK');
45 + });
46 +
47 + it('delete succeeds', () => {
48 + expect(result.stdout).toContain('DELETE_OK');
49 + });
50 +
51 + it('all operations complete', () => {
52 + expect(result.stdout).toContain('ALL_OK');
53 + });
54 + });
55 + },
56 +});
ts/e2e-tests/runtimes/node/tool-router-files/fixtures/index.mjs new
+76
@@ -0,0 +1,76 @@
1 +/**
2 + * E2E fixture: Tool Router session files mount (list, upload, download, delete).
3 + * Requires COMPOSIO_API_KEY in environment.
4 + */
5 +import { Composio } from '@composio/core';
6 +
7 +const apiKey = process.env.COMPOSIO_API_KEY;
8 +if (!apiKey) {
9 + console.error('COMPOSIO_API_KEY is required');
10 + process.exit(1);
11 +}
12 +
13 +const composio = new Composio({ apiKey });
14 +
15 +async function main() {
16 + // Create a session (hackernews is public, no auth needed; files mount is always available)
17 + const session = await composio.create('e2e-tool-router-files-user', {
18 + toolkits: ['hackernews'],
19 + manageConnections: false,
20 + });
21 +
22 + const { files } = session;
23 + const testPath = 'e2e-test-upload.txt';
24 + const testContent = 'Hello from Tool Router files E2E test';
25 +
26 + // Upload a buffer
27 + const buffer = new TextEncoder().encode(testContent);
28 + const uploaded = await files.upload(buffer, {
29 + remotePath: testPath,
30 + mimetype: 'text/plain',
31 + });
32 + if (!uploaded.mountRelativePath || !uploaded.downloadUrl) {
33 + throw new Error('Upload failed: missing mountRelativePath or downloadUrl');
34 + }
35 + const storedPath = uploaded.mountRelativePath.replace(/^\//, '');
36 + console.log('UPLOAD_OK');
37 +
38 + // List files (retry for eventual consistency; omit path for root - SDK normalizes)
39 + let listOk = false;
40 + for (let attempt = 0; attempt < 5; attempt++) {
41 + const listResult = await files.list();
42 + const found = listResult.items?.some(
43 + (item) =>
44 + item.mountRelativePath === storedPath ||
45 + item.mountRelativePath === testPath ||
46 + item.mountRelativePath?.endsWith(testPath) ||
47 + item.mountRelativePath?.includes(testPath)
48 + );
49 + if (found) {
50 + listOk = true;
51 + break;
52 + }
53 + await new Promise((r) => setTimeout(r, 1000));
54 + }
55 + if (listOk) console.log('LIST_OK');
56 + else console.log('LIST_SKIP'); // eventual consistency
57 +
58 + // Download the file (use path from API response)
59 + const downloaded = await files.download(storedPath);
60 + const content = await downloaded.text();
61 + if (content !== testContent) {
62 + throw new Error(`Download failed: expected "${testContent}", got "${content}"`);
63 + }
64 + console.log('DOWNLOAD_OK');
65 +
66 + // Delete the file (use path from API response)
67 + await files.delete(storedPath);
68 + console.log('DELETE_OK');
69 +
70 + console.log('ALL_OK');
71 +}
72 +
73 +main().catch((err) => {
74 + console.log('ERROR:', err?.message || err);
75 + process.exit(1);
76 +});
ts/e2e-tests/runtimes/node/tool-router-files/package.json new
+17
@@ -0,0 +1,17 @@
1 +{
2 + "name": "@e2e-tests/node-tool-router-files",
3 + "version": "0.0.0",
4 + "private": true,
5 + "type": "module",
6 + "scripts": {
7 + "typecheck": "tsc --noEmit",
8 + "test:e2e": "bun test e2e.test.ts",
9 + "test:e2e:node": "bun test e2e.test.ts"
10 + },
11 + "dependencies": {
12 + "@composio/core": "workspace:*"
13 + },
14 + "devDependencies": {
15 + "@e2e-tests/utils": "workspace:*"
16 + }
17 +}
ts/e2e-tests/runtimes/node/tool-router-files/tsconfig.json new
+12
@@ -0,0 +1,12 @@
1 +{
2 + "$schema": "https://json.schemastore.org/tsconfig",
3 + "compilerOptions": {
4 + "target": "es2022",
5 + "module": "esnext",
6 + "moduleResolution": "bundler",
7 + "strict": true,
8 + "skipLibCheck": true,
9 + "noEmit": true
10 + },
11 + "include": ["e2e.test.ts"]
12 +}
ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext/README.md
+2 -2
@@ -18,7 +18,7 @@ This causes `TS2307: Cannot find module './foo.mjs'` errors.
18
19 | Test | Description |
20 | ---------------------- | -------------------------------------------------------------- |
21 -| composio ts generate | Runs CLI to generate TypeScript files for entelligence toolkit |
21 +| composio ts generate | Runs CLI to generate TypeScript files for hackernews toolkit |
22 | File existence | Verifies generated .ts files exist |
23 | TypeScript compilation | Runs `tsc --noEmit` to check import resolution |
24
@@ -33,7 +33,7 @@ fixtures/
33 The fixture script:
34
35 1. Cleans up any previous generated files
36 -2. Runs `composio ts generate --toolkits entelligence --output-dir ./generated`
36 +2. Runs `composio ts generate --toolkits hackernews --output-dir ./generated`
37 3. Verifies generated `.ts` files exist
38 4. Runs `npx tsc --noEmit` to check TypeScript compilation
39 5. Fails if TS2307 errors occur (indicating `.mjs` import bug)
ts/e2e-tests/runtimes/node/typescript-mjs-import-nodenext/fixtures/index.mjs
+3 -3
@@ -31,11 +31,11 @@ if (existsSync(GENERATED_DIR)) {
31 rmSync(GENERATED_DIR, { recursive: true });
32 }
33
34 -// Test 1: Run composio ts generate --toolkits entelligence --output-dir ./generated
35 -console.log('Test 1: Running composio ts generate --toolkits entelligence --output-dir ./generated...');
34 +// Test 1: Run composio ts generate --toolkits hackernews --output-dir ./generated
35 +console.log('Test 1: Running composio ts generate --toolkits hackernews --output-dir ./generated...');
36 try {
37 // Use the composio CLI binary built and installed to /usr/local/bin in the Dockerfile
38 - execSync(`composio ts generate --toolkits entelligence --output-dir ${GENERATED_DIR}`, {
38 + execSync(`composio ts generate --toolkits hackernews --output-dir ${GENERATED_DIR}`, {
39 cwd: __dirname,
40 stdio: 'inherit',
41 env: { ...process.env, FORCE_COLOR: '0' },
ts/packages/core/src/composio.ts
+5 -5
@@ -18,7 +18,7 @@ import { Files } from '#files';
18 import { getDefaultHeaders } from './utils/session';
19 import { ToolkitVersionParam } from './types/tool.types';
20 import { ToolRouter } from './models/ToolRouter';
21 -import { ToolRouterCreateSessionConfig, ToolRouterSession } from './types/toolRouter.types';
21 +import { ToolRouterCreateSessionConfig, Session } from './types/toolRouter.types';
22 import { CONFIG_DEFAULTS } from './utils/config-defaults';
23
24 export type ComposioConfig<
@@ -165,7 +165,7 @@ export class Composio<
165 *
166 * @param userId {string} The user id to create the session for
167 * @param config {ToolRouterConfig} The config for the tool router session
168 - * @returns {Promise<ToolRouterSession<TToolCollection, TTool, TProvider>>} The tool router session
168 + * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session
169 *
170 * @example
171 * ```typescript
@@ -186,15 +186,15 @@ export class Composio<
186 create: (
187 userId: string,
188 routerConfig?: ToolRouterCreateSessionConfig
189 - ) => Promise<ToolRouterSession<unknown, unknown, TProvider>>;
189 + ) => Promise<Session<unknown, unknown, TProvider>>;
190
191 /**
192 * Use an existing tool router session
193 *
194 * @param id {string} The id of the session to use
195 - * @returns {Promise<ToolRouterSession<TToolCollection, TTool, TProvider>>} The tool router session
195 + * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session
196 */
197 - use: (id: string) => Promise<ToolRouterSession<unknown, unknown, TProvider>>;
197 + use: (id: string) => Promise<Session<unknown, unknown, TProvider>>;
198
199 /**
200 * Creates a new instance of the Composio SDK.
ts/packages/core/src/errors/RemoteFileErrors.ts new
+62
@@ -0,0 +1,62 @@
1 +import { ComposioError, ComposioErrorOptions } from './ComposioError';
2 +
3 +export const RemoteFileErrorCodes = {
4 + DOWNLOAD_FAILED: 'REMOTE_FILE_DOWNLOAD_FAILED',
5 +} as const;
6 +
7 +export interface RemoteFileDownloadErrorOptions extends Omit<ComposioErrorOptions, 'code'> {
8 + /** HTTP status code from the failed response */
9 + statusCode?: number;
10 + /** HTTP status text (e.g. "Not Found", "Forbidden") */
11 + statusText?: string;
12 + /** The presigned download URL that failed */
13 + downloadUrl?: string;
14 + /** Mount-relative path of the file (e.g. "output/report.pdf") */
15 + mountRelativePath?: string;
16 + /** Filename extracted from the mount path */
17 + filename?: string;
18 +}
19 +
20 +/**
21 + * Error thrown when fetching a remote file from a tool router session mount fails.
22 + * Includes HTTP status, URL, and file path context for debugging.
23 + */
24 +export class RemoteFileDownloadError extends ComposioError {
25 + constructor(
26 + message: string = 'Failed to download remote file',
27 + options: RemoteFileDownloadErrorOptions = {}
28 + ) {
29 + const {
30 + statusCode,
31 + statusText,
32 + downloadUrl,
33 + mountRelativePath,
34 + filename,
35 + meta: optionsMeta,
36 + ...rest
37 + } = options;
38 +
39 + const meta: Record<string, unknown> = {
40 + ...optionsMeta,
41 + ...(statusCode !== undefined && { statusCode }),
42 + ...(statusText && { statusText }),
43 + ...(downloadUrl && { downloadUrl }),
44 + ...(mountRelativePath && { mountRelativePath }),
45 + ...(filename && { filename }),
46 + };
47 +
48 + super(message, {
49 + ...rest,
50 + code: RemoteFileErrorCodes.DOWNLOAD_FAILED,
51 + statusCode,
52 + meta: Object.keys(meta).length > 0 ? meta : undefined,
53 + possibleFixes: options.possibleFixes ?? [
54 + 'Verify the download URL has not expired (check expiresAt)',
55 + 'Ensure the file exists at the specified mount path',
56 + 'Retry the operation; presigned URLs may have transient failures',
57 + ],
58 + });
59 +
60 + this.name = 'RemoteFileDownloadError';
61 + }
62 +}
ts/packages/core/src/errors/index.ts
+3
@@ -33,3 +33,6 @@ export * from './SDKErrors';
33
34 // Trigger Errors
35 export * from './TriggerErrors';
36 +
37 +// Remote File Errors
38 +export * from './RemoteFileErrors';
ts/packages/core/src/index.ts
+4
@@ -5,9 +5,12 @@ export { ComposioProvider } from './provider/ComposioProvider';
5 export { BaseNonAgenticProvider, BaseAgenticProvider } from './provider/BaseProvider';
6 export type { BaseComposioProvider } from './provider/BaseProvider';
7 export { jsonSchemaToZodSchema, removeNonRequiredProperties } from './utils/jsonSchema';
8 +export { getExtensionFromMimeType } from './utils/mime';
9 export { AuthScheme } from './models/AuthScheme';
10 export { MCP } from './models/MCP';
11 +export { RemoteFile } from './models/RemoteFile';
12 export { createConnectionRequest } from './models/ConnectionRequest';
13 +export { ToolRouterSession } from './models/ToolRouterSession';
14 export * from './types/provider.types';
15 export * from './types/customTool.types';
16 export * from './types/tool.types';
@@ -22,6 +25,7 @@ export * from './types/mcp.types';
25 export * from './types/files.types';
26 export * from './types/connectionRequest.types';
27 export * from './types/toolRouter.types';
28 +export * from './types/ToolRouterSessionFilesMount.types';
29 export * as constants from './utils/constants';
30
31 export { default as logger } from './utils/logger';
ts/packages/core/src/models/RemoteFile.ts new
+172
@@ -0,0 +1,172 @@
1 +import { platform } from '#platform';
2 +import { COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME } from '../utils/constants';
3 +
4 +function getParentDir(filePath: string): string {
5 + const lastSep = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
6 + if (lastSep <= 0) return '';
7 + return filePath.slice(0, lastSep);
8 +}
9 +import { RemoteFileData, RemoteFileDataSchema } from '../types/ToolRouterSessionFilesMount.types';
10 +import { RemoteFileDownloadError, ValidationError } from '../errors';
11 +
12 +/**
13 + * Represents a file stored in a tool router session's file mount.
14 + * Provides methods to fetch, save, and work with the file content.
15 + *
16 + * @example
17 + * ```typescript
18 + * const remoteFile = await session.files.download('/output/report.pdf');
19 + * const buffer = await remoteFile.buffer();
20 + * await remoteFile.save('/tmp/report.pdf');
21 + * const text = await remoteFile.text();
22 + * ```
23 + *
24 + * @example
25 + * ```typescript
26 + * // Create from API response (snake_case)
27 + * const remoteFile = RemoteFile.parse(apiResponse);
28 + *
29 + * // Or create from parsed data (camelCase)
30 + * const remoteFile = new RemoteFile({
31 + * expiresAt: '...',
32 + * mountRelativePath: 'report.pdf',
33 + * sandboxMountPrefix: '/mnt/files',
34 + * downloadUrl: 'https://...',
35 + * });
36 + * ```
37 + */
38 +export class RemoteFile {
39 + /** ISO 8601 timestamp when the download URL expires */
40 + readonly expiresAt: string;
41 +
42 + /** Relative path within the mount (e.g. "report.pdf") */
43 + readonly mountRelativePath: string;
44 +
45 + /** Absolute mount path inside the sandbox (e.g. /mnt/files) */
46 + readonly sandboxMountPrefix: string;
47 +
48 + /** Presigned URL for downloading the file */
49 + readonly downloadUrl: string;
50 +
51 + constructor(data: RemoteFileData) {
52 + this.expiresAt = data.expiresAt;
53 + this.mountRelativePath = data.mountRelativePath;
54 + this.sandboxMountPrefix = data.sandboxMountPrefix;
55 + this.downloadUrl = data.downloadUrl;
56 + }
57 +
58 + /**
59 + * Parses an API response (snake_case) and returns a RemoteFile instance.
60 + * @param data - Raw API response with snake_case keys
61 + * @returns A RemoteFile instance
62 + * @throws ValidationError if the response shape is invalid
63 + */
64 + static parse(data: unknown): RemoteFile {
65 + const parsed = RemoteFileDataSchema.safeParse(data);
66 + if (!parsed.success) {
67 + throw new ValidationError('Failed to parse remote file response', {
68 + cause: parsed.error,
69 + });
70 + }
71 + return new RemoteFile(parsed.data);
72 + }
73 +
74 + /** Filename extracted from the mount path (e.g. "report.pdf" from "output/report.pdf") */
75 + get filename(): string {
76 + return platform.basename(this.mountRelativePath);
77 + }
78 +
79 + /**
80 + * Fetches the file content as a buffer.
81 + * @returns The file content as a Uint8Array
82 + * @throws RemoteFileDownloadError if the fetch fails
83 + */
84 + async buffer(): Promise<Uint8Array> {
85 + const response = await fetch(this.downloadUrl);
86 + if (!response.ok) {
87 + throw new RemoteFileDownloadError(
88 + `Failed to download file: ${response.status} ${response.statusText}`,
89 + {
90 + statusCode: response.status,
91 + statusText: response.statusText,
92 + downloadUrl: this.downloadUrl,
93 + mountRelativePath: this.mountRelativePath,
94 + filename: this.filename,
95 + cause: new Error(`HTTP ${response.status}: ${response.statusText}`),
96 + }
97 + );
98 + }
99 + const arrayBuffer = await response.arrayBuffer();
100 + return new Uint8Array(arrayBuffer);
101 + }
102 +
103 + /**
104 + * Fetches the file content as UTF-8 text.
105 + * @returns The file content as a string
106 + * @throws Error if the fetch fails
107 + */
108 + async text(): Promise<string> {
109 + const buf = await this.buffer();
110 + return new TextDecoder().decode(buf);
111 + }
112 +
113 + /**
114 + * Fetches the file content as a Blob.
115 + * @returns The file content as a Blob
116 + * @throws RemoteFileDownloadError if the fetch fails
117 + */
118 + async blob(): Promise<Blob> {
119 + const response = await fetch(this.downloadUrl);
120 + if (!response.ok) {
121 + throw new RemoteFileDownloadError(
122 + `Failed to download file: ${response.status} ${response.statusText}`,
123 + {
124 + statusCode: response.status,
125 + statusText: response.statusText,
126 + downloadUrl: this.downloadUrl,
127 + mountRelativePath: this.mountRelativePath,
128 + filename: this.filename,
129 + cause: new Error(`HTTP ${response.status}: ${response.statusText}`),
130 + }
131 + );
132 + }
133 + return response.blob();
134 + }
135 +
136 + /**
137 + * Downloads and saves the file to the local filesystem.
138 + * Requires a Node.js runtime with file system support (not available in Cloudflare Workers/Edge).
139 + *
140 + * @param path - Local path to save the file. If omitted, saves to the Composio temp directory using the filename from the mount path.
141 + * @returns The absolute path where the file was saved
142 + * @throws Error if file system is not supported or the save fails
143 + */
144 + async save(path?: string): Promise<string> {
145 + if (!platform.supportsFileSystem) {
146 + throw new Error(
147 + 'File system operations are not supported in this runtime (e.g. Cloudflare Workers). ' +
148 + 'Use buffer(), text(), or blob() to work with the file content in memory, or run in Node.js.'
149 + );
150 + }
151 +
152 + const content = await this.buffer();
153 + const homeDir = platform.homedir();
154 + if (!homeDir) {
155 + throw new Error('Cannot determine save location: home directory is not available');
156 + }
157 +
158 + const savePath =
159 + path ?? platform.joinPath(homeDir, COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME, this.filename);
160 +
161 + const dir =
162 + path != null
163 + ? getParentDir(savePath)
164 + : platform.joinPath(homeDir, COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME);
165 + if (dir && !platform.existsSync(dir)) {
166 + platform.mkdirSync(dir);
167 + }
168 +
169 + platform.writeFileSync(savePath, content);
170 + return savePath;
171 + }
172 +}
ts/packages/core/src/models/ToolRouter.ts
+25 -177
@@ -22,32 +22,14 @@ import { telemetry } from '../telemetry/Telemetry';
22 import { BaseComposioProvider } from '../provider/BaseProvider';
23 import { ComposioConfig } from '../composio';
24 import {
25 - ToolRouterAuthorizeFn,
26 - ToolRouterToolkitsFn,
25 ToolRouterCreateSessionConfig,
28 - ToolRouterSession,
29 - ToolRouterSessionExperimental,
30 - ToolkitConnectionStateSchema,
31 - ToolRouterToolkitsOptions,
32 - ToolRouterToolkitsOptionsSchema,
26 + Session,
27 + SessionExperimental,
28 MCPServerType,
29 ToolRouterMCPServerConfig,
30 } from '../types/toolRouter.types';
31 import { ToolRouterCreateSessionConfigSchema } from '../types/toolRouter.types';
37 -import { Tools } from './Tools';
38 -import {
39 - ExecuteToolModifiers,
40 - SessionExecuteMetaModifiers,
41 - SessionMetaToolOptions,
42 - ProviderOptions,
43 - TransformToolSchemaModifier,
44 -} from '../types/modifiers.types';
45 -import { ConnectionRequest } from '../types/connectionRequest.types';
46 -import { createConnectionRequest } from './ConnectionRequest';
47 -import { ConnectedAccountStatuses } from '../types/connectedAccounts.types';
48 -import { transform } from '../utils/transform';
32 import { SessionCreateParams } from '@composio/client/resources/tool-router.mjs';
50 -import { ValidationError } from '../errors';
33 import {
34 transformToolRouterTagsParams,
35 transformToolRouterToolsParams,
@@ -55,6 +37,7 @@ import {
37 transformToolRouterWorkbenchParams,
38 transformToolRouterToolkitsParams,
39 } from '../lib/toolRouterParams';
40 +import { ToolRouterSession } from './ToolRouterSession';
41
42 export class ToolRouter<
43 TToolCollection,
@@ -68,157 +51,28 @@ export class ToolRouter<
51 telemetry.instrument(this, 'ToolRouter');
52 }
53
71 - /**
72 - * Creates a function that authorizes a toolkit for a user.
73 - * @param sessionId {string} The session id to create the authorize function for
74 - * @returns {ToolRouterAuthorizeFn} The authorize function
75 - *
76 - */
77 - private createAuthorizeFn = (sessionId: string): ToolRouterAuthorizeFn => {
78 - const authorizeFn = async (
79 - toolkit: string,
80 - options?: { callbackUrl?: string }
81 - ): Promise<ConnectionRequest> => {
82 - const response = await this.client.toolRouter.session.link(sessionId, {
83 - ...(options?.callbackUrl ? { callback_url: options.callbackUrl } : {}),
84 - toolkit,
85 - });
86 -
87 - return createConnectionRequest(
88 - this.client,
89 - response.connected_account_id,
90 - ConnectedAccountStatuses.INITIATED,
91 - response.redirect_url
92 - );
93 - };
94 - return authorizeFn;
95 - };
96 -
97 - /**
98 - *
99 - * @param sessionId {string} The session id to create the toolkits function for
100 - * @returns {ToolRouterToolkitsFn} The toolkits function
101 - *
102 - * @example
103 - * ```typescript
104 - * import { Composio } from '@composio/core';
105 - *
106 - * const composio = new Composio();
107 - * const session = await composio.toolRouter.use('session_123');
108 - *
109 - * const toolkits = await session.toolkits();
110 - * console.log(toolkits);
111 - * ```
112 - */
113 - private createToolkitsFn = (sessionId: string): ToolRouterToolkitsFn => {
114 - const connectionsFn = async (options?: ToolRouterToolkitsOptions) => {
115 - const toolkitOptions = ToolRouterToolkitsOptionsSchema.safeParse(options ?? {});
116 - if (!toolkitOptions.success) {
117 - throw new ValidationError('Failed to parse toolkits options', {
118 - cause: toolkitOptions.error,
119 - });
120 - }
121 -
122 - const result = await this.client.toolRouter.session.toolkits(sessionId, {
123 - cursor: toolkitOptions.data.nextCursor,
124 - limit: toolkitOptions.data.limit,
125 - toolkits: toolkitOptions.data.toolkits,
126 - is_connected: toolkitOptions.data.isConnected,
127 - search: toolkitOptions.data.search,
128 - });
129 -
130 - const toolkitConnectedStates = result.items.map(item => {
131 - const connectedState = transform(item)
132 - .with(ToolkitConnectionStateSchema)
133 - .using(item => ({
134 - slug: item.slug,
135 - name: item.name,
136 - logo: item.meta?.logo,
137 - isNoAuth: item.is_no_auth,
138 - connection: item.is_no_auth
139 - ? undefined
140 - : {
141 - isActive: item.connected_account?.status === 'ACTIVE',
142 - authConfig: item.connected_account && {
143 - id: item.connected_account?.auth_config.id,
144 - mode: item.connected_account?.auth_config.auth_scheme,
145 - isComposioManaged: item.connected_account?.auth_config.is_composio_managed,
146 - },
147 - connectedAccount: item.connected_account
148 - ? {
149 - id: item.connected_account.id,
150 - status: item.connected_account.status,
151 - }
152 - : undefined,
153 - },
154 - }));
155 - return connectedState;
156 - });
157 -
158 - return {
159 - items: toolkitConnectedStates,
160 - nextCursor: result.next_cursor,
161 - totalPages: result.total_pages,
162 - };
163 - };
164 -
165 - return connectionsFn as ToolRouterToolkitsFn;
166 - };
167 -
168 - /**
169 - * @internal
170 - * Creates a function that wraps the tools based on the provider.
171 - * The returned tools will be of the type the frameworks expects.
172 - *
173 - * @param sessionId - The session id to get the tools for
174 - * @returns A function that wraps the tools based on the provider with session-specific modifiers.
175 - */
176 - private createToolsFn = (
177 - sessionId: string
178 - ): ((modifiers?: SessionMetaToolOptions) => Promise<ReturnType<TProvider['wrapTools']>>) => {
179 - return async (modifiers?: SessionMetaToolOptions) => {
180 - const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
181 - const tools = await ToolsModel.getRawToolRouterMetaTools(
182 - sessionId,
183 - modifiers?.modifySchema
184 - ? {
185 - modifySchema: modifiers?.modifySchema,
186 - }
187 - : undefined
188 - );
189 - const wrappedTools = ToolsModel.wrapToolsForToolRouter(sessionId, tools, modifiers);
190 - return wrappedTools as ReturnType<TProvider['wrapTools']>;
191 - };
192 - };
193 -
194 - /**
195 - * Creates a MCP server config object.
196 - * @param type {MCPServerType} The type of the MCP server
197 - * @param url {string} The URL of the MCP server
198 - * @returns {ToolRouterMCPServerConfig} The MCP server config object
199 - */
200 - private createMCPServerConfig = ({
54 + private createMCPServerConfig({
55 type,
56 url,
57 }: {
58 type: MCPServerType;
59 url: string;
206 - }): ToolRouterMCPServerConfig => {
60 + }): ToolRouterMCPServerConfig {
61 return {
62 type,
63 url,
64 headers: {
211 - ...(this.config?.apiKey ? { 'x-api-key': this.config?.apiKey } : {}),
65 + ...(this.config?.apiKey ? { 'x-api-key': this.config.apiKey } : {}),
66 },
67 };
214 - };
68 + }
69
70 /**
71 * Creates a new tool router session for a user.
72 *
73 * @param userId {string} The user id to create the session for
74 * @param config {ToolRouterCreateSessionConfig} The config for the tool router session
221 - * @returns {Promise<ToolRouterSession<TToolCollection, TTool, TProvider>>} The tool router session
75 + * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session
76 *
77 * @example
78 * ```typescript
@@ -251,7 +105,7 @@ export class ToolRouter<
105 async create(
106 userId: string,
107 config?: ToolRouterCreateSessionConfig
254 - ): Promise<ToolRouterSession<TToolCollection, TTool, TProvider>> {
108 + ): Promise<Session<TToolCollection, TTool, TProvider>> {
109 const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});
110
111 const payload: SessionCreateParams = {
@@ -265,7 +119,6 @@ export class ToolRouter<
119 routerConfig.manageConnections
120 ),
121 workbench: transformToolRouterWorkbenchParams(routerConfig.workbench),
268 - // Map SDK's experimental.assistivePrompt.userTimezone to API's experimental.assistive_prompt_config.user_timezone
122 experimental: routerConfig.experimental?.assistivePrompt?.userTimezone
123 ? {
124 assistive_prompt_config: {
@@ -277,27 +130,25 @@ export class ToolRouter<
130
131 const session = await this.client.toolRouter.session.create(payload);
132
280 - // Transform experimental response: API's assistive_prompt -> SDK's assistivePrompt
281 - const experimental: ToolRouterSessionExperimental | undefined = session.experimental
133 + const experimental: SessionExperimental | undefined = session.experimental
134 ? {
135 assistivePrompt: session.experimental.assistive_prompt,
136 }
137 : undefined;
138
287 - return {
288 - sessionId: session.session_id,
289 - mcp: this.createMCPServerConfig(session.mcp),
290 - tools: this.createToolsFn(session.session_id),
291 - authorize: this.createAuthorizeFn(session.session_id),
292 - toolkits: this.createToolkitsFn(session.session_id),
293 - experimental,
294 - };
139 + return new ToolRouterSession<TToolCollection, TTool, TProvider>(
140 + this.client,
141 + this.config,
142 + session.session_id,
143 + this.createMCPServerConfig(session.mcp),
144 + experimental
145 + );
146 }
147
148 /**
149 * Use an existing session
150 * @param id {string} The id of the session to use
300 - * @returns {Promise<ToolRouterSession<TToolCollection, TTool, TProvider>>} The tool router session
151 + * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session
152 *
153 * @example
154 * ```typescript
@@ -311,16 +162,13 @@ export class ToolRouter<
162 * console.log(session.mcp.headers);
163 * ```
164 */
314 - async use(
315 - id: string
316 - ): Promise<Omit<ToolRouterSession<TToolCollection, TTool, TProvider>, 'experimental'>> {
165 + async use(id: string): Promise<Omit<Session<TToolCollection, TTool, TProvider>, 'experimental'>> {
166 const session = await this.client.toolRouter.session.retrieve(id);
318 - return {
319 - sessionId: session.session_id,
320 - mcp: this.createMCPServerConfig(session.mcp),
321 - tools: this.createToolsFn(session.session_id),
322 - authorize: this.createAuthorizeFn(session.session_id),
323 - toolkits: this.createToolkitsFn(session.session_id),
324 - };
167 + return new ToolRouterSession<TToolCollection, TTool, TProvider>(
168 + this.client,
169 + this.config,
170 + session.session_id,
171 + this.createMCPServerConfig(session.mcp)
172 + );
173 }
174 }
ts/packages/core/src/models/ToolRouterSession.ts new
+202
@@ -0,0 +1,202 @@
1 +import { telemetry } from '../telemetry/Telemetry';
2 +import { Composio as ComposioClient } from '@composio/client';
3 +import { BaseComposioProvider } from '../provider/BaseProvider';
4 +import { ComposioConfig } from '../composio';
5 +import {
6 + ToolRouterMCPServerConfig,
7 + SessionExperimental,
8 + ToolRouterToolkitsOptions,
9 + ToolRouterToolkitsOptionsSchema,
10 + ToolRouterSessionSearchResponse,
11 + ToolRouterSessionSearchResponseSchema,
12 + ToolRouterSessionExecuteResponse,
13 + ToolRouterSessionExecuteResponseSchema,
14 +} from '../types/toolRouter.types';
15 +import {
16 + transformSearchResponse,
17 + transformExecuteResponse,
18 +} from '../utils/transformers/toolRouterResponseTransform';
19 +import { SessionMetaToolOptions } from '../types/modifiers.types';
20 +import { ConnectionRequest } from '../types/connectionRequest.types';
21 +import { createConnectionRequest } from './ConnectionRequest';
22 +import { ConnectedAccountStatuses } from '../types/connectedAccounts.types';
23 +import { transform } from '../utils/transform';
24 +import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';
25 +import { ValidationError } from '../errors';
26 +import { Tools } from './Tools';
27 +import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';
28 +
29 +export class ToolRouterSession<
30 + TToolCollection,
31 + TTool,
32 + TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,
33 +> {
34 + public readonly sessionId: string;
35 + public readonly mcp: ToolRouterMCPServerConfig;
36 + public readonly files: ToolRouterSessionFilesMount;
37 +
38 + constructor(
39 + private readonly client: ComposioClient,
40 + private readonly config: ComposioConfig<TProvider> | undefined,
41 + sessionId: string,
42 + mcp: ToolRouterMCPServerConfig,
43 + public readonly experimental?: SessionExperimental
44 + ) {
45 + this.sessionId = sessionId;
46 + this.mcp = mcp;
47 + this.files = new ToolRouterSessionFilesMount(client, sessionId);
48 + telemetry.instrument(this, 'ToolRouterSession');
49 + }
50 +
51 + /**
52 + * Get the tools available in the session, formatted for your AI framework.
53 + * Requires a provider to be configured in the Composio constructor.
54 + */
55 + async tools(modifiers?: SessionMetaToolOptions): Promise<ReturnType<TProvider['wrapTools']>> {
56 + const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
57 + const tools = await ToolsModel.getRawToolRouterMetaTools(
58 + this.sessionId,
59 + modifiers?.modifySchema ? { modifySchema: modifiers.modifySchema } : undefined
60 + );
61 + const wrappedTools = ToolsModel.wrapToolsForToolRouter(this.sessionId, tools, modifiers);
62 + return wrappedTools as ReturnType<TProvider['wrapTools']>;
63 + }
64 +
65 + /**
66 + * Initiate an authorization flow for a toolkit.
67 + * Returns a ConnectionRequest with a redirect URL for the user.
68 + */
69 + async authorize(toolkit: string, options?: { callbackUrl?: string }): Promise<ConnectionRequest> {
70 + const response = await this.client.toolRouter.session.link(this.sessionId, {
71 + ...(options?.callbackUrl ? { callback_url: options.callbackUrl } : {}),
72 + toolkit,
73 + });
74 +
75 + return createConnectionRequest(
76 + this.client,
77 + response.connected_account_id,
78 + ConnectedAccountStatuses.INITIATED,
79 + response.redirect_url
80 + );
81 + }
82 +
83 + /**
84 + * Query the connection state of toolkits in the session.
85 + * Supports pagination and filtering by toolkit slugs.
86 + */
87 + async toolkits(options?: ToolRouterToolkitsOptions) {
88 + const toolkitOptions = ToolRouterToolkitsOptionsSchema.safeParse(options ?? {});
89 + if (!toolkitOptions.success) {
90 + throw new ValidationError('Failed to parse toolkits options', {
91 + cause: toolkitOptions.error,
92 + });
93 + }
94 +
95 + const result = await this.client.toolRouter.session.toolkits(this.sessionId, {
96 + cursor: toolkitOptions.data.nextCursor,
97 + limit: toolkitOptions.data.limit,
98 + toolkits: toolkitOptions.data.toolkits,
99 + is_connected: toolkitOptions.data.isConnected,
100 + search: toolkitOptions.data.search,
101 + });
102 +
103 + const toolkitConnectedStates = result.items.map(item => {
104 + const connectedState = transform(item)
105 + .with(ToolkitConnectionStateSchema)
106 + .using(item => ({
107 + slug: item.slug,
108 + name: item.name,
109 + logo: item.meta?.logo,
110 + isNoAuth: item.is_no_auth,
111 + connection: item.is_no_auth
112 + ? undefined
113 + : {
114 + isActive: item.connected_account?.status === 'ACTIVE',
115 + authConfig: item.connected_account && {
116 + id: item.connected_account?.auth_config.id,
117 + mode: item.connected_account?.auth_config.auth_scheme,
118 + isComposioManaged: item.connected_account?.auth_config.is_composio_managed,
119 + },
120 + connectedAccount: item.connected_account
121 + ? {
122 + id: item.connected_account.id,
123 + status: item.connected_account.status,
124 + }
125 + : undefined,
126 + },
127 + }));
128 + return connectedState;
129 + });
130 +
131 + return {
132 + items: toolkitConnectedStates,
133 + nextCursor: result.next_cursor ?? undefined,
134 + totalPages: result.total_pages,
135 + };
136 + }
137 +
138 + /**
139 + * Search for tools by semantic use case.
140 + * Returns relevant tools for the given query with schemas and guidance.
141 + *
142 + * @param params - Search parameters
143 + * @param params.query - Semantic use-case query (e.g. "send emails", "create GitHub issues")
144 + * @param params.toolkits - Optional toolkit slugs to filter by
145 + * @returns Search results with matching tools and schemas
146 + *
147 + * @example
148 + * ```typescript
149 + * const session = await composio.toolRouter.use('session_123');
150 + * const results = await session.search({
151 + * query: 'send emails and notify Slack',
152 + * toolkits: ['gmail', 'slack'],
153 + * });
154 + * ```
155 + */
156 + async search(params: {
157 + query: string;
158 + toolkits?: string[];
159 + }): Promise<ToolRouterSessionSearchResponse> {
160 + const response = await this.client.toolRouter.session.search(this.sessionId, {
161 + queries: [{ use_case: params.query }],
162 + ...(params.toolkits?.length ? { toolkits: params.toolkits } : {}),
163 + });
164 + const transformed = transformSearchResponse(response);
165 + return ToolRouterSessionSearchResponseSchema.parse(transformed);
166 + }
167 +
168 + /**
169 + * Execute a tool within the session.
170 + *
171 + * @param toolSlug - The tool slug to execute (e.g. "GMAIL_SEND_EMAIL")
172 + * @param arguments_ - Optional tool arguments. Defaults to empty object if omitted.
173 + * @returns The tool execution result
174 + *
175 + * @example
176 + * ```typescript
177 + * const session = await composio.toolRouter.use('session_123');
178 + * const result = await session.execute('GMAIL_SEND_EMAIL', {
179 + * to: 'user@example.com',
180 + * subject: 'Hello',
181 + * body: 'Hi!',
182 + * });
183 + * ```
184 + *
185 + * @example
186 + * ```typescript
187 + * // Execute with no arguments
188 + * const result = await session.execute('HACKERNEWS_GET_USER');
189 + * ```
190 + */
191 + async execute(
192 + toolSlug: string,
193 + arguments_?: Record<string, unknown>
194 + ): Promise<ToolRouterSessionExecuteResponse> {
195 + const response = await this.client.toolRouter.session.execute(this.sessionId, {
196 + tool_slug: toolSlug,
197 + arguments: arguments_ ?? {},
198 + });
199 + const transformed = transformExecuteResponse(response);
200 + return ToolRouterSessionExecuteResponseSchema.parse(transformed);
201 + }
202 +}
ts/packages/core/src/models/ToolRouterSessionFileMount.ts new
+383
@@ -0,0 +1,383 @@
1 +import { telemetry } from '../telemetry/Telemetry';
2 +import { Composio as ComposioClient } from '@composio/client';
3 +import {
4 + FileDeleteResponse,
5 + FileDeleteResponseSchema,
6 + FileListResponse,
7 + FileListResponseSchema,
8 + RemoteFileDataSchema,
9 + ToolRouterSessionFilesMountDeleteOptions,
10 + ToolRouterSessionFilesMountDeleteOptionsSchema,
11 + ToolRouterSessionFilesMountDownloadOptions,
12 + ToolRouterSessionFilesMountDownloadOptionsSchema,
13 + ToolRouterSessionFilesMountListOptions,
14 + ToolRouterSessionFilesMountListOptionsSchema,
15 + ToolRouterSessionFilesMountUploadOptions,
16 + ToolRouterSessionFilesMountUploadOptionsSchema,
17 +} from '../types/ToolRouterSessionFilesMount.types';
18 +import { RemoteFile } from './RemoteFile';
19 +import { ValidationError } from '../errors';
20 +import { platform } from '#platform';
21 +import { getExtensionFromMimeType } from '../utils/mime';
22 +import { getRandomShortId } from '../utils/uuid';
23 +
24 +export class ToolRouterSessionFilesMount {
25 + private readonly sessionId: string;
26 + private readonly client: ComposioClient;
27 +
28 + constructor(client: ComposioClient, sessionId: string) {
29 + this.client = client;
30 + this.sessionId = sessionId;
31 + telemetry.instrument(this, 'ToolRouterSessionFiles');
32 + }
33 +
34 + /**
35 + * Lists files and directories at the specified path on the session's file mount.
36 + *
37 + * Use this to browse the virtual filesystem attached to the tool router session.
38 + * The path is relative to the mount root (e.g., `"/"` for root, `"/documents"` for a subdirectory).
39 + * Supports cursor-based pagination via `cursor` and `limit` options.
40 + *
41 + * @param options - Optional configuration for the list operation.
42 + * @param options.path - The directory path to list. Use `"/"` for the mount root.
43 + * @param options.mountId - The ID of the file mount to operate on. Defaults to `"files"` when omitted.
44 + * @param options.cursor - Pagination cursor from the previous response's nextCursor field.
45 + * @param options.limit - Maximum number of files to return per page (1-500).
46 + * @returns List of files with nextCursor for pagination.
47 + *
48 + * @example
49 + * ```typescript
50 + * const session = await composio.toolRouter.use('session_123');
51 + * const { items, nextCursor } = await session.files.list({ path: '/' });
52 + * ```
53 + *
54 + * @example
55 + * ```typescript
56 + * // Paginated listing
57 + * let result = await session.files.list({ path: '/', limit: 10 });
58 + * while (result.nextCursor) {
59 + * result = await session.files.list({ path: '/', cursor: result.nextCursor, limit: 10 });
60 + * }
61 + * ```
62 + */
63 + async list(options?: ToolRouterSessionFilesMountListOptions): Promise<FileListResponse> {
64 + const listOptions = ToolRouterSessionFilesMountListOptionsSchema.safeParse(options ?? {});
65 +
66 + if (!listOptions.success) {
67 + throw new ValidationError('Failed to parse tool router session files mount list options', {
68 + cause: listOptions.error,
69 + });
70 + }
71 +
72 + // API requires: no leading slash, min 1 char when provided. Omit for root.
73 + const rawPath = listOptions.data.path;
74 + const mountRelativePrefix =
75 + rawPath === undefined || rawPath === '' || rawPath === '/'
76 + ? undefined
77 + : rawPath.startsWith('/')
78 + ? rawPath.slice(1)
79 + : rawPath;
80 +
81 + const response = await this.client.toolRouter.session.files.list(listOptions.data.mountId, {
82 + session_id: this.sessionId,
83 + mount_relative_prefix: mountRelativePrefix,
84 + cursor: listOptions.data.cursor,
85 + limit: listOptions.data.limit,
86 + });
87 +
88 + const data =
89 + typeof response === 'object' && 'body' in response
90 + ? (response as { body: unknown }).body
91 + : response;
92 +
93 + const parsed = FileListResponseSchema.safeParse(data);
94 + if (!parsed.success) {
95 + throw new ValidationError('Failed to parse file list response', {
96 + cause: parsed.error,
97 + });
98 + }
99 + return parsed.data;
100 + }
101 +
102 + private async normalizeUploadInput(
103 + input: string | File | ArrayBuffer | Uint8Array,
104 + options: { remotePath?: string; mimetype?: string }
105 + ): Promise<{ fileToUpload: File; remotePath: string; mimetype: string }> {
106 + if (typeof input === 'string') {
107 + if (input.startsWith('http://') || input.startsWith('https://')) {
108 + const response = await fetch(input);
109 + if (!response.ok) {
110 + throw new Error(`Failed to fetch file from URL: ${response.statusText}`);
111 + }
112 + const arrayBuffer = await response.arrayBuffer();
113 + const mimeType = response.headers.get('content-type') || 'application/octet-stream';
114 + const url = new URL(input);
115 + const pathname = url.pathname;
116 + const segments = pathname.split('/').filter(Boolean);
117 + let filename = segments.length > 0 ? segments[segments.length - 1] : '';
118 + if (!filename || !filename.includes('.')) {
119 + const extension = getExtensionFromMimeType(mimeType);
120 + filename = `${getRandomShortId()}.${extension}`;
121 + }
122 + const file = new File([arrayBuffer], filename, { type: mimeType });
123 + return {
124 + fileToUpload: file,
125 + remotePath: options.remotePath ?? filename,
126 + mimetype: mimeType,
127 + };
128 + }
129 + const content = platform.readFileSync(input);
130 + const buffer =
131 + content instanceof Uint8Array
132 + ? new Uint8Array(content)
133 + : new TextEncoder().encode(content as string);
134 + const filename = platform.basename(input);
135 + const mimetype = options.mimetype ?? 'application/octet-stream';
136 + const file = new File([buffer], filename, { type: mimetype });
137 + return {
138 + fileToUpload: file,
139 + remotePath: options.remotePath ?? filename,
140 + mimetype,
141 + };
142 + }
143 +
144 + if (input instanceof File) {
145 + return {
146 + fileToUpload: input,
147 + remotePath: options.remotePath ?? (input.name || `upload-${getRandomShortId()}.bin`),
148 + mimetype: input.type || 'application/octet-stream',
149 + };
150 + }
151 +
152 + const buffer = input instanceof ArrayBuffer ? new Uint8Array(input) : input;
153 + if (!options.mimetype && !options.remotePath) {
154 + throw new Error(
155 + 'When passing a buffer, either mimetype or remotePath (filename) is required. ' +
156 + 'Example: files.upload(buffer, { remotePath: "data.json", mimetype: "application/json" })'
157 + );
158 + }
159 + const mimetype = options.mimetype ?? 'application/octet-stream';
160 + const ext = getExtensionFromMimeType(mimetype);
161 + const remotePath = options.remotePath ?? `upload-${getRandomShortId()}.${ext}`;
162 + const file = new File([buffer as BlobPart], remotePath, { type: mimetype });
163 + return {
164 + fileToUpload: file,
165 + remotePath,
166 + mimetype,
167 + };
168 + }
169 +
170 + /**
171 + * Uploads a file to the session's file mount.
172 + *
173 + * Accepts a file path (local or URL), a native File object, or a raw buffer.
174 + * The file is stored in the virtual filesystem associated with the tool router session.
175 + *
176 + * @param input - File path (string), native File, or raw buffer (ArrayBuffer | Uint8Array).
177 + * @param options - Optional configuration. When passing a buffer, remotePath is required.
178 + * @returns Metadata about the uploaded file.
179 + *
180 + * @example
181 + * ```typescript
182 + * // From file path (local or URL)
183 + * await session.files.upload('/path/to/report.pdf');
184 + * await session.files.upload('https://example.com/file.pdf');
185 + * ```
186 + *
187 + * @example
188 + * ```typescript
189 + * // From native File (e.g. from input[type=file])
190 + * await session.files.upload(fileInput.files[0]);
191 + * ```
192 + *
193 + * @example
194 + * ```typescript
195 + * // From raw buffer
196 + * await session.files.upload(buffer, { remotePath: 'data.json', mimetype: 'application/json' });
197 + * ```
198 + */
199 + async upload(
200 + input: string | File | ArrayBuffer | Uint8Array,
201 + options?: ToolRouterSessionFilesMountUploadOptions
202 + ): Promise<RemoteFile> {
203 + const uploadOptions = ToolRouterSessionFilesMountUploadOptionsSchema.safeParse(options ?? {});
204 +
205 + if (!uploadOptions.success) {
206 + throw new ValidationError('Failed to parse tool router session files mount upload options', {
207 + cause: uploadOptions.error,
208 + });
209 + }
210 +
211 + const { fileToUpload, remotePath, mimetype } = await this.normalizeUploadInput(
212 + input,
213 + uploadOptions.data
214 + );
215 +
216 + const createUploadURLResponse = await this.client.toolRouter.session.files.createUploadURL(
217 + uploadOptions.data.mountId,
218 + {
219 + session_id: this.sessionId,
220 + mount_relative_path: remotePath,
221 + mimetype,
222 + }
223 + );
224 +
225 + const uploadURLData =
226 + typeof createUploadURLResponse === 'object' && 'body' in createUploadURLResponse
227 + ? (createUploadURLResponse as { body: unknown }).body
228 + : createUploadURLResponse;
229 +
230 + const uploadResponse = await fetch((uploadURLData as { upload_url: string }).upload_url, {
231 + method: 'PUT',
232 + body: await fileToUpload.arrayBuffer(),
233 + headers: {
234 + 'Content-Type': mimetype,
235 + },
236 + });
237 +
238 + if (!uploadResponse.ok) {
239 + throw new Error(`Failed to upload file: ${uploadResponse.statusText}`);
240 + }
241 +
242 + const createDownloadURLResponse = await this.client.toolRouter.session.files.createDownloadURL(
243 + uploadOptions.data.mountId,
244 + {
245 + session_id: this.sessionId,
246 + mount_relative_path: (uploadURLData as { mount_relative_path: string }).mount_relative_path,
247 + }
248 + );
249 +
250 + const downloadData =
251 + typeof createDownloadURLResponse === 'object' && 'body' in createDownloadURLResponse
252 + ? (createDownloadURLResponse as { body: unknown }).body
253 + : createDownloadURLResponse;
254 +
255 + const parsed = RemoteFileDataSchema.safeParse(downloadData);
256 + if (!parsed.success) {
257 + throw new ValidationError('Failed to parse remote file properties', {
258 + cause: parsed.error,
259 + });
260 + }
261 +
262 + return new RemoteFile(parsed.data);
263 + }
264 +
265 + /**
266 + * Downloads a file from the session's file mount to the local filesystem.
267 + *
268 + * Retrieves a file stored in the session's virtual filesystem (e.g., one produced
269 + * by a tool or previously uploaded) and saves it to the specified local path.
270 + *
271 + * @param filePath - The path of the file on the mount to download, or the local path where the file should be saved (implementation-specific).
272 + * @param options - Optional configuration for the download.
273 + * @param options.mountId - The ID of the file mount to download from. Defaults to `"files"` when omitted.
274 + * @returns The downloaded file data or path (implementation-specific).
275 + *
276 + * @example
277 + * ```typescript
278 + * const session = await composio.toolRouter.use('session_123');
279 + * const result = await session.files.download('/output/report.pdf');
280 + * ```
281 + *
282 + * @example
283 + * ```typescript
284 + * // Download from a custom mount
285 + * await session.files.download('/exports/data.json', {
286 + * mountId: 'custom-mount',
287 + * });
288 + * ```
289 + */
290 + async download(
291 + filePath: string,
292 + options?: ToolRouterSessionFilesMountDownloadOptions
293 + ): Promise<RemoteFile> {
294 + const downloadOptions = ToolRouterSessionFilesMountDownloadOptionsSchema.safeParse(
295 + options ?? {}
296 + );
297 +
298 + if (!downloadOptions.success) {
299 + throw new ValidationError(
300 + 'Failed to parse tool router session files mount download options',
301 + {
302 + cause: downloadOptions.error,
303 + }
304 + );
305 + }
306 +
307 + const createDownloadURLResponse = await this.client.toolRouter.session.files.createDownloadURL(
308 + downloadOptions.data.mountId,
309 + {
310 + session_id: this.sessionId,
311 + mount_relative_path: filePath,
312 + }
313 + );
314 +
315 + const downloadURLData =
316 + typeof createDownloadURLResponse === 'object' && 'body' in createDownloadURLResponse
317 + ? (createDownloadURLResponse as { body: unknown }).body
318 + : createDownloadURLResponse;
319 +
320 + const parsed = RemoteFileDataSchema.safeParse(downloadURLData);
321 + if (!parsed.success) {
322 + throw new ValidationError('Failed to parse remote file properties', {
323 + cause: parsed.error,
324 + });
325 + }
326 + return new RemoteFile(parsed.data);
327 + }
328 +
329 + /**
330 + * Deletes a file or directory at the specified path on the session's file mount.
331 + *
332 + * Removes the file or directory from the virtual filesystem. Use with caution:
333 + * deletion is typically irreversible. Ensure the path exists and is intended for removal.
334 + *
335 + * @param remotePath - The path of the file or directory to delete on the mount.
336 + * @param options - Optional configuration for the delete operation.
337 + * @param options.mountId - The ID of the file mount to operate on. Defaults to `"files"` when omitted.
338 + * @returns Confirmation of deletion (implementation-specific).
339 + *
340 + * @example
341 + * ```typescript
342 + * const session = await composio.toolRouter.use('session_123');
343 + * await session.files.delete('/temp/cache.json');
344 + * ```
345 + *
346 + * @example
347 + * ```typescript
348 + * // Delete from a custom mount
349 + * await session.files.delete('/old-backup', {
350 + * mountId: 'custom-mount',
351 + * });
352 + * ```
353 + *
354 + * @warning This operation is destructive. Deleted files cannot be recovered.
355 + */
356 + async delete(
357 + remotePath: string,
358 + options?: ToolRouterSessionFilesMountDeleteOptions
359 + ): Promise<FileDeleteResponse> {
360 + const deleteOptions = ToolRouterSessionFilesMountDeleteOptionsSchema.safeParse(options ?? {});
361 +
362 + if (!deleteOptions.success) {
363 + throw new ValidationError('Failed to parse tool router session files mount delete options', {
364 + cause: deleteOptions.error,
365 + });
366 + }
367 +
368 + const deleteResponse = await this.client.toolRouter.session.files.delete(
369 + deleteOptions.data.mountId,
370 + {
371 + session_id: this.sessionId,
372 + mount_relative_path: remotePath,
373 + }
374 + );
375 + const fileDeleteResponse = FileDeleteResponseSchema.safeParse(deleteResponse);
376 + if (!fileDeleteResponse.success) {
377 + throw new ValidationError('Failed to parse file delete response', {
378 + cause: fileDeleteResponse.error,
379 + });
380 + }
381 + return fileDeleteResponse.data;
382 + }
383 +}
ts/packages/core/src/types/ToolRouterSessionFilesMount.types.ts new
+96
@@ -0,0 +1,96 @@
1 +import z from 'zod/v3';
2 +import { DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID } from '../utils/constants';
3 +
4 +export const ToolRouterSessionFilesMountListOptionsSchema = z.object({
5 + path: z.string().optional(),
6 + mountId: z.string().default(DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID),
7 + /** Pagination cursor from the previous response nextCursor field */
8 + cursor: z.string().optional(),
9 + /** Maximum number of files to return per page (1-500) */
10 + limit: z.number().min(1).max(500).optional(),
11 +});
12 +
13 +export type ToolRouterSessionFilesMountListOptions = z.input<
14 + typeof ToolRouterSessionFilesMountListOptionsSchema
15 +>;
16 +
17 +const FileListItemSchema = z.object({
18 + last_modified: z.string(),
19 + mount_relative_path: z.string(),
20 + sandbox_mount_prefix: z.string(),
21 + size: z.number(),
22 +});
23 +
24 +export const FileListResponseSchema = z
25 + .object({
26 + items: z.array(FileListItemSchema),
27 + next_cursor: z.string().optional(),
28 + })
29 + .transform(data => ({
30 + items: data.items.map(item => ({
31 + lastModified: item.last_modified,
32 + mountRelativePath: item.mount_relative_path,
33 + sandboxMountPrefix: item.sandbox_mount_prefix,
34 + size: item.size,
35 + })),
36 + nextCursor: data.next_cursor,
37 + }));
38 +
39 +export type FileListResponse = z.infer<typeof FileListResponseSchema>;
40 +
41 +export const ToolRouterSessionFilesMountUploadOptionsSchema = z.object({
42 + /** Remote path/filename on the mount. When passing a buffer, either mimetype or remotePath is required. */
43 + remotePath: z.string().optional(),
44 + mountId: z.string().default(DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID),
45 + /** MIME type. When passing a buffer, either mimetype or remotePath is required. Ignored when passing File (uses file.type). */
46 + mimetype: z.string().optional(),
47 +});
48 +
49 +export type ToolRouterSessionFilesMountUploadOptions = z.input<
50 + typeof ToolRouterSessionFilesMountUploadOptionsSchema
51 +>;
52 +
53 +export const ToolRouterSessionFilesMountDownloadOptionsSchema = z.object({
54 + mountId: z.string().default(DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID),
55 +});
56 +
57 +export type ToolRouterSessionFilesMountDownloadOptions = z.input<
58 + typeof ToolRouterSessionFilesMountDownloadOptionsSchema
59 +>;
60 +
61 +export const ToolRouterSessionFilesMountDeleteOptionsSchema = z.object({
62 + mountId: z.string().default(DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID),
63 +});
64 +
65 +export type ToolRouterSessionFilesMountDeleteOptions = z.input<
66 + typeof ToolRouterSessionFilesMountDeleteOptionsSchema
67 +>;
68 +
69 +export const RemoteFileDataSchema = z
70 + .object({
71 + expires_at: z.string(),
72 + mount_relative_path: z.string(),
73 + sandbox_mount_prefix: z.string(),
74 + download_url: z.string(),
75 + })
76 + .transform(data => ({
77 + expiresAt: data.expires_at,
78 + mountRelativePath: data.mount_relative_path,
79 + sandboxMountPrefix: data.sandbox_mount_prefix,
80 + downloadUrl: data.download_url,
81 + }));
82 +
83 +/** Parsed shape from API response. Use with `new RemoteFile(data)`. */
84 +export type RemoteFileData = z.infer<typeof RemoteFileDataSchema>;
85 +
86 +export const FileDeleteResponseSchema = z
87 + .object({
88 + mount_relative_path: z.string(),
89 + sandbox_mount_prefix: z.string(),
90 + })
91 + .transform(data => ({
92 + mountRelativePath: data.mount_relative_path,
93 + sandboxMountPrefix: data.sandbox_mount_prefix,
94 + }));
95 +
96 +export type FileDeleteResponse = z.infer<typeof FileDeleteResponseSchema>;
ts/packages/core/src/types/toolRouter.types.ts
+108 -27
@@ -1,7 +1,8 @@
1 import z from 'zod/v3';
2 -import { BaseComposioProvider } from '../provider/BaseProvider';
2 +import type { BaseComposioProvider } from '../provider/BaseProvider';
3 import { SessionMetaToolOptions } from './modifiers.types';
4 import { ConnectionRequest } from './connectionRequest.types';
5 +import type { ToolRouterSessionFilesMount } from '../models/ToolRouterSessionFileMount';
6
7 export const MCPServerTypeSchema = z.enum(['http', 'sse']);
8 export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;
@@ -305,49 +306,129 @@ export type ToolRouterToolkitsOptions = z.infer<typeof ToolRouterToolkitsOptions
306 export type ToolRouterToolkitsFn = (
307 options?: ToolRouterToolkitsOptions
308 ) => Promise<ToolkitConnectionsDetails>;
309 +
310 +// --- Session search response schemas (camelCase) ---
311 +
312 +const ToolRouterSessionSearchResultReferenceWorkbenchSnippetSchema = z.object({
313 + code: z.string(),
314 + description: z.string(),
315 +});
316 +
317 +const ToolRouterSessionSearchResultSchema = z.object({
318 + index: z.number(),
319 + useCase: z.string(),
320 + primaryToolSlugs: z.array(z.string()),
321 + relatedToolSlugs: z.array(z.string()),
322 + toolkits: z.array(z.string()),
323 + difficulty: z.string().optional(),
324 + error: z.string().nullable().optional(),
325 + executionGuidance: z.string().optional(),
326 + knownPitfalls: z.array(z.string()).optional(),
327 + memory: z.record(z.string(), z.array(z.string())).optional(),
328 + planId: z.string().optional(),
329 + recommendedPlanSteps: z.array(z.string()).optional(),
330 + referenceWorkbenchSnippets: z
331 + .array(ToolRouterSessionSearchResultReferenceWorkbenchSnippetSchema)
332 + .optional(),
333 +});
334 +
335 +const ToolRouterSessionSearchSessionSchema = z.object({
336 + id: z.string(),
337 + generateId: z.boolean(),
338 + instructions: z.string(),
339 +});
340 +
341 +const ToolRouterSessionSearchTimeInfoSchema = z.object({
342 + currentTimeUtc: z.string(),
343 + currentTimeUtcEpochSeconds: z.number(),
344 + message: z.string(),
345 +});
346 +
347 +const ToolRouterSessionSearchToolSchemasSchemaRefSchema = z.object({
348 + args: z.object({ toolSlugs: z.array(z.string()) }),
349 + message: z.string(),
350 + tool: z.literal('COMPOSIO_GET_TOOL_SCHEMAS'),
351 +});
352 +
353 +const ToolRouterSessionSearchToolSchemaSchema = z.object({
354 + toolSlug: z.string(),
355 + toolkit: z.string(),
356 + description: z.string().optional(),
357 + hasFullSchema: z.boolean().optional(),
358 + inputSchema: z.record(z.string(), z.unknown()).optional(),
359 + outputSchema: z.record(z.string(), z.unknown()).optional(),
360 + schemaRef: ToolRouterSessionSearchToolSchemasSchemaRefSchema.optional(),
361 +});
362 +
363 +const ToolRouterSessionSearchToolkitConnectionStatusSchema = z.object({
364 + toolkit: z.string(),
365 + description: z.string(),
366 + hasActiveConnection: z.boolean(),
367 + statusMessage: z.string(),
368 + connectionDetails: z.record(z.string(), z.unknown()).optional(),
369 + currentUserInfo: z.record(z.string(), z.unknown()).optional(),
370 +});
371 +
372 +export const ToolRouterSessionSearchResponseSchema = z.object({
373 + success: z.boolean(),
374 + error: z.string().nullable(),
375 + results: z.array(ToolRouterSessionSearchResultSchema),
376 + toolSchemas: z.record(z.string(), ToolRouterSessionSearchToolSchemaSchema),
377 + toolkitConnectionStatuses: z.array(ToolRouterSessionSearchToolkitConnectionStatusSchema),
378 + nextStepsGuidance: z.array(z.string()),
379 + session: ToolRouterSessionSearchSessionSchema,
380 + timeInfo: ToolRouterSessionSearchTimeInfoSchema,
381 +});
382 +export type ToolRouterSessionSearchResponse = z.infer<typeof ToolRouterSessionSearchResponseSchema>;
383 +
384 +// --- Session execute response schema (camelCase) ---
385 +
386 +export const ToolRouterSessionExecuteResponseSchema = z.object({
387 + data: z.record(z.string(), z.unknown()),
388 + error: z.string().nullable(),
389 + logId: z.string(),
390 +});
391 +export type ToolRouterSessionExecuteResponse = z.infer<
392 + typeof ToolRouterSessionExecuteResponseSchema
393 +>;
394 +
395 /**
396 * Experimental features response from session creation.
397 * Only returned on session creation, not on GET.
398 */
312 -export interface ToolRouterSessionExperimental {
399 +export interface SessionExperimental {
400 /**
401 * The assistive system prompt to inject into your agent for optimal tool router usage.
402 */
403 assistivePrompt?: string;
404 }
405
319 -export interface ToolRouterSession<
406 +export type ToolRouterSessionSearchFn = (params: {
407 + query: string;
408 + toolkits?: string[];
409 +}) => Promise<ToolRouterSessionSearchResponse>;
410 +
411 +export type ToolRouterSessionExecuteFn = (
412 + toolSlug: string,
413 + arguments_?: Record<string, unknown>
414 +) => Promise<ToolRouterSessionExecuteResponse>;
415 +
416 +/** Session type returned by ToolRouter.create() and ToolRouter.use() */
417 +export interface Session<
418 TToolCollection,
419 TTool,
420 TProvider extends BaseComposioProvider<TToolCollection, TTool, unknown>,
421 > {
324 - /**
325 - * The session id of the tool router session.
326 - */
422 sessionId: string;
328 - /**
329 - * The MCP server config of the tool router session.
330 - * Contains the URL, type ('http' or 'sse'), and headers for authentication.
331 - */
423 mcp: ToolRouterMCPServerConfig;
333 - /**
334 - * Get the tools available in the session, formatted for your AI framework.
335 - * Requires a provider to be configured in the Composio constructor.
336 - */
424 tools: ToolRouterToolsFn<TToolCollection, TTool, TProvider>;
338 - /**
339 - * Initiate an authorization flow for a toolkit.
340 - * Returns a ConnectionRequest with a redirect URL for the user.
341 - */
425 authorize: ToolRouterAuthorizeFn;
343 - /**
344 - * Query the connection state of toolkits in the session.
345 - * Supports pagination and filtering by toolkit slugs.
346 - */
426 toolkits: ToolRouterToolkitsFn;
348 - /**
349 - * Experimental features including the generated system prompt.
350 - * Only returned on session creation, not on GET.
351 - */
352 - experimental?: ToolRouterSessionExperimental;
427 + /** Search for tools by semantic use case */
428 + search: ToolRouterSessionSearchFn;
429 + /** Execute a tool within the session */
430 + execute: ToolRouterSessionExecuteFn;
431 + /** File mount operations (list, upload, download, delete) */
432 + files: ToolRouterSessionFilesMount;
433 + experimental?: SessionExperimental;
434 }
ts/packages/core/src/utils/constants.ts
+2
@@ -18,3 +18,5 @@ export const COMPOSIO_LOG_LEVEL = getEnvVariable('COMPOSIO_LOG_LEVEL') as
18 | undefined;
19
20 export const IS_DEVELOPMENT_OR_CI = getEnvVariable('DEVELOPMENT') || getEnvVariable('CI') || false;
21 +
22 +export const DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID = 'files';
ts/packages/core/src/utils/mime.ts new
+75
@@ -0,0 +1,75 @@
1 +/**
2 + * Maps MIME types to file extensions.
3 + * Used when deriving filenames from content-type headers (e.g. for URLs without path segments).
4 + */
5 +export function getExtensionFromMimeType(mimeType: string): string {
6 + const mimeToExt: Record<string, string> = {
7 + 'text/plain': 'txt',
8 + 'text/html': 'html',
9 + 'text/css': 'css',
10 + 'text/javascript': 'js',
11 + 'application/json': 'json',
12 + 'application/xml': 'xml',
13 + 'application/pdf': 'pdf',
14 + 'application/zip': 'zip',
15 + 'application/x-zip-compressed': 'zip',
16 + 'application/gzip': 'gz',
17 + 'application/octet-stream': 'bin',
18 + 'application/x-tar': 'tar',
19 + 'application/msword': 'doc',
20 + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
21 + 'application/vnd.ms-excel': 'xls',
22 + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
23 + 'application/vnd.ms-powerpoint': 'ppt',
24 + 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
25 + 'image/jpeg': 'jpg',
26 + 'image/jpg': 'jpg',
27 + 'image/png': 'png',
28 + 'image/gif': 'gif',
29 + 'image/svg+xml': 'svg',
30 + 'image/webp': 'webp',
31 + 'image/bmp': 'bmp',
32 + 'image/tiff': 'tiff',
33 + 'audio/mpeg': 'mp3',
34 + 'audio/wav': 'wav',
35 + 'audio/ogg': 'ogg',
36 + 'video/mp4': 'mp4',
37 + 'video/mpeg': 'mpeg',
38 + 'video/quicktime': 'mov',
39 + 'video/x-msvideo': 'avi',
40 + 'video/webm': 'webm',
41 + };
42 +
43 + const cleanMimeType = mimeType.split(';')[0].toLowerCase().trim();
44 +
45 + if (mimeToExt[cleanMimeType]) {
46 + return mimeToExt[cleanMimeType];
47 + }
48 +
49 + const parts = cleanMimeType.split('/');
50 + if (parts.length === 2) {
51 + const subtype = parts[1].toLowerCase();
52 +
53 + if (subtype.includes('+')) {
54 + const plusParts = subtype.split('+');
55 + const prefix = plusParts[0];
56 + const suffix = plusParts[plusParts.length - 1];
57 +
58 + const knownPrefixes = ['svg', 'atom', 'rss'];
59 + if (knownPrefixes.includes(prefix)) {
60 + return prefix;
61 + }
62 +
63 + const structuredSuffixes = ['json', 'xml', 'yaml', 'zip', 'gzip'];
64 + if (structuredSuffixes.includes(suffix)) {
65 + return suffix;
66 + }
67 +
68 + return suffix;
69 + }
70 +
71 + return subtype || 'txt';
72 + }
73 +
74 + return 'bin';
75 +}
ts/packages/core/src/utils/transformers/toolRouterResponseTransform.ts new
+160
@@ -0,0 +1,160 @@
1 +/**
2 + * Transforms snake_case Tool Router API responses to camelCase for SDK consumers.
3 + */
4 +
5 +interface RawSearchResult {
6 + index: number;
7 + use_case: string;
8 + primary_tool_slugs: string[];
9 + related_tool_slugs: string[];
10 + toolkits: string[];
11 + difficulty?: string;
12 + error?: string | null;
13 + execution_guidance?: string;
14 + known_pitfalls?: string[];
15 + memory?: Record<string, string[]>;
16 + plan_id?: string;
17 + recommended_plan_steps?: string[];
18 + reference_workbench_snippets?: Array<{ code: string; description: string }>;
19 +}
20 +
21 +interface RawSearchSession {
22 + id: string;
23 + generate_id: boolean;
24 + instructions: string;
25 +}
26 +
27 +interface RawSearchTimeInfo {
28 + current_time_utc: string;
29 + current_time_utc_epoch_seconds: number;
30 + message: string;
31 +}
32 +
33 +interface RawToolSchema {
34 + tool_slug: string;
35 + toolkit: string;
36 + description?: string;
37 + hasFullSchema?: boolean;
38 + input_schema?: Record<string, unknown>;
39 + output_schema?: Record<string, unknown>;
40 + schemaRef?: {
41 + args: { tool_slugs: string[] };
42 + message: string;
43 + tool: string;
44 + };
45 +}
46 +
47 +interface RawToolkitConnectionStatus {
48 + toolkit: string;
49 + description: string;
50 + has_active_connection: boolean;
51 + status_message: string;
52 + connection_details?: Record<string, unknown>;
53 + current_user_info?: Record<string, unknown>;
54 +}
55 +
56 +interface RawSearchResponse {
57 + success: boolean;
58 + error: string | null;
59 + results: RawSearchResult[];
60 + tool_schemas: Record<string, RawToolSchema>;
61 + toolkit_connection_statuses: RawToolkitConnectionStatus[];
62 + next_steps_guidance: string[];
63 + session: RawSearchSession;
64 + time_info: RawSearchTimeInfo;
65 +}
66 +
67 +interface RawExecuteResponse {
68 + data: Record<string, unknown>;
69 + error: string | null;
70 + log_id: string;
71 +}
72 +
73 +function transformSearchResult(raw: RawSearchResult) {
74 + return {
75 + index: raw.index,
76 + useCase: raw.use_case,
77 + primaryToolSlugs: raw.primary_tool_slugs,
78 + relatedToolSlugs: raw.related_tool_slugs,
79 + toolkits: raw.toolkits,
80 + difficulty: raw.difficulty,
81 + error: raw.error,
82 + executionGuidance: raw.execution_guidance,
83 + knownPitfalls: raw.known_pitfalls,
84 + memory: raw.memory,
85 + planId: raw.plan_id,
86 + recommendedPlanSteps: raw.recommended_plan_steps,
87 + referenceWorkbenchSnippets: raw.reference_workbench_snippets,
88 + };
89 +}
90 +
91 +function transformToolSchema(raw: RawToolSchema) {
92 + return {
93 + toolSlug: raw.tool_slug,
94 + toolkit: raw.toolkit,
95 + description: raw.description,
96 + hasFullSchema: raw.hasFullSchema,
97 + inputSchema: raw.input_schema,
98 + outputSchema: raw.output_schema,
99 + schemaRef: raw.schemaRef
100 + ? {
101 + args: { toolSlugs: raw.schemaRef.args.tool_slugs },
102 + message: raw.schemaRef.message,
103 + tool: raw.schemaRef.tool,
104 + }
105 + : undefined,
106 + };
107 +}
108 +
109 +function transformToolkitConnectionStatus(raw: RawToolkitConnectionStatus) {
110 + return {
111 + toolkit: raw.toolkit,
112 + description: raw.description,
113 + hasActiveConnection: raw.has_active_connection,
114 + statusMessage: raw.status_message,
115 + connectionDetails: raw.connection_details,
116 + currentUserInfo: raw.current_user_info,
117 + };
118 +}
119 +
120 +/**
121 + * Transforms a raw session search API response to camelCase.
122 + */
123 +export function transformSearchResponse(raw: RawSearchResponse) {
124 + const toolSchemas: Record<string, ReturnType<typeof transformToolSchema>> = {};
125 + for (const [slug, schema] of Object.entries(raw.tool_schemas)) {
126 + toolSchemas[slug] = transformToolSchema(schema);
127 + }
128 +
129 + return {
130 + success: raw.success,
131 + error: raw.error,
132 + results: raw.results.map(transformSearchResult),
133 + toolSchemas,
134 + toolkitConnectionStatuses: raw.toolkit_connection_statuses.map(
135 + transformToolkitConnectionStatus
136 + ),
137 + nextStepsGuidance: raw.next_steps_guidance,
138 + session: {
139 + id: raw.session.id,
140 + generateId: raw.session.generate_id,
141 + instructions: raw.session.instructions,
142 + },
143 + timeInfo: {
144 + currentTimeUtc: raw.time_info.current_time_utc,
145 + currentTimeUtcEpochSeconds: raw.time_info.current_time_utc_epoch_seconds,
146 + message: raw.time_info.message,
147 + },
148 + };
149 +}
150 +
151 +/**
152 + * Transforms a raw session execute API response to camelCase.
153 + */
154 +export function transformExecuteResponse(raw: RawExecuteResponse) {
155 + return {
156 + data: raw.data,
157 + error: raw.error,
158 + logId: raw.log_id,
159 + };
160 +}
ts/packages/core/test/errors/RemoteFileErrors.test.ts new
+43
@@ -0,0 +1,43 @@
1 +import { describe, it, expect } from 'vitest';
2 +import { ComposioError } from '../../src/errors/ComposioError';
3 +import { RemoteFileDownloadError, RemoteFileErrorCodes } from '../../src/errors/RemoteFileErrors';
4 +
5 +describe('RemoteFileDownloadError', () => {
6 + it('should create error with default message', () => {
7 + const err = new RemoteFileDownloadError();
8 + expect(err.message).toBe('Failed to download remote file');
9 + expect(err.name).toBe('RemoteFileDownloadError');
10 + expect(err.code).toContain(RemoteFileErrorCodes.DOWNLOAD_FAILED);
11 + });
12 +
13 + it('should create error with custom message and options', () => {
14 + const err = new RemoteFileDownloadError('Download failed: 404', {
15 + statusCode: 404,
16 + statusText: 'Not Found',
17 + downloadUrl: 'https://example.com/file',
18 + mountRelativePath: 'output/report.pdf',
19 + filename: 'report.pdf',
20 + });
21 +
22 + expect(err.message).toBe('Download failed: 404');
23 + expect(err.code).toContain(RemoteFileErrorCodes.DOWNLOAD_FAILED);
24 + expect(err.meta).toMatchObject({
25 + statusCode: 404,
26 + statusText: 'Not Found',
27 + downloadUrl: 'https://example.com/file',
28 + mountRelativePath: 'output/report.pdf',
29 + filename: 'report.pdf',
30 + });
31 + expect(err.possibleFixes).toBeDefined();
32 + expect(err.possibleFixes).toContain(
33 + 'Verify the download URL has not expired (check expiresAt)'
34 + );
35 + });
36 +
37 + it('should extend ComposioError', () => {
38 + const err = new RemoteFileDownloadError();
39 + expect(err).toBeInstanceOf(Error);
40 + expect(err).toBeInstanceOf(ComposioError);
41 + expect(err).toBeInstanceOf(RemoteFileDownloadError);
42 + });
43 +});
ts/packages/core/test/models/RemoteFile.test.ts new
+168
@@ -0,0 +1,168 @@
1 +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2 +import { RemoteFile } from '../../src/models/RemoteFile';
3 +import { RemoteFileDownloadError, ValidationError } from '../../src/errors';
4 +
5 +describe('RemoteFile', () => {
6 + const validCamelCaseData = {
7 + expiresAt: '2025-12-31T23:59:59.000Z',
8 + mountRelativePath: 'output/report.pdf',
9 + sandboxMountPrefix: '/mnt/files',
10 + downloadUrl: 'https://s3.example.com/presigned-url',
11 + };
12 +
13 + const validSnakeCaseData = {
14 + expires_at: '2025-12-31T23:59:59.000Z',
15 + mount_relative_path: 'output/report.pdf',
16 + sandbox_mount_prefix: '/mnt/files',
17 + download_url: 'https://s3.example.com/presigned-url',
18 + };
19 +
20 + let originalFetch: typeof globalThis.fetch;
21 +
22 + beforeEach(() => {
23 + originalFetch = globalThis.fetch;
24 + });
25 +
26 + afterEach(() => {
27 + globalThis.fetch = originalFetch;
28 + });
29 +
30 + describe('constructor', () => {
31 + it('should create instance with valid camelCase data', () => {
32 + const file = new RemoteFile(validCamelCaseData);
33 + expect(file.expiresAt).toBe(validCamelCaseData.expiresAt);
34 + expect(file.mountRelativePath).toBe(validCamelCaseData.mountRelativePath);
35 + expect(file.sandboxMountPrefix).toBe(validCamelCaseData.sandboxMountPrefix);
36 + expect(file.downloadUrl).toBe(validCamelCaseData.downloadUrl);
37 + });
38 + });
39 +
40 + describe('parse', () => {
41 + it('should parse snake_case API response and return RemoteFile', () => {
42 + const file = RemoteFile.parse(validSnakeCaseData);
43 + expect(file).toBeInstanceOf(RemoteFile);
44 + expect(file.expiresAt).toBe(validSnakeCaseData.expires_at);
45 + expect(file.mountRelativePath).toBe(validSnakeCaseData.mount_relative_path);
46 + expect(file.downloadUrl).toBe(validSnakeCaseData.download_url);
47 + });
48 +
49 + it('should throw ValidationError for invalid data', () => {
50 + expect(() => RemoteFile.parse({})).toThrow(ValidationError);
51 + expect(() => RemoteFile.parse({ expires_at: 'x' })).toThrow(ValidationError);
52 + expect(() => RemoteFile.parse(null)).toThrow(ValidationError);
53 + });
54 + });
55 +
56 + describe('filename', () => {
57 + it('should return basename of mount path', () => {
58 + const file = new RemoteFile(validCamelCaseData);
59 + expect(file.filename).toBe('report.pdf');
60 + });
61 +
62 + it('should handle nested path', () => {
63 + const file = new RemoteFile({
64 + ...validCamelCaseData,
65 + mountRelativePath: 'output/subdir/data.json',
66 + });
67 + expect(file.filename).toBe('data.json');
68 + });
69 + });
70 +
71 + describe('buffer', () => {
72 + it('should fetch and return file content as Uint8Array', async () => {
73 + const content = new Uint8Array([1, 2, 3]);
74 + globalThis.fetch = vi.fn().mockResolvedValue({
75 + ok: true,
76 + arrayBuffer: () => Promise.resolve(content.buffer),
77 + });
78 +
79 + const file = new RemoteFile(validCamelCaseData);
80 + const result = await file.buffer();
81 +
82 + expect(globalThis.fetch).toHaveBeenCalledWith(validCamelCaseData.downloadUrl);
83 + expect(result).toBeInstanceOf(Uint8Array);
84 + expect(result).toEqual(content);
85 + });
86 +
87 + it('should throw RemoteFileDownloadError when fetch fails', async () => {
88 + globalThis.fetch = vi.fn().mockResolvedValue({
89 + ok: false,
90 + status: 404,
91 + statusText: 'Not Found',
92 + });
93 +
94 + const file = new RemoteFile(validCamelCaseData);
95 +
96 + await expect(file.buffer()).rejects.toThrow(RemoteFileDownloadError);
97 + await expect(file.buffer()).rejects.toMatchObject({
98 + name: 'RemoteFileDownloadError',
99 + message: expect.stringContaining('404'),
100 + });
101 + });
102 + });
103 +
104 + describe('text', () => {
105 + it('should fetch and return file content as UTF-8 string', async () => {
106 + const content = 'Hello, World!';
107 + globalThis.fetch = vi.fn().mockResolvedValue({
108 + ok: true,
109 + arrayBuffer: () => Promise.resolve(new TextEncoder().encode(content).buffer),
110 + });
111 +
112 + const file = new RemoteFile(validCamelCaseData);
113 + const result = await file.text();
114 +
115 + expect(result).toBe(content);
116 + });
117 + });
118 +
119 + describe('blob', () => {
120 + it('should fetch and return file content as Blob', async () => {
121 + const blob = new Blob(['data']);
122 + globalThis.fetch = vi.fn().mockResolvedValue({
123 + ok: true,
124 + blob: () => Promise.resolve(blob),
125 + });
126 +
127 + const file = new RemoteFile(validCamelCaseData);
128 + const result = await file.blob();
129 +
130 + expect(result).toBe(blob);
131 + });
132 +
133 + it('should throw RemoteFileDownloadError when fetch fails', async () => {
134 + globalThis.fetch = vi.fn().mockResolvedValue({
135 + ok: false,
136 + status: 403,
137 + statusText: 'Forbidden',
138 + });
139 +
140 + const file = new RemoteFile(validCamelCaseData);
141 +
142 + await expect(file.blob()).rejects.toThrow(RemoteFileDownloadError);
143 + });
144 + });
145 +
146 + describe('save', () => {
147 + it('should save file to specified path when platform supports file system', async () => {
148 + const content = new Uint8Array([1, 2, 3]);
149 + globalThis.fetch = vi.fn().mockResolvedValue({
150 + ok: true,
151 + arrayBuffer: () => Promise.resolve(content.buffer),
152 + });
153 +
154 + const file = new RemoteFile(validCamelCaseData);
155 + const { platform } = await import('../../src/platform/node');
156 + const { join } = await import('node:path');
157 + const { tmpdir } = await import('node:os');
158 + const savePath = join(tmpdir(), `composio-remote-file-test-${Date.now()}.pdf`);
159 +
160 + const result = await file.save(savePath);
161 +
162 + expect(result).toBe(savePath);
163 + expect(platform.existsSync(savePath)).toBe(true);
164 + const written = platform.readFileSync(savePath) as Uint8Array;
165 + expect(new Uint8Array(written)).toEqual(content);
166 + });
167 + });
168 +});
ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts new
+414
@@ -0,0 +1,414 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import { ToolRouterSessionFilesMount } from '../../src/models/ToolRouterSessionFileMount';
3 +import { ValidationError } from '../../src/errors';
4 +import { DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID } from '../../src/utils/constants';
5 +
6 +const sessionId = 'trs_session_123';
7 +
8 +const createMockClient = () => ({
9 + toolRouter: {
10 + session: {
11 + files: {
12 + list: vi.fn(),
13 + createUploadURL: vi.fn(),
14 + createDownloadURL: vi.fn(),
15 + delete: vi.fn(),
16 + },
17 + },
18 + },
19 +});
20 +
21 +describe('ToolRouterSessionFilesMount', () => {
22 + let mockClient: ReturnType<typeof createMockClient>;
23 + let filesMount: ToolRouterSessionFilesMount;
24 +
25 + beforeEach(() => {
26 + vi.clearAllMocks();
27 + mockClient = createMockClient();
28 + filesMount = new ToolRouterSessionFilesMount(mockClient as any, sessionId);
29 + });
30 +
31 + describe('list', () => {
32 + it('should call list with default mountId and no path', async () => {
33 + mockClient.toolRouter.session.files.list.mockResolvedValueOnce({ items: [] });
34 +
35 + const result = await filesMount.list();
36 +
37 + expect(mockClient.toolRouter.session.files.list).toHaveBeenCalledWith(
38 + DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
39 + {
40 + session_id: sessionId,
41 + mount_relative_prefix: undefined,
42 + cursor: undefined,
43 + limit: undefined,
44 + }
45 + );
46 + expect(result).toEqual({ items: [], nextCursor: undefined });
47 + });
48 +
49 + it('should call list with custom path and mountId (strips leading slash for API)', async () => {
50 + mockClient.toolRouter.session.files.list.mockResolvedValueOnce({ items: [] });
51 +
52 + await filesMount.list({
53 + path: '/documents',
54 + mountId: 'custom-mount',
55 + });
56 +
57 + expect(mockClient.toolRouter.session.files.list).toHaveBeenCalledWith('custom-mount', {
58 + session_id: sessionId,
59 + mount_relative_prefix: 'documents',
60 + cursor: undefined,
61 + limit: undefined,
62 + });
63 + });
64 +
65 + it('should return transformed response with items and nextCursor', async () => {
66 + const apiResponse = {
67 + items: [
68 + {
69 + last_modified: '2025-03-09T12:00:00.000Z',
70 + mount_relative_path: 'file.txt',
71 + sandbox_mount_prefix: '/mnt/files',
72 + size: 42,
73 + },
74 + ],
75 + next_cursor: 'cursor_abc123',
76 + };
77 + mockClient.toolRouter.session.files.list.mockResolvedValueOnce(apiResponse);
78 +
79 + const result = await filesMount.list();
80 +
81 + expect(result).toEqual({
82 + items: [
83 + {
84 + lastModified: '2025-03-09T12:00:00.000Z',
85 + mountRelativePath: 'file.txt',
86 + sandboxMountPrefix: '/mnt/files',
87 + size: 42,
88 + },
89 + ],
90 + nextCursor: 'cursor_abc123',
91 + });
92 + });
93 +
94 + it('should pass cursor and limit for pagination (path / omitted for root)', async () => {
95 + mockClient.toolRouter.session.files.list.mockResolvedValueOnce({ items: [] });
96 +
97 + await filesMount.list({
98 + path: '/',
99 + cursor: 'cursor_page2',
100 + limit: 25,
101 + });
102 +
103 + expect(mockClient.toolRouter.session.files.list).toHaveBeenCalledWith(
104 + DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
105 + {
106 + session_id: sessionId,
107 + mount_relative_prefix: undefined,
108 + cursor: 'cursor_page2',
109 + limit: 25,
110 + }
111 + );
112 + });
113 + });
114 +
115 + describe('download', () => {
116 + const createDownloadURLResponse = {
117 + expires_at: '2025-12-31T23:59:59.000Z',
118 + mount_relative_path: 'output/report.pdf',
119 + sandbox_mount_prefix: '/mnt/files',
120 + download_url: 'https://s3.example.com/presigned',
121 + };
122 +
123 + it('should call createDownloadURL and return RemoteFile', async () => {
124 + mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce(
125 + createDownloadURLResponse
126 + );
127 +
128 + const result = await filesMount.download('/output/report.pdf');
129 +
130 + expect(mockClient.toolRouter.session.files.createDownloadURL).toHaveBeenCalledWith(
131 + DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
132 + {
133 + session_id: sessionId,
134 + mount_relative_path: '/output/report.pdf',
135 + }
136 + );
137 + expect(result).toBeDefined();
138 + expect(result.mountRelativePath).toBe('output/report.pdf');
139 + expect(result.downloadUrl).toBe('https://s3.example.com/presigned');
140 + });
141 +
142 + it('should use custom mountId when provided', async () => {
143 + mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce(
144 + createDownloadURLResponse
145 + );
146 +
147 + await filesMount.download('/output/report.pdf', { mountId: 'exports' });
148 +
149 + expect(mockClient.toolRouter.session.files.createDownloadURL).toHaveBeenCalledWith(
150 + 'exports',
151 + {
152 + session_id: sessionId,
153 + mount_relative_path: '/output/report.pdf',
154 + }
155 + );
156 + });
157 + });
158 +
159 + describe('delete', () => {
160 + const deleteResponse = {
161 + mount_relative_path: '/temp/cache.json',
162 + sandbox_mount_prefix: '/mnt/files',
163 + };
164 +
165 + it('should call delete and return parsed response', async () => {
166 + mockClient.toolRouter.session.files.delete.mockResolvedValueOnce(deleteResponse);
167 +
168 + const result = await filesMount.delete('/temp/cache.json');
169 +
170 + expect(mockClient.toolRouter.session.files.delete).toHaveBeenCalledWith(
171 + DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
172 + {
173 + session_id: sessionId,
174 + mount_relative_path: '/temp/cache.json',
175 + }
176 + );
177 + expect(result).toEqual({
178 + mountRelativePath: '/temp/cache.json',
179 + sandboxMountPrefix: '/mnt/files',
180 + });
181 + });
182 +
183 + it('should use custom mountId when provided', async () => {
184 + mockClient.toolRouter.session.files.delete.mockResolvedValueOnce(deleteResponse);
185 +
186 + await filesMount.delete('/old-backup', { mountId: 'backups' });
187 +
188 + expect(mockClient.toolRouter.session.files.delete).toHaveBeenCalledWith('backups', {
189 + session_id: sessionId,
190 + mount_relative_path: '/old-backup',
191 + });
192 + });
193 + });
194 +
195 + describe('upload', () => {
196 + const mountRelativePath = 'composio-upload-test.txt';
197 + const createUploadURLResponse = {
198 + upload_url: 'https://s3.example.com/upload',
199 + mount_relative_path: mountRelativePath,
200 + sandbox_mount_prefix: '/mnt/files',
201 + expires_at: '2025-12-31T23:59:59.000Z',
202 + };
203 +
204 + const createDownloadURLResponse = {
205 + download_url: 'https://s3.example.com/presigned',
206 + mount_relative_path: mountRelativePath,
207 + sandbox_mount_prefix: '/mnt/files',
208 + expires_at: '2025-12-31T23:59:59.000Z',
209 + };
210 +
211 + beforeEach(() => {
212 + globalThis.fetch = vi.fn().mockImplementation((url: string, init?: RequestInit) => {
213 + if (init?.method === 'PUT') {
214 + return Promise.resolve({ ok: true });
215 + }
216 + return Promise.reject(new Error('Unexpected fetch'));
217 + }) as unknown as typeof fetch;
218 + });
219 +
220 + it('should upload local file and return RemoteFile', async () => {
221 + const { platform } = await import('../../src/platform/node');
222 + const { join } = await import('node:path');
223 + const { tmpdir } = await import('node:os');
224 + const testFilePath = join(tmpdir(), 'composio-upload-test.txt');
225 + platform.writeFileSync(testFilePath, 'test content', 'utf8');
226 +
227 + mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce(
228 + createUploadURLResponse
229 + );
230 + mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce(
231 + createDownloadURLResponse
232 + );
233 +
234 + const result = await filesMount.upload(testFilePath);
235 +
236 + expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(
237 + DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
238 + {
239 + session_id: sessionId,
240 + mount_relative_path: 'composio-upload-test.txt',
241 + mimetype: 'application/octet-stream',
242 + }
243 + );
244 + expect(mockClient.toolRouter.session.files.createDownloadURL).toHaveBeenCalledWith(
245 + DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
246 + {
247 + session_id: sessionId,
248 + mount_relative_path: mountRelativePath,
249 + }
250 + );
251 + expect(result.mountRelativePath).toBe(mountRelativePath);
252 + expect(result.downloadUrl).toBe('https://s3.example.com/presigned');
253 + });
254 +
255 + it('should handle upload response body wrapper', async () => {
256 + const { platform } = await import('../../src/platform/node');
257 + const { join } = await import('node:path');
258 + const { tmpdir } = await import('node:os');
259 + const testFilePath = join(tmpdir(), 'composio-upload-test.txt');
260 + platform.writeFileSync(testFilePath, 'test content', 'utf8');
261 +
262 + mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
263 + url: 'https://api.example.com/upload_url',
264 + status: 201,
265 + body: createUploadURLResponse,
266 + });
267 + mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce(
268 + createDownloadURLResponse
269 + );
270 +
271 + const result = await filesMount.upload(testFilePath);
272 +
273 + expect(result.mountRelativePath).toBe(mountRelativePath);
274 + expect(result.downloadUrl).toBe('https://s3.example.com/presigned');
275 + });
276 +
277 + it('should upload native File object', async () => {
278 + const file = new File([new TextEncoder().encode('hello')], 'greeting.txt', {
279 + type: 'text/plain',
280 + });
281 +
282 + mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
283 + ...createUploadURLResponse,
284 + mount_relative_path: 'greeting.txt',
285 + });
286 + mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({
287 + ...createDownloadURLResponse,
288 + mount_relative_path: 'greeting.txt',
289 + });
290 +
291 + const result = await filesMount.upload(file);
292 +
293 + expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(
294 + DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
295 + {
296 + session_id: sessionId,
297 + mount_relative_path: 'greeting.txt',
298 + mimetype: 'text/plain',
299 + }
300 + );
301 + expect(result.mountRelativePath).toBe('greeting.txt');
302 + });
303 +
304 + it('should upload File with custom remotePath', async () => {
305 + const file = new File([new Uint8Array([1, 2, 3])], 'original.bin', {
306 + type: 'application/octet-stream',
307 + });
308 +
309 + mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
310 + ...createUploadURLResponse,
311 + mount_relative_path: 'custom-name.bin',
312 + });
313 + mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({
314 + ...createDownloadURLResponse,
315 + mount_relative_path: 'custom-name.bin',
316 + });
317 +
318 + const result = await filesMount.upload(file, { remotePath: 'custom-name.bin' });
319 +
320 + expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(
321 + DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
322 + {
323 + session_id: sessionId,
324 + mount_relative_path: 'custom-name.bin',
325 + mimetype: 'application/octet-stream',
326 + }
327 + );
328 + expect(result.mountRelativePath).toBe('custom-name.bin');
329 + });
330 +
331 + it('should upload raw buffer with remotePath and mimetype', async () => {
332 + const buffer = new TextEncoder().encode('{"key":"value"}');
333 +
334 + mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
335 + ...createUploadURLResponse,
336 + mount_relative_path: 'data.json',
337 + });
338 + mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({
339 + ...createDownloadURLResponse,
340 + mount_relative_path: 'data.json',
341 + });
342 +
343 + const result = await filesMount.upload(buffer, {
344 + remotePath: 'data.json',
345 + mimetype: 'application/json',
346 + });
347 +
348 + expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(
349 + DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
350 + {
351 + session_id: sessionId,
352 + mount_relative_path: 'data.json',
353 + mimetype: 'application/json',
354 + }
355 + );
356 + expect(result.mountRelativePath).toBe('data.json');
357 + });
358 +
359 + it('should return mountRelativePath from API response when it differs from requested path', async () => {
360 + const buffer = new Uint8Array([0x89, 0x50, 0x4e, 0x47]); // PNG signature
361 +
362 + mockClient.toolRouter.session.files.createUploadURL.mockResolvedValueOnce({
363 + ...createUploadURLResponse,
364 + mount_relative_path: 'upload-7949b409.jpg', // API returns different path
365 + });
366 + mockClient.toolRouter.session.files.createDownloadURL.mockResolvedValueOnce({
367 + ...createDownloadURLResponse,
368 + mount_relative_path: 'upload-7949b409.jpg',
369 + });
370 +
371 + const result = await filesMount.upload(buffer, { remotePath: 'file.png' });
372 +
373 + expect(result.mountRelativePath).toBe('upload-7949b409.jpg');
374 + });
375 +
376 + it('should throw when buffer is provided without mimetype or remotePath', async () => {
377 + const buffer = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
378 +
379 + await expect(filesMount.upload(buffer)).rejects.toThrow(
380 + 'When passing a buffer, either mimetype or remotePath (filename) is required'
381 + );
382 + });
383 +
384 + it('should upload ArrayBuffer with mimetype when remotePath omitted', async () => {
385 + const buffer = new ArrayBuffer(8);
386 + new DataView(buffer).setUint32(0, 0xdeadbeef);
387 +
388 + mockClient.toolRouter.session.files.createUploadURL.mockImplementation((_, params) =>
389 + Promise.resolve({
390 + ...createUploadURLResponse,
391 + mount_relative_path: params.mount_relative_path,
392 + })
393 + );
394 + mockClient.toolRouter.session.files.createDownloadURL.mockImplementation((_, params) =>
395 + Promise.resolve({
396 + ...createDownloadURLResponse,
397 + mount_relative_path: params.mount_relative_path,
398 + })
399 + );
400 +
401 + const result = await filesMount.upload(buffer, { mimetype: 'application/octet-stream' });
402 +
403 + expect(mockClient.toolRouter.session.files.createUploadURL).toHaveBeenCalledWith(
404 + DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID,
405 + expect.objectContaining({
406 + session_id: sessionId,
407 + mimetype: 'application/octet-stream',
408 + mount_relative_path: expect.stringMatching(/^upload-.+\.bin$/),
409 + })
410 + );
411 + expect(result.mountRelativePath).toMatch(/^upload-.+\.bin$/);
412 + });
413 + });
414 +});
ts/packages/core/test/models/toolRouter.test.ts
+145 -1
@@ -5,7 +5,7 @@ import { telemetry } from '../../src/telemetry/Telemetry';
5 import { MockProvider } from '../utils/mocks/provider.mock';
6 import { Tools } from '../../src/models/Tools';
7 import { ConnectedAccountStatuses } from '../../src/types/connectedAccounts.types';
8 -import { ToolRouterCreateSessionConfig, ToolRouterSession } from '../../src/types/toolRouter.types';
8 +import { ToolRouterCreateSessionConfig, Session } from '../../src/types/toolRouter.types';
9
10 // Mock dependencies
11 vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -35,6 +35,8 @@ const createMockClient = () => ({
35 link: vi.fn(),
36 toolkits: vi.fn(),
37 executeMeta: vi.fn(),
38 + search: vi.fn(),
39 + execute: vi.fn(),
40 },
41 },
42 tools: {
@@ -1774,6 +1776,148 @@ describe('ToolRouter', () => {
1776 });
1777 });
1778
1779 + describe('search function', () => {
1780 + const userId = 'user_123';
1781 + const sessionId = 'session_123';
1782 +
1783 + const mockSearchResponse = {
1784 + success: true,
1785 + error: null,
1786 + results: [
1787 + {
1788 + index: 1,
1789 + use_case: 'send emails',
1790 + primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
1791 + related_tool_slugs: [],
1792 + toolkits: ['gmail'],
1793 + },
1794 + ],
1795 + tool_schemas: {
1796 + GMAIL_SEND_EMAIL: {
1797 + tool_slug: 'GMAIL_SEND_EMAIL',
1798 + toolkit: 'gmail',
1799 + description: 'Send an email',
1800 + hasFullSchema: true,
1801 + input_schema: {},
1802 + output_schema: {},
1803 + },
1804 + },
1805 + toolkit_connection_statuses: [
1806 + {
1807 + toolkit: 'gmail',
1808 + description: 'Gmail',
1809 + has_active_connection: false,
1810 + status_message: 'No connection',
1811 + },
1812 + ],
1813 + next_steps_guidance: ['Connect Gmail'],
1814 + session: {
1815 + id: 'trs_123',
1816 + generate_id: false,
1817 + instructions: 'Reuse session',
1818 + },
1819 + time_info: {
1820 + current_time_utc: '2025-03-09T12:00:00.000Z',
1821 + current_time_utc_epoch_seconds: 1741521600,
1822 + message: 'UTC',
1823 + },
1824 + };
1825 +
1826 + it('should call search with correct params and return camelCase response', async () => {
1827 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1828 + mockClient.toolRouter.session.search.mockResolvedValueOnce(mockSearchResponse);
1829 +
1830 + const session = await toolRouter.create(userId);
1831 + const result = await session.search({ query: 'send emails' });
1832 +
1833 + expect(mockClient.toolRouter.session.search).toHaveBeenCalledWith(sessionId, {
1834 + queries: [{ use_case: 'send emails' }],
1835 + });
1836 + expect(result.success).toBe(true);
1837 + expect(result.results[0].useCase).toBe('send emails');
1838 + expect(result.results[0].primaryToolSlugs).toEqual(['GMAIL_SEND_EMAIL']);
1839 + expect(result.toolSchemas.GMAIL_SEND_EMAIL.toolSlug).toBe('GMAIL_SEND_EMAIL');
1840 + expect(result.nextStepsGuidance).toEqual(['Connect Gmail']);
1841 + expect(result.session.generateId).toBe(false);
1842 + expect(result.timeInfo.currentTimeUtcEpochSeconds).toBe(1741521600);
1843 + });
1844 +
1845 + it('should pass toolkits filter when provided', async () => {
1846 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1847 + mockClient.toolRouter.session.search.mockResolvedValueOnce(mockSearchResponse);
1848 +
1849 + const session = await toolRouter.create(userId);
1850 + await session.search({ query: 'send emails', toolkits: ['gmail', 'slack'] });
1851 +
1852 + expect(mockClient.toolRouter.session.search).toHaveBeenCalledWith(sessionId, {
1853 + queries: [{ use_case: 'send emails' }],
1854 + toolkits: ['gmail', 'slack'],
1855 + });
1856 + });
1857 +
1858 + it('should propagate search API errors', async () => {
1859 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1860 + mockClient.toolRouter.session.search.mockRejectedValueOnce(new Error('Search failed'));
1861 +
1862 + const session = await toolRouter.create(userId);
1863 +
1864 + await expect(session.search({ query: 'send emails' })).rejects.toThrow('Search failed');
1865 + });
1866 + });
1867 +
1868 + describe('execute function', () => {
1869 + const userId = 'user_123';
1870 + const sessionId = 'session_123';
1871 +
1872 + const mockExecuteResponse = {
1873 + data: { tool_slug: 'GMAIL_SEND_EMAIL', id: 'msg_123' },
1874 + error: null,
1875 + log_id: 'log_abc',
1876 + };
1877 +
1878 + it('should call execute with correct params and return camelCase response', async () => {
1879 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1880 + mockClient.toolRouter.session.execute.mockResolvedValueOnce(mockExecuteResponse);
1881 +
1882 + const session = await toolRouter.create(userId);
1883 + const result = await session.execute('GMAIL_SEND_EMAIL', {
1884 + to: 'user@example.com',
1885 + subject: 'Hi',
1886 + body: 'Hello',
1887 + });
1888 +
1889 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
1890 + tool_slug: 'GMAIL_SEND_EMAIL',
1891 + arguments: { to: 'user@example.com', subject: 'Hi', body: 'Hello' },
1892 + });
1893 + expect(result.data).toEqual({ tool_slug: 'GMAIL_SEND_EMAIL', id: 'msg_123' });
1894 + expect(result.error).toBeNull();
1895 + expect(result.logId).toBe('log_abc');
1896 + });
1897 +
1898 + it('should propagate execute API errors', async () => {
1899 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1900 + mockClient.toolRouter.session.execute.mockRejectedValueOnce(new Error('Execute failed'));
1901 +
1902 + const session = await toolRouter.create(userId);
1903 +
1904 + await expect(session.execute('GMAIL_SEND_EMAIL')).rejects.toThrow('Execute failed');
1905 + });
1906 +
1907 + it('should default arguments to empty object when omitted', async () => {
1908 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1909 + mockClient.toolRouter.session.execute.mockResolvedValueOnce(mockExecuteResponse);
1910 +
1911 + const session = await toolRouter.create(userId);
1912 + await session.execute('HACKERNEWS_GET_USER');
1913 +
1914 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
1915 + tool_slug: 'HACKERNEWS_GET_USER',
1916 + arguments: {},
1917 + });
1918 + });
1919 + });
1920 +
1921 describe('tools function', () => {
1922 const userId = 'user_123';
1923 const sessionId = 'session_123';
ts/packages/core/test/utils/mime.test.ts new
+9
@@ -0,0 +1,9 @@
1 +import { describe, it, expect } from 'vitest';
2 +import { getExtensionFromMimeType } from '../../src/utils/mime';
3 +
4 +describe('getExtensionFromMimeType', () => {
5 + it('should return extension for known mimetype', () => {
6 + expect(getExtensionFromMimeType('image/png')).toBe('png');
7 + expect(getExtensionFromMimeType('application/pdf')).toBe('pdf');
8 + });
9 +});
ts/packages/core/test/utils/toolRouterResponseTransform.test.ts new
+164
@@ -0,0 +1,164 @@
1 +import { describe, it, expect } from 'vitest';
2 +import {
3 + transformSearchResponse,
4 + transformExecuteResponse,
5 +} from '../../src/utils/transformers/toolRouterResponseTransform';
6 +
7 +describe('toolRouterResponseTransform', () => {
8 + describe('transformSearchResponse', () => {
9 + it('should transform snake_case search response to camelCase', () => {
10 + const raw = {
11 + success: true,
12 + error: null,
13 + results: [
14 + {
15 + index: 1,
16 + use_case: 'send emails',
17 + primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
18 + related_tool_slugs: ['GMAIL_CREATE_DRAFT'],
19 + toolkits: ['gmail'],
20 + difficulty: 'easy',
21 + recommended_plan_steps: ['Step 1', 'Step 2'],
22 + },
23 + ],
24 + tool_schemas: {
25 + GMAIL_SEND_EMAIL: {
26 + tool_slug: 'GMAIL_SEND_EMAIL',
27 + toolkit: 'gmail',
28 + description: 'Send an email',
29 + hasFullSchema: true,
30 + input_schema: { to: { type: 'string' } },
31 + output_schema: { id: { type: 'string' } },
32 + },
33 + },
34 + toolkit_connection_statuses: [
35 + {
36 + toolkit: 'gmail',
37 + description: 'Gmail toolkit',
38 + has_active_connection: true,
39 + status_message: 'Connected',
40 + },
41 + ],
42 + next_steps_guidance: ['Connect Gmail if needed'],
43 + session: {
44 + id: 'trs_123',
45 + generate_id: false,
46 + instructions: 'Reuse this session id',
47 + },
48 + time_info: {
49 + current_time_utc: '2025-03-09T12:00:00.000Z',
50 + current_time_utc_epoch_seconds: 1741521600,
51 + message: 'UTC time',
52 + },
53 + };
54 +
55 + const result = transformSearchResponse(raw);
56 +
57 + expect(result.success).toBe(true);
58 + expect(result.error).toBeNull();
59 + expect(result.results).toHaveLength(1);
60 + expect(result.results[0]).toEqual({
61 + index: 1,
62 + useCase: 'send emails',
63 + primaryToolSlugs: ['GMAIL_SEND_EMAIL'],
64 + relatedToolSlugs: ['GMAIL_CREATE_DRAFT'],
65 + toolkits: ['gmail'],
66 + difficulty: 'easy',
67 + recommendedPlanSteps: ['Step 1', 'Step 2'],
68 + });
69 + expect(result.toolSchemas).toHaveProperty('GMAIL_SEND_EMAIL');
70 + expect(result.toolSchemas.GMAIL_SEND_EMAIL).toEqual({
71 + toolSlug: 'GMAIL_SEND_EMAIL',
72 + toolkit: 'gmail',
73 + description: 'Send an email',
74 + hasFullSchema: true,
75 + inputSchema: { to: { type: 'string' } },
76 + outputSchema: { id: { type: 'string' } },
77 + });
78 + expect(result.toolkitConnectionStatuses[0]).toEqual({
79 + toolkit: 'gmail',
80 + description: 'Gmail toolkit',
81 + hasActiveConnection: true,
82 + statusMessage: 'Connected',
83 + });
84 + expect(result.nextStepsGuidance).toEqual(['Connect Gmail if needed']);
85 + expect(result.session).toEqual({
86 + id: 'trs_123',
87 + generateId: false,
88 + instructions: 'Reuse this session id',
89 + });
90 + expect(result.timeInfo).toEqual({
91 + currentTimeUtc: '2025-03-09T12:00:00.000Z',
92 + currentTimeUtcEpochSeconds: 1741521600,
93 + message: 'UTC time',
94 + });
95 + });
96 +
97 + it('should transform schemaRef with tool_slugs to toolSlugs', () => {
98 + const raw = {
99 + success: true,
100 + error: null,
101 + results: [],
102 + tool_schemas: {
103 + TOOL_X: {
104 + tool_slug: 'TOOL_X',
105 + toolkit: 'x',
106 + schemaRef: {
107 + args: { tool_slugs: ['TOOL_X'] },
108 + message: 'Fetch schema',
109 + tool: 'COMPOSIO_GET_TOOL_SCHEMAS',
110 + },
111 + },
112 + },
113 + toolkit_connection_statuses: [],
114 + next_steps_guidance: [],
115 + session: {
116 + id: 'trs_1',
117 + generate_id: true,
118 + instructions: 'Use session',
119 + },
120 + time_info: {
121 + current_time_utc: '2025-03-09T12:00:00.000Z',
122 + current_time_utc_epoch_seconds: 1741521600,
123 + message: 'UTC',
124 + },
125 + };
126 +
127 + const result = transformSearchResponse(raw);
128 + expect(result.toolSchemas.TOOL_X.schemaRef).toEqual({
129 + args: { toolSlugs: ['TOOL_X'] },
130 + message: 'Fetch schema',
131 + tool: 'COMPOSIO_GET_TOOL_SCHEMAS',
132 + });
133 + });
134 + });
135 +
136 + describe('transformExecuteResponse', () => {
137 + it('should transform snake_case execute response to camelCase', () => {
138 + const raw = {
139 + data: { tool_slug: 'GMAIL_SEND_EMAIL', id: 'msg_123' },
140 + error: null,
141 + log_id: 'log_abc',
142 + };
143 +
144 + const result = transformExecuteResponse(raw);
145 +
146 + expect(result.data).toEqual({ tool_slug: 'GMAIL_SEND_EMAIL', id: 'msg_123' });
147 + expect(result.error).toBeNull();
148 + expect(result.logId).toBe('log_abc');
149 + });
150 +
151 + it('should preserve error in execute response', () => {
152 + const raw = {
153 + data: {},
154 + error: 'Connection not found',
155 + log_id: 'log_err',
156 + };
157 +
158 + const result = transformExecuteResponse(raw);
159 +
160 + expect(result.error).toBe('Connection not found');
161 + expect(result.logId).toBe('log_err');
162 + });
163 + });
164 +});