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 21, 14:45 UTC
fix(ts): preprocess session file uploads
jkomyno committed
Aug 25, 2026 at 04:09 UTC
a61ad27940de36d7e88857359e319c9a0f733ec4
5 files changed
+456
-45
ts/packages/core/src/models/ToolRouterSession.ts
+36
-8
@@ -41,7 +41,11 @@ import { ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT, serializeExperimentalForWire } from
41
import { z } from 'zod/v3';
42
import { transform } from '../utils/transform';
43
import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';
44
-import { ComposioAclOnlyForSharedError, ValidationError } from '../errors';
44
+import {
45
+ ComposioAclOnlyForSharedError,
46
+ ComposioInvalidModifierError,
47
+ ValidationError,
48
+} from '../errors';
49
import { Tools } from './Tools';
50
import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';
51
import type {
@@ -51,7 +55,7 @@ import type {
55
RegisteredCustomTool,
56
RegisteredCustomToolkit,
57
} from '../types/customTool.types';
54
-import type { Tool, ToolExecuteResponse } from '../types/tool.types';
58
+import { ToolSchema, type Tool, type ToolExecuteResponse } from '../types/tool.types';
59
import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
60
import type {
61
SessionExecuteParams,
@@ -190,13 +194,14 @@ export class ToolRouterSession<
194
requestOptions?: ComposioRequestOptions
195
): Promise<ReturnType<TProvider['wrapTools']>> {
196
const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
193
- const tools = await ToolsModel.getRawToolRouterSessionTools(
197
+ const rawTools = await ToolsModel.getRawToolRouterSessionTools(
198
this.sessionId,
195
- modifiers?.modifySchema ? { modifySchema: modifiers.modifySchema } : undefined,
199
+ undefined,
200
requestOptions
201
);
202
+ const tools = await this.applySchemaModifier(rawTools, modifiers?.modifySchema);
203
const sessionTools = await this.addPreloadedCustomTools(tools, modifiers);
199
- const toolBySlug = new Map(sessionTools.map(tool => [tool.slug.toUpperCase(), tool]));
204
+ const rawToolBySlug = new Map(rawTools.map(tool => [tool.slug.toUpperCase(), tool]));
205
206
if (this.hasCustomTools()) {
207
// Create an execute function that splits local/remote tools in COMPOSIO_MULTI_EXECUTE_TOOL
@@ -205,7 +210,7 @@ export class ToolRouterSession<
210
input: Record<string, unknown>
211
): Promise<ToolExecuteResponse> => {
212
if (toolSlug === COMPOSIO_MULTI_EXECUTE_TOOL) {
208
- return this.routeMultiExecute(input, ToolsModel, sessionTools, modifiers);
213
+ return this.routeMultiExecute(input, ToolsModel, rawTools, modifiers);
214
}
215
const customTool = findCustomTool(this.customToolsMap, toolSlug);
216
if (customTool) {
@@ -217,7 +222,7 @@ export class ToolRouterSession<
222
toolSlug,
223
input,
224
modifiers,
220
- toolBySlug.get(toolSlug.toUpperCase())
225
+ rawToolBySlug.get(toolSlug.toUpperCase())
226
);
227
};
228
@@ -233,10 +238,33 @@ export class ToolRouterSession<
238
}
239
240
// Standard path (no local tools)
236
- const wrappedTools = ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers);
241
+ const wrappedTools = modifiers?.modifySchema
242
+ ? ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers, rawTools)
243
+ : ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers);
244
return wrappedTools as ReturnType<TProvider['wrapTools']>;
245
}
246
247
+ private async applySchemaModifier(
248
+ tools: Tool[],
249
+ modifier?: SessionMetaToolOptions['modifySchema']
250
+ ): Promise<Tool[]> {
251
+ if (!modifier) {
252
+ return tools;
253
+ }
254
+ if (typeof modifier !== 'function') {
255
+ throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
256
+ }
257
+ return Promise.all(
258
+ tools.map(tool =>
259
+ modifier({
260
+ toolSlug: tool.slug,
261
+ toolkitSlug: tool.toolkit?.slug ?? 'unknown',
262
+ schema: ToolSchema.parse(tool),
263
+ })
264
+ )
265
+ );
266
+ }
267
+
268
private async addPreloadedCustomTools(
269
tools: Tool[],
270
modifiers?: SessionMetaToolOptions
ts/packages/core/src/models/Tools.ts
+66
-20
@@ -272,12 +272,56 @@ export class Tools<
272
if (requestOptions?.signal?.aborted) {
273
throw new ComposioRequestCancelledError();
274
}
275
+ let modifiedParams = await this.applyFileUploadModifiers(
276
+ tool,
277
+ { toolSlug, toolkitSlug, params },
278
+ modifiers?.beforeFileUpload,
279
+ requestOptions
280
+ );
281
+
282
+ // apply the before execute modifiers
283
+ if (modifiers?.beforeExecute) {
284
+ if (typeof modifiers.beforeExecute === 'function') {
285
+ modifiedParams = await modifiers.beforeExecute({
286
+ toolSlug,
287
+ toolkitSlug,
288
+ params: modifiedParams,
289
+ });
290
+ if (requestOptions?.signal?.aborted) {
291
+ throw new ComposioRequestCancelledError();
292
+ }
293
+ } else {
294
+ throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
295
+ }
296
+ }
297
+ return modifiedParams;
298
+ }
299
+
300
+ /**
301
+ * Applies schema-aware file preprocessing shared by direct and Tool Router
302
+ * session execution. This always runs before the caller's `beforeExecute`
303
+ * hook so the hook observes the exact arguments sent to the backend.
304
+ */
305
+ private async applyFileUploadModifiers(
306
+ tool: Tool,
307
+ {
308
+ toolSlug,
309
+ toolkitSlug,
310
+ params,
311
+ }: {
312
+ toolSlug: string;
313
+ toolkitSlug: string;
314
+ params: ToolExecuteParams;
315
+ },
316
+ beforeFileUpload?: ExecuteToolModifiers['beforeFileUpload'],
317
+ requestOptions?: ComposioRequestOptions
318
+ ): Promise<ToolExecuteParams> {
319
let modifiedParams = params;
320
// if auto upload download files is enabled, upload the files to the Composio API
321
if (this.autoUploadDownloadFiles) {
322
const fileToolModifier = new FileToolModifier(this.client, {
323
...this.fileUploadPathOptions,
280
- beforeFileUpload: modifiers?.beforeFileUpload,
324
+ beforeFileUpload,
325
});
326
modifiedParams = await fileToolModifier.fileUploadModifier(tool, {
327
toolSlug,
@@ -321,21 +365,6 @@ export class Tools<
365
);
366
}
367
}
324
- // apply the before execute modifiers
325
- if (modifiers?.beforeExecute) {
326
- if (typeof modifiers.beforeExecute === 'function') {
327
- modifiedParams = await modifiers.beforeExecute({
328
- toolSlug,
329
- toolkitSlug,
330
- params: modifiedParams,
331
- });
332
- if (requestOptions?.signal?.aborted) {
333
- throw new ComposioRequestCancelledError();
334
- }
335
- } else {
336
- throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
337
- }
338
- }
368
return modifiedParams;
369
}
370
@@ -867,9 +896,10 @@ export class Tools<
896
wrapToolsForToolRouter(
897
sessionId: string,
898
tools: Tool[],
870
- modifiers?: SessionExecuteMetaModifiers
899
+ modifiers?: SessionExecuteMetaModifiers,
900
+ rawTools: Tool[] = tools.map(tool => ToolSchema.parse(tool))
901
): Tool[] {
872
- const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, tools, modifiers);
902
+ const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, rawTools, modifiers);
903
return this.provider.wrapTools(tools, executeToolFn) as Tool[];
904
}
905
@@ -1166,9 +1196,25 @@ export class Tools<
1196
});
1197
}
1198
1169
- // Apply beforeExecute modifier if provided
1199
let modifiedParams = body.arguments ?? {};
1200
const toolkitSlug = tool?.toolkit?.slug ?? 'composio';
1201
+
1202
+ if (tool) {
1203
+ const fileModifiedParams = await this.applyFileUploadModifiers(
1204
+ tool,
1205
+ {
1206
+ toolSlug,
1207
+ toolkitSlug,
1208
+ params: { arguments: modifiedParams },
1209
+ },
1210
+ undefined,
1211
+ requestOptions
1212
+ );
1213
+ modifiedParams = fileModifiedParams.arguments ?? {};
1214
+ }
1215
+
1216
+ // Apply beforeExecute modifier after file preprocessing so the hook sees
1217
+ // the same arguments that will be sent to the Tool Router.
1218
if (modifiers?.beforeExecute) {
1219
modifiedParams = await modifiers.beforeExecute({
1220
toolSlug,
@@ -1324,7 +1370,7 @@ export class Tools<
1370
* @deprecated The `customConnectionData` proxy param is deprecated and will be
1371
* removed in a future release. Use `customAuthParams` instead.
1372
*/
1327
- // @ts-ignore
1373
+ // @ts-expect-error
1374
custom_connection_data: toolProxyParams.data.customConnectionData,
1375
} as ComposioToolProxyParams;
1376
return withCancellation(
ts/packages/core/src/utils/modifiers/FileToolModifier.utils.neutral.ts
+52
-4
@@ -203,6 +203,20 @@ export const jsonSchemaTypeMatchesValue = (schema: JSONSchemaProperty, value: un
203
}
204
};
205
206
+/** Mirrors the array-shape inference used by {@link jsonSchemaTypeMatchesValue}. */
207
+const isArrayShapedSchema = (schema: JSONSchemaProperty | undefined): boolean => {
208
+ if (!schema) return false;
209
+ if (Array.isArray(schema.type)) return schema.type.includes('array');
210
+ return schema.type === 'array' || (schema.type === undefined && schema.items !== undefined);
211
+};
212
+
213
+/** Mirrors the object-shape inference used by {@link jsonSchemaTypeMatchesValue}. */
214
+const isObjectShapedSchema = (schema: JSONSchemaProperty | undefined): boolean => {
215
+ if (!schema) return false;
216
+ if (Array.isArray(schema.type)) return schema.type.includes('object');
217
+ return schema.type === 'object' || (schema.type === undefined && schema.properties !== undefined);
218
+};
219
+
220
/**
221
* Picks the file-bearing `anyOf`/`oneOf`/`allOf` variant whose JSON Schema
222
* shape matches the runtime value, falling back to the first file-bearing
@@ -243,19 +257,53 @@ export const walkFileUploadableLeaves = async (
257
258
const uploadableVariant = findSchemaVariantWithFileProperty(schema, 'file_uploadable', value);
259
if (uploadableVariant) {
260
+ // A scalar empty string cannot match an array-only file input, but callers
261
+ // use it to mean "no files". Route it through the leaf handler so it is
262
+ // omitted, unless another non-file variant explicitly accepts strings.
263
+ const matchingNonFileVariant = getSchemaVariants(schema).some(
264
+ variant =>
265
+ !schemaHasFileProperty(variant, 'file_uploadable') &&
266
+ jsonSchemaTypeMatchesValue(variant, value)
267
+ );
268
+ if (
269
+ isEmptyFileValue(value) &&
270
+ isArrayShapedSchema(uploadableVariant) &&
271
+ !matchingNonFileVariant
272
+ ) {
273
+ return leaf(value);
274
+ }
275
return walkFileUploadableLeaves(value, uploadableVariant, leaf);
276
}
277
249
- if (schema?.type === 'object' && schema.properties && isPlainObject(value)) {
278
+ if (
279
+ isEmptyFileValue(value) &&
280
+ isArrayShapedSchema(schema) &&
281
+ schemaHasFileProperty(schema, 'file_uploadable')
282
+ ) {
283
+ return leaf(value);
284
+ }
285
+
286
+ if (isObjectShapedSchema(schema) && schema?.properties && isPlainObject(value)) {
287
const transformed: Record<string, unknown> = {};
288
for (const [k, v] of Object.entries(value)) {
252
- const walked = await walkFileUploadableLeaves(v, schema.properties[k], leaf);
253
- if (walked !== DELETE_VALUE) transformed[k] = walked;
289
+ const propertySchema = Object.hasOwn(schema.properties, k) ? schema.properties[k] : undefined;
290
+ const walked = await walkFileUploadableLeaves(v, propertySchema, leaf);
291
+ if (walked !== DELETE_VALUE) {
292
+ // Define every key as an own data property so reserved JSON keys such
293
+ // as `__proto__` remain enumerable without invoking its inherited
294
+ // setter and changing this ordinary object's prototype.
295
+ Object.defineProperty(transformed, k, {
296
+ configurable: true,
297
+ enumerable: true,
298
+ value: walked,
299
+ writable: true,
300
+ });
301
+ }
302
}
303
return transformed;
304
}
305
258
- if (schema?.type === 'array' && schema.items && Array.isArray(value)) {
306
+ if (isArrayShapedSchema(schema) && schema?.items && Array.isArray(value)) {
307
// `items` can be a single schema or an array of schemas; we handle both.
308
const itemSchema = Array.isArray(schema.items) ? schema.items[0] : schema.items;
309
const walked = await Promise.all(
ts/packages/core/test/models/toolRouter.test.ts
+30
-13
@@ -2669,6 +2669,17 @@ describe('ToolRouter', () => {
2669
describe('tools function', () => {
2670
const userId = 'user_123';
2671
const sessionId = 'session_123';
2672
+ const validSessionTool = { slug: 'COMPOSIO_SEARCH_TOOLS', name: 'Search tools' };
2673
+
2674
+ const mockToolsWithValidSessionTool = () => {
2675
+ vi.mocked(Tools).mockImplementationOnce(function () {
2676
+ return {
2677
+ getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
2678
+ getRawToolRouterSessionTools: vi.fn().mockResolvedValue([validSessionTool]),
2679
+ wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
2680
+ };
2681
+ });
2682
+ };
2683
2684
beforeEach(() => {
2685
// Reset the Tools mock before each test
@@ -2714,12 +2725,13 @@ describe('ToolRouter', () => {
2725
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
2726
2727
const modifiers = {
2717
- modifySchema: vi.fn(tool => ({
2718
- ...tool,
2728
+ modifySchema: vi.fn(({ schema }) => ({
2729
+ ...schema,
2730
description: 'Modified description',
2731
})),
2732
beforeExecute: vi.fn(),
2733
};
2734
+ mockToolsWithValidSessionTool();
2735
2736
const session = await toolRouter.create(userId);
2737
const tools = await session.tools(modifiers);
@@ -2727,13 +2739,14 @@ describe('ToolRouter', () => {
2739
const toolsInstance = vi.mocked(Tools).mock.results[0].value;
2740
expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
2741
sessionId,
2730
- { modifySchema: modifiers.modifySchema },
2742
+ undefined,
2743
undefined
2744
);
2745
expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
2746
sessionId,
2735
- [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
2736
- modifiers
2747
+ [{ ...validSessionTool, description: 'Modified description' }],
2748
+ modifiers,
2749
+ [validSessionTool]
2750
);
2751
2752
expect(tools).toBe('mocked-wrapped-tools');
@@ -3046,8 +3059,10 @@ describe('ToolRouter', () => {
3059
it('should call tools function multiple times with different modifiers', async () => {
3060
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
3061
3049
- const modifier1 = { modifySchema: vi.fn() };
3050
- const modifier2 = { modifySchema: vi.fn() };
3062
+ const modifier1 = { modifySchema: vi.fn(({ schema }) => schema) };
3063
+ const modifier2 = { modifySchema: vi.fn(({ schema }) => schema) };
3064
+ mockToolsWithValidSessionTool();
3065
+ mockToolsWithValidSessionTool();
3066
3067
const session = await toolRouter.create(userId);
3068
@@ -3061,25 +3076,27 @@ describe('ToolRouter', () => {
3076
const firstToolsInstance = vi.mocked(Tools).mock.results[0].value;
3077
expect(firstToolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
3078
sessionId,
3064
- { modifySchema: modifier1.modifySchema },
3079
+ undefined,
3080
undefined
3081
);
3082
expect(firstToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
3083
sessionId,
3069
- [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
3070
- modifier1
3084
+ [validSessionTool],
3085
+ modifier1,
3086
+ [validSessionTool]
3087
);
3088
3089
const secondToolsInstance = vi.mocked(Tools).mock.results[1].value;
3090
expect(secondToolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
3091
sessionId,
3076
- { modifySchema: modifier2.modifySchema },
3092
+ undefined,
3093
undefined
3094
);
3095
expect(secondToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
3096
sessionId,
3081
- [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
3082
- modifier2
3097
+ [validSessionTool],
3098
+ modifier2,
3099
+ [validSessionTool]
3100
);
3101
});
3102
ts/packages/core/test/tools/fileModifiers.test.ts
+272
@@ -9,8 +9,10 @@ import {
9
import { ComposioRequestCancelledError } from '../../src/errors/SDKErrors';
10
import * as fileUtils from '../../src/utils/fileUtils.node';
11
import { Tools } from '../../src/models/Tools';
12
+import { ToolRouterSession } from '../../src/models/ToolRouterSession';
13
import { createTestContext, setupTest, mockToolExecution } from '../utils/toolExecuteUtils';
14
import { mockClient } from '../utils/mocks/client.mock';
15
+import { MockProvider } from '../utils/mocks/provider.mock';
16
17
// Mock the fileUtils module
18
vi.mock('../../src/utils/fileUtils.node', () => ({
@@ -360,6 +362,84 @@ describe('FileToolModifier', () => {
362
});
363
});
364
365
+ it('drops scalar empty values for array-only file inputs and preserves null and staged files', async () => {
366
+ const fileUploadable = {
367
+ type: 'object' as const,
368
+ file_uploadable: true,
369
+ properties: {
370
+ name: { type: 'string' as const },
371
+ mimetype: { type: 'string' as const },
372
+ s3key: { type: 'string' as const },
373
+ },
374
+ };
375
+ const staged = { name: 'a.txt', mimetype: 'text/plain', s3key: 'staged/a.txt' };
376
+ const arrayFileTool: Tool = {
377
+ ...mockTool,
378
+ inputParameters: {
379
+ type: 'object',
380
+ properties: {
381
+ files: {
382
+ anyOf: [{ type: 'array', items: fileUploadable }, { type: 'null' }],
383
+ },
384
+ directFiles: { type: 'array', items: fileUploadable },
385
+ nullableFile: { anyOf: [fileUploadable, { type: 'null' }] },
386
+ stagedFiles: { type: 'array', items: fileUploadable },
387
+ },
388
+ },
389
+ };
390
+
391
+ const result = await fileToolModifier.fileUploadModifier(arrayFileTool, {
392
+ toolSlug: 'test-tool',
393
+ toolkitSlug: 'test-toolkit',
394
+ params: {
395
+ arguments: {
396
+ files: '',
397
+ directFiles: '',
398
+ nullableFile: null,
399
+ stagedFiles: [staged],
400
+ },
401
+ userId: 'test-user',
402
+ },
403
+ });
404
+
405
+ expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
406
+ expect(result.arguments).toEqual({
407
+ nullableFile: null,
408
+ stagedFiles: [staged],
409
+ });
410
+ });
411
+
412
+ it('drops scalar empty values for composed file arrays inferred from items', async () => {
413
+ const typelessArrayFileTool: Tool = {
414
+ ...mockTool,
415
+ inputParameters: {
416
+ type: 'object',
417
+ properties: {
418
+ files: {
419
+ anyOf: [
420
+ {
421
+ items: { type: 'object', file_uploadable: true },
422
+ },
423
+ { type: 'null' },
424
+ ],
425
+ },
426
+ },
427
+ },
428
+ };
429
+
430
+ const result = await fileToolModifier.fileUploadModifier(typelessArrayFileTool, {
431
+ toolSlug: 'test-tool',
432
+ toolkitSlug: 'test-toolkit',
433
+ params: {
434
+ arguments: { files: '' },
435
+ userId: 'test-user',
436
+ },
437
+ });
438
+
439
+ expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
440
+ expect(result.arguments).toEqual({});
441
+ });
442
+
443
it('should upload file for file_uploadable parameters', async () => {
444
const mockFileData = {
445
name: 'file.txt',
@@ -2003,6 +2083,63 @@ describe('Tools with dangerouslyAllowAutoUploadDownloadFiles', () => {
2083
availableVersions: ['20251201_01'],
2084
};
2085
2086
+ describe('when dangerouslyAllowAutoUploadDownloadFiles is true', () => {
2087
+ beforeEach(() => {
2088
+ context.tools = new Tools(mockClient as unknown as ComposioClient, {
2089
+ provider: context.mockProvider,
2090
+ dangerouslyAllowAutoUploadDownloadFiles: true,
2091
+ });
2092
+ vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockResolvedValue({
2093
+ name: 'file.txt',
2094
+ mimetype: 'text/plain',
2095
+ s3key: 'uploads/file.txt',
2096
+ });
2097
+ mockClient.toolRouter.session.execute.mockResolvedValue({
2098
+ data: { uploaded: true },
2099
+ error: null,
2100
+ log_id: 'session-log',
2101
+ });
2102
+ });
2103
+
2104
+ it('stages session file arguments before beforeExecute and the request', async () => {
2105
+ const beforeExecute = vi.fn(({ params }) => params);
2106
+
2107
+ await context.tools.executeSessionTool(
2108
+ 'COMPOSIO_TOOL',
2109
+ {
2110
+ sessionId: 'session-123',
2111
+ arguments: { file: '/path/to/file.txt' },
2112
+ },
2113
+ { beforeExecute },
2114
+ mockToolWithFileUpload
2115
+ );
2116
+
2117
+ const staged = { name: 'file.txt', mimetype: 'text/plain', s3key: 'uploads/file.txt' };
2118
+ expect(fileUtils.getFileDataAfterUploadingToS3).toHaveBeenCalledWith(
2119
+ '/path/to/file.txt',
2120
+ expect.objectContaining({
2121
+ toolSlug: 'COMPOSIO_TOOL',
2122
+ toolkitSlug: 'test-toolkit',
2123
+ })
2124
+ );
2125
+ expect(beforeExecute).toHaveBeenCalledWith({
2126
+ toolSlug: 'COMPOSIO_TOOL',
2127
+ toolkitSlug: 'test-toolkit',
2128
+ sessionId: 'session-123',
2129
+ params: { file: staged },
2130
+ });
2131
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
2132
+ 'session-123',
2133
+ {
2134
+ tool_slug: 'COMPOSIO_TOOL',
2135
+ arguments: { file: staged },
2136
+ enable_auto_workbench_offload: true,
2137
+ },
2138
+ undefined
2139
+ );
2140
+ });
2141
+ });
2142
+
2143
describe('when dangerouslyAllowAutoUploadDownloadFiles is false', () => {
2144
beforeEach(async () => {
2145
context.tools = new Tools(mockClient as unknown as ComposioClient, {
@@ -2126,6 +2263,141 @@ describe('Tools with dangerouslyAllowAutoUploadDownloadFiles', () => {
2263
expect(mockClient.tools.execute.mock.calls[0]?.[1]?.arguments).toEqual({ text: 'keep' });
2264
});
2265
2266
+ it('cleans typeless session file schemas without allowing prototype-key injection', async () => {
2267
+ const staged = { name: 'a.txt', mimetype: 'text/plain', s3key: 'staged/a.txt' };
2268
+ const argumentsWithPrototypeKey: Record<string, unknown> = JSON.parse(
2269
+ '{"file":"","__proto__":{"polluted":true},"staged":{"name":"a.txt","mimetype":"text/plain","s3key":"staged/a.txt"},"nullable":null,"nested":{"file":"","__proto__":{"nestedPolluted":true},"text":"nested keep"},"text":"keep"}'
2270
+ );
2271
+ const tool: Tool = {
2272
+ ...mockToolWithFileUpload,
2273
+ inputParameters: {
2274
+ properties: {
2275
+ file: { type: 'string', file_uploadable: true },
2276
+ staged: { type: 'object', file_uploadable: true },
2277
+ nullable: {
2278
+ anyOf: [{ type: 'object', file_uploadable: true }, { type: 'null' }],
2279
+ },
2280
+ nested: {
2281
+ properties: {
2282
+ file: { type: 'string', file_uploadable: true },
2283
+ text: { type: 'string' },
2284
+ },
2285
+ },
2286
+ text: { type: 'string' },
2287
+ },
2288
+ },
2289
+ };
2290
+ const beforeExecute = vi.fn(({ params }) => params);
2291
+ mockClient.toolRouter.session.execute.mockResolvedValueOnce({
2292
+ data: { ok: true },
2293
+ error: null,
2294
+ log_id: 'session-log',
2295
+ });
2296
+
2297
+ await context.tools.executeSessionTool(
2298
+ 'COMPOSIO_TOOL',
2299
+ { sessionId: 'session-123', arguments: argumentsWithPrototypeKey },
2300
+ { beforeExecute },
2301
+ tool
2302
+ );
2303
+
2304
+ const hookArguments = beforeExecute.mock.calls[0]?.[0].params as Record<string, unknown>;
2305
+ expect(Object.getPrototypeOf(hookArguments)).toBe(Object.prototype);
2306
+ expect(Object.hasOwn(hookArguments, '__proto__')).toBe(true);
2307
+ expect(Object.keys(hookArguments)).toContain('__proto__');
2308
+ expect(hookArguments).not.toHaveProperty('file');
2309
+ expect(hookArguments.__proto__).toEqual({ polluted: true });
2310
+ expect(hookArguments.polluted).toBeUndefined();
2311
+ expect(hookArguments.staged).toEqual(staged);
2312
+ expect(hookArguments.nullable).toBeNull();
2313
+ expect(hookArguments.text).toBe('keep');
2314
+ const hookNested = hookArguments.nested as Record<string, unknown>;
2315
+ expect(Object.getPrototypeOf(hookNested)).toBe(Object.prototype);
2316
+ expect(Object.hasOwn(hookNested, '__proto__')).toBe(true);
2317
+ expect(Object.keys(hookNested)).toContain('__proto__');
2318
+ expect(hookNested).not.toHaveProperty('file');
2319
+ expect(hookNested.__proto__).toEqual({ nestedPolluted: true });
2320
+ expect(hookNested.nestedPolluted).toBeUndefined();
2321
+ expect(hookNested.text).toBe('nested keep');
2322
+
2323
+ const requestArguments = mockClient.toolRouter.session.execute.mock.calls[0]?.[1]
2324
+ ?.arguments as Record<string, unknown>;
2325
+ expect(Object.getPrototypeOf(requestArguments)).toBe(Object.prototype);
2326
+ expect(Object.hasOwn(requestArguments, '__proto__')).toBe(true);
2327
+ expect(Object.keys(requestArguments)).toContain('__proto__');
2328
+ expect(requestArguments.__proto__).toEqual({ polluted: true });
2329
+ expect(requestArguments.polluted).toBeUndefined();
2330
+ expect(requestArguments.staged).toEqual(staged);
2331
+ expect(requestArguments.nullable).toBeNull();
2332
+ const requestNested = requestArguments.nested as Record<string, unknown>;
2333
+ expect(Object.getPrototypeOf(requestNested)).toBe(Object.prototype);
2334
+ expect(Object.hasOwn(requestNested, '__proto__')).toBe(true);
2335
+ expect(Object.keys(requestNested)).toContain('__proto__');
2336
+ expect(requestNested).not.toHaveProperty('file');
2337
+ expect(requestNested.__proto__).toEqual({ nestedPolluted: true });
2338
+ expect(requestNested.nestedPolluted).toBeUndefined();
2339
+ expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
2340
+ });
2341
+
2342
+ it('uses raw session schemas for cleanup when modifySchema removes file flags', async () => {
2343
+ const provider = new MockProvider();
2344
+ const session = new ToolRouterSession(
2345
+ mockClient as unknown as ComposioClient,
2346
+ {
2347
+ apiKey: 'test-api-key',
2348
+ provider,
2349
+ dangerouslyAllowAutoUploadDownloadFiles: false,
2350
+ },
2351
+ 'session-123',
2352
+ { type: 'http', url: 'https://mcp.example.com/session-123' }
2353
+ );
2354
+ mockClient.toolRouter.session.tools.mockResolvedValueOnce({
2355
+ items: [mockRawToolWithFileUpload],
2356
+ next_cursor: null,
2357
+ });
2358
+ mockClient.toolRouter.session.execute.mockResolvedValueOnce({
2359
+ data: { ok: true },
2360
+ error: null,
2361
+ log_id: 'session-log',
2362
+ });
2363
+ provider.wrapTools.mockImplementation(tools => tools);
2364
+
2365
+ await session.tools({
2366
+ modifySchema: ({ schema }) => ({
2367
+ ...schema,
2368
+ inputParameters: {
2369
+ type: 'object',
2370
+ properties: {
2371
+ file: { type: 'string' },
2372
+ text: { type: 'string' },
2373
+ },
2374
+ },
2375
+ }),
2376
+ });
2377
+
2378
+ const displayTools = provider.wrapTools.mock.calls[0]?.[0] as Tool[];
2379
+ expect(displayTools[0]?.inputParameters?.properties?.file).not.toHaveProperty(
2380
+ 'file_uploadable'
2381
+ );
2382
+
2383
+ const executeTool = provider.wrapTools.mock.calls[0]?.[1] as (
2384
+ toolSlug: string,
2385
+ input: Record<string, unknown>
2386
+ ) => Promise<unknown>;
2387
+ await executeTool('COMPOSIO_TOOL', { file: '', text: 'keep' });
2388
+
2389
+ expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
2390
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
2391
+ 'session-123',
2392
+ {
2393
+ tool_slug: 'COMPOSIO_TOOL',
2394
+ arguments: { text: 'keep' },
2395
+ enable_auto_workbench_offload: true,
2396
+ },
2397
+ undefined
2398
+ );
2399
+ });
2400
+
2401
it('warns once per tool when auto-upload is off and the tool has a file-uploadable input', async () => {
2402
const warnSpy = vi.spyOn((await import('../../src/utils/logger')).default, 'warn');
2403
warnSpy.mockImplementation(() => {}); // silence the log in test output