Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(ts): preprocess session file uploads

jkomynoa61ad27940de
diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.ts
index e9ebeac6e..e8fdb9ac7 100644
--- a/ts/packages/core/src/models/ToolRouterSession.ts
+++ b/ts/packages/core/src/models/ToolRouterSession.ts
@@ -41,7 +41,11 @@ import { ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT, serializeExperimentalForWire } from
import { z } from 'zod/v3';
import { transform } from '../utils/transform';
import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';
-import { ComposioAclOnlyForSharedError, ValidationError } from '../errors';
+import {
+ ComposioAclOnlyForSharedError,
+ ComposioInvalidModifierError,
+ ValidationError,
+} from '../errors';
import { Tools } from './Tools';
import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';
import type {
@@ -51,7 +55,7 @@ import type {
RegisteredCustomTool,
RegisteredCustomToolkit,
} from '../types/customTool.types';
-import type { Tool, ToolExecuteResponse } from '../types/tool.types';
+import { ToolSchema, type Tool, type ToolExecuteResponse } from '../types/tool.types';
import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
import type {
SessionExecuteParams,
@@ -190,13 +194,14 @@ export class ToolRouterSession<
requestOptions?: ComposioRequestOptions
): Promise<ReturnType<TProvider['wrapTools']>> {
const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
- const tools = await ToolsModel.getRawToolRouterSessionTools(
+ const rawTools = await ToolsModel.getRawToolRouterSessionTools(
this.sessionId,
- modifiers?.modifySchema ? { modifySchema: modifiers.modifySchema } : undefined,
+ undefined,
requestOptions
);
+ const tools = await this.applySchemaModifier(rawTools, modifiers?.modifySchema);
const sessionTools = await this.addPreloadedCustomTools(tools, modifiers);
- const toolBySlug = new Map(sessionTools.map(tool => [tool.slug.toUpperCase(), tool]));
+ const rawToolBySlug = new Map(rawTools.map(tool => [tool.slug.toUpperCase(), tool]));
if (this.hasCustomTools()) {
// Create an execute function that splits local/remote tools in COMPOSIO_MULTI_EXECUTE_TOOL
@@ -205,7 +210,7 @@ export class ToolRouterSession<
input: Record<string, unknown>
): Promise<ToolExecuteResponse> => {
if (toolSlug === COMPOSIO_MULTI_EXECUTE_TOOL) {
- return this.routeMultiExecute(input, ToolsModel, sessionTools, modifiers);
+ return this.routeMultiExecute(input, ToolsModel, rawTools, modifiers);
}
const customTool = findCustomTool(this.customToolsMap, toolSlug);
if (customTool) {
@@ -217,7 +222,7 @@ export class ToolRouterSession<
toolSlug,
input,
modifiers,
- toolBySlug.get(toolSlug.toUpperCase())
+ rawToolBySlug.get(toolSlug.toUpperCase())
);
};
@@ -233,10 +238,33 @@ export class ToolRouterSession<
}
// Standard path (no local tools)
- const wrappedTools = ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers);
+ const wrappedTools = modifiers?.modifySchema
+ ? ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers, rawTools)
+ : ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers);
return wrappedTools as ReturnType<TProvider['wrapTools']>;
}
+ private async applySchemaModifier(
+ tools: Tool[],
+ modifier?: SessionMetaToolOptions['modifySchema']
+ ): Promise<Tool[]> {
+ if (!modifier) {
+ return tools;
+ }
+ if (typeof modifier !== 'function') {
+ throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
+ }
+ return Promise.all(
+ tools.map(tool =>
+ modifier({
+ toolSlug: tool.slug,
+ toolkitSlug: tool.toolkit?.slug ?? 'unknown',
+ schema: ToolSchema.parse(tool),
+ })
+ )
+ );
+ }
+
private async addPreloadedCustomTools(
tools: Tool[],
modifiers?: SessionMetaToolOptions
diff --git a/ts/packages/core/src/models/Tools.ts b/ts/packages/core/src/models/Tools.ts
index 6209925d6..f3d9507f9 100644
--- a/ts/packages/core/src/models/Tools.ts
+++ b/ts/packages/core/src/models/Tools.ts
@@ -272,12 +272,56 @@ export class Tools<
if (requestOptions?.signal?.aborted) {
throw new ComposioRequestCancelledError();
}
+ let modifiedParams = await this.applyFileUploadModifiers(
+ tool,
+ { toolSlug, toolkitSlug, params },
+ modifiers?.beforeFileUpload,
+ requestOptions
+ );
+
+ // apply the before execute modifiers
+ if (modifiers?.beforeExecute) {
+ if (typeof modifiers.beforeExecute === 'function') {
+ modifiedParams = await modifiers.beforeExecute({
+ toolSlug,
+ toolkitSlug,
+ params: modifiedParams,
+ });
+ if (requestOptions?.signal?.aborted) {
+ throw new ComposioRequestCancelledError();
+ }
+ } else {
+ throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
+ }
+ }
+ return modifiedParams;
+ }
+
+ /**
+ * Applies schema-aware file preprocessing shared by direct and Tool Router
+ * session execution. This always runs before the caller's `beforeExecute`
+ * hook so the hook observes the exact arguments sent to the backend.
+ */
+ private async applyFileUploadModifiers(
+ tool: Tool,
+ {
+ toolSlug,
+ toolkitSlug,
+ params,
+ }: {
+ toolSlug: string;
+ toolkitSlug: string;
+ params: ToolExecuteParams;
+ },
+ beforeFileUpload?: ExecuteToolModifiers['beforeFileUpload'],
+ requestOptions?: ComposioRequestOptions
+ ): Promise<ToolExecuteParams> {
let modifiedParams = params;
// if auto upload download files is enabled, upload the files to the Composio API
if (this.autoUploadDownloadFiles) {
const fileToolModifier = new FileToolModifier(this.client, {
...this.fileUploadPathOptions,
- beforeFileUpload: modifiers?.beforeFileUpload,
+ beforeFileUpload,
});
modifiedParams = await fileToolModifier.fileUploadModifier(tool, {
toolSlug,
@@ -321,21 +365,6 @@ export class Tools<
);
}
}
- // apply the before execute modifiers
- if (modifiers?.beforeExecute) {
- if (typeof modifiers.beforeExecute === 'function') {
- modifiedParams = await modifiers.beforeExecute({
- toolSlug,
- toolkitSlug,
- params: modifiedParams,
- });
- if (requestOptions?.signal?.aborted) {
- throw new ComposioRequestCancelledError();
- }
- } else {
- throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
- }
- }
return modifiedParams;
}
@@ -867,9 +896,10 @@ export class Tools<
wrapToolsForToolRouter(
sessionId: string,
tools: Tool[],
- modifiers?: SessionExecuteMetaModifiers
+ modifiers?: SessionExecuteMetaModifiers,
+ rawTools: Tool[] = tools.map(tool => ToolSchema.parse(tool))
): Tool[] {
- const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, tools, modifiers);
+ const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, rawTools, modifiers);
return this.provider.wrapTools(tools, executeToolFn) as Tool[];
}
@@ -1166,9 +1196,25 @@ export class Tools<
});
}
- // Apply beforeExecute modifier if provided
let modifiedParams = body.arguments ?? {};
const toolkitSlug = tool?.toolkit?.slug ?? 'composio';
+
+ if (tool) {
+ const fileModifiedParams = await this.applyFileUploadModifiers(
+ tool,
+ {
+ toolSlug,
+ toolkitSlug,
+ params: { arguments: modifiedParams },
+ },
+ undefined,
+ requestOptions
+ );
+ modifiedParams = fileModifiedParams.arguments ?? {};
+ }
+
+ // Apply beforeExecute modifier after file preprocessing so the hook sees
+ // the same arguments that will be sent to the Tool Router.
if (modifiers?.beforeExecute) {
modifiedParams = await modifiers.beforeExecute({
toolSlug,
@@ -1324,7 +1370,7 @@ export class Tools<
* @deprecated The `customConnectionData` proxy param is deprecated and will be
* removed in a future release. Use `customAuthParams` instead.
*/
- // @ts-ignore
+ // @ts-expect-error
custom_connection_data: toolProxyParams.data.customConnectionData,
} as ComposioToolProxyParams;
return withCancellation(
diff --git a/ts/packages/core/src/utils/modifiers/FileToolModifier.utils.neutral.ts b/ts/packages/core/src/utils/modifiers/FileToolModifier.utils.neutral.ts
index d64e3fcf8..6458eaf6e 100644
--- a/ts/packages/core/src/utils/modifiers/FileToolModifier.utils.neutral.ts
+++ b/ts/packages/core/src/utils/modifiers/FileToolModifier.utils.neutral.ts
@@ -203,6 +203,20 @@ export const jsonSchemaTypeMatchesValue = (schema: JSONSchemaProperty, value: un
}
};
+/** Mirrors the array-shape inference used by {@link jsonSchemaTypeMatchesValue}. */
+const isArrayShapedSchema = (schema: JSONSchemaProperty | undefined): boolean => {
+ if (!schema) return false;
+ if (Array.isArray(schema.type)) return schema.type.includes('array');
+ return schema.type === 'array' || (schema.type === undefined && schema.items !== undefined);
+};
+
+/** Mirrors the object-shape inference used by {@link jsonSchemaTypeMatchesValue}. */
+const isObjectShapedSchema = (schema: JSONSchemaProperty | undefined): boolean => {
+ if (!schema) return false;
+ if (Array.isArray(schema.type)) return schema.type.includes('object');
+ return schema.type === 'object' || (schema.type === undefined && schema.properties !== undefined);
+};
+
/**
* Picks the file-bearing `anyOf`/`oneOf`/`allOf` variant whose JSON Schema
* shape matches the runtime value, falling back to the first file-bearing
@@ -243,19 +257,53 @@ export const walkFileUploadableLeaves = async (
const uploadableVariant = findSchemaVariantWithFileProperty(schema, 'file_uploadable', value);
if (uploadableVariant) {
+ // A scalar empty string cannot match an array-only file input, but callers
+ // use it to mean "no files". Route it through the leaf handler so it is
+ // omitted, unless another non-file variant explicitly accepts strings.
+ const matchingNonFileVariant = getSchemaVariants(schema).some(
+ variant =>
+ !schemaHasFileProperty(variant, 'file_uploadable') &&
+ jsonSchemaTypeMatchesValue(variant, value)
+ );
+ if (
+ isEmptyFileValue(value) &&
+ isArrayShapedSchema(uploadableVariant) &&
+ !matchingNonFileVariant
+ ) {
+ return leaf(value);
+ }
return walkFileUploadableLeaves(value, uploadableVariant, leaf);
}
- if (schema?.type === 'object' && schema.properties && isPlainObject(value)) {
+ if (
+ isEmptyFileValue(value) &&
+ isArrayShapedSchema(schema) &&
+ schemaHasFileProperty(schema, 'file_uploadable')
+ ) {
+ return leaf(value);
+ }
+
+ if (isObjectShapedSchema(schema) && schema?.properties && isPlainObject(value)) {
const transformed: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value)) {
- const walked = await walkFileUploadableLeaves(v, schema.properties[k], leaf);
- if (walked !== DELETE_VALUE) transformed[k] = walked;
+ const propertySchema = Object.hasOwn(schema.properties, k) ? schema.properties[k] : undefined;
+ const walked = await walkFileUploadableLeaves(v, propertySchema, leaf);
+ if (walked !== DELETE_VALUE) {
+ // Define every key as an own data property so reserved JSON keys such
+ // as `__proto__` remain enumerable without invoking its inherited
+ // setter and changing this ordinary object's prototype.
+ Object.defineProperty(transformed, k, {
+ configurable: true,
+ enumerable: true,
+ value: walked,
+ writable: true,
+ });
+ }
}
return transformed;
}
- if (schema?.type === 'array' && schema.items && Array.isArray(value)) {
+ if (isArrayShapedSchema(schema) && schema?.items && Array.isArray(value)) {
// `items` can be a single schema or an array of schemas; we handle both.
const itemSchema = Array.isArray(schema.items) ? schema.items[0] : schema.items;
const walked = await Promise.all(
diff --git a/ts/packages/core/test/models/toolRouter.test.ts b/ts/packages/core/test/models/toolRouter.test.ts
index 290fd8737..263374736 100644
--- a/ts/packages/core/test/models/toolRouter.test.ts
+++ b/ts/packages/core/test/models/toolRouter.test.ts
@@ -2669,6 +2669,17 @@ describe('ToolRouter', () => {
describe('tools function', () => {
const userId = 'user_123';
const sessionId = 'session_123';
+ const validSessionTool = { slug: 'COMPOSIO_SEARCH_TOOLS', name: 'Search tools' };
+
+ const mockToolsWithValidSessionTool = () => {
+ vi.mocked(Tools).mockImplementationOnce(function () {
+ return {
+ getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
+ getRawToolRouterSessionTools: vi.fn().mockResolvedValue([validSessionTool]),
+ wrapToolsForToolRouter: vi.fn().mockReturnValue('mocked-wrapped-tools'),
+ };
+ });
+ };
beforeEach(() => {
// Reset the Tools mock before each test
@@ -2714,12 +2725,13 @@ describe('ToolRouter', () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
const modifiers = {
- modifySchema: vi.fn(tool => ({
- ...tool,
+ modifySchema: vi.fn(({ schema }) => ({
+ ...schema,
description: 'Modified description',
})),
beforeExecute: vi.fn(),
};
+ mockToolsWithValidSessionTool();
const session = await toolRouter.create(userId);
const tools = await session.tools(modifiers);
@@ -2727,13 +2739,14 @@ describe('ToolRouter', () => {
const toolsInstance = vi.mocked(Tools).mock.results[0].value;
expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
sessionId,
- { modifySchema: modifiers.modifySchema },
+ undefined,
undefined
);
expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
sessionId,
- [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
- modifiers
+ [{ ...validSessionTool, description: 'Modified description' }],
+ modifiers,
+ [validSessionTool]
);
expect(tools).toBe('mocked-wrapped-tools');
@@ -3046,8 +3059,10 @@ describe('ToolRouter', () => {
it('should call tools function multiple times with different modifiers', async () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
- const modifier1 = { modifySchema: vi.fn() };
- const modifier2 = { modifySchema: vi.fn() };
+ const modifier1 = { modifySchema: vi.fn(({ schema }) => schema) };
+ const modifier2 = { modifySchema: vi.fn(({ schema }) => schema) };
+ mockToolsWithValidSessionTool();
+ mockToolsWithValidSessionTool();
const session = await toolRouter.create(userId);
@@ -3061,25 +3076,27 @@ describe('ToolRouter', () => {
const firstToolsInstance = vi.mocked(Tools).mock.results[0].value;
expect(firstToolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
sessionId,
- { modifySchema: modifier1.modifySchema },
+ undefined,
undefined
);
expect(firstToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
sessionId,
- [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
- modifier1
+ [validSessionTool],
+ modifier1,
+ [validSessionTool]
);
const secondToolsInstance = vi.mocked(Tools).mock.results[1].value;
expect(secondToolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
sessionId,
- { modifySchema: modifier2.modifySchema },
+ undefined,
undefined
);
expect(secondToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
sessionId,
- [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
- modifier2
+ [validSessionTool],
+ modifier2,
+ [validSessionTool]
);
});
diff --git a/ts/packages/core/test/tools/fileModifiers.test.ts b/ts/packages/core/test/tools/fileModifiers.test.ts
index 37924b723..6c6e6ca14 100644
--- a/ts/packages/core/test/tools/fileModifiers.test.ts
+++ b/ts/packages/core/test/tools/fileModifiers.test.ts
@@ -9,8 +9,10 @@ import {
import { ComposioRequestCancelledError } from '../../src/errors/SDKErrors';
import * as fileUtils from '../../src/utils/fileUtils.node';
import { Tools } from '../../src/models/Tools';
+import { ToolRouterSession } from '../../src/models/ToolRouterSession';
import { createTestContext, setupTest, mockToolExecution } from '../utils/toolExecuteUtils';
import { mockClient } from '../utils/mocks/client.mock';
+import { MockProvider } from '../utils/mocks/provider.mock';
// Mock the fileUtils module
vi.mock('../../src/utils/fileUtils.node', () => ({
@@ -360,6 +362,84 @@ describe('FileToolModifier', () => {
});
});
+ it('drops scalar empty values for array-only file inputs and preserves null and staged files', async () => {
+ const fileUploadable = {
+ type: 'object' as const,
+ file_uploadable: true,
+ properties: {
+ name: { type: 'string' as const },
+ mimetype: { type: 'string' as const },
+ s3key: { type: 'string' as const },
+ },
+ };
+ const staged = { name: 'a.txt', mimetype: 'text/plain', s3key: 'staged/a.txt' };
+ const arrayFileTool: Tool = {
+ ...mockTool,
+ inputParameters: {
+ type: 'object',
+ properties: {
+ files: {
+ anyOf: [{ type: 'array', items: fileUploadable }, { type: 'null' }],
+ },
+ directFiles: { type: 'array', items: fileUploadable },
+ nullableFile: { anyOf: [fileUploadable, { type: 'null' }] },
+ stagedFiles: { type: 'array', items: fileUploadable },
+ },
+ },
+ };
+
+ const result = await fileToolModifier.fileUploadModifier(arrayFileTool, {
+ toolSlug: 'test-tool',
+ toolkitSlug: 'test-toolkit',
+ params: {
+ arguments: {
+ files: '',
+ directFiles: '',
+ nullableFile: null,
+ stagedFiles: [staged],
+ },
+ userId: 'test-user',
+ },
+ });
+
+ expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
+ expect(result.arguments).toEqual({
+ nullableFile: null,
+ stagedFiles: [staged],
+ });
+ });
+
+ it('drops scalar empty values for composed file arrays inferred from items', async () => {
+ const typelessArrayFileTool: Tool = {
+ ...mockTool,
+ inputParameters: {
+ type: 'object',
+ properties: {
+ files: {
+ anyOf: [
+ {
+ items: { type: 'object', file_uploadable: true },
+ },
+ { type: 'null' },
+ ],
+ },
+ },
+ },
+ };
+
+ const result = await fileToolModifier.fileUploadModifier(typelessArrayFileTool, {
+ toolSlug: 'test-tool',
+ toolkitSlug: 'test-toolkit',
+ params: {
+ arguments: { files: '' },
+ userId: 'test-user',
+ },
+ });
+
+ expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
+ expect(result.arguments).toEqual({});
+ });
+
it('should upload file for file_uploadable parameters', async () => {
const mockFileData = {
name: 'file.txt',
@@ -2003,6 +2083,63 @@ describe('Tools with dangerouslyAllowAutoUploadDownloadFiles', () => {
availableVersions: ['20251201_01'],
};
+ describe('when dangerouslyAllowAutoUploadDownloadFiles is true', () => {
+ beforeEach(() => {
+ context.tools = new Tools(mockClient as unknown as ComposioClient, {
+ provider: context.mockProvider,
+ dangerouslyAllowAutoUploadDownloadFiles: true,
+ });
+ vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockResolvedValue({
+ name: 'file.txt',
+ mimetype: 'text/plain',
+ s3key: 'uploads/file.txt',
+ });
+ mockClient.toolRouter.session.execute.mockResolvedValue({
+ data: { uploaded: true },
+ error: null,
+ log_id: 'session-log',
+ });
+ });
+
+ it('stages session file arguments before beforeExecute and the request', async () => {
+ const beforeExecute = vi.fn(({ params }) => params);
+
+ await context.tools.executeSessionTool(
+ 'COMPOSIO_TOOL',
+ {
+ sessionId: 'session-123',
+ arguments: { file: '/path/to/file.txt' },
+ },
+ { beforeExecute },
+ mockToolWithFileUpload
+ );
+
+ const staged = { name: 'file.txt', mimetype: 'text/plain', s3key: 'uploads/file.txt' };
+ expect(fileUtils.getFileDataAfterUploadingToS3).toHaveBeenCalledWith(
+ '/path/to/file.txt',
+ expect.objectContaining({
+ toolSlug: 'COMPOSIO_TOOL',
+ toolkitSlug: 'test-toolkit',
+ })
+ );
+ expect(beforeExecute).toHaveBeenCalledWith({
+ toolSlug: 'COMPOSIO_TOOL',
+ toolkitSlug: 'test-toolkit',
+ sessionId: 'session-123',
+ params: { file: staged },
+ });
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
+ 'session-123',
+ {
+ tool_slug: 'COMPOSIO_TOOL',
+ arguments: { file: staged },
+ enable_auto_workbench_offload: true,
+ },
+ undefined
+ );
+ });
+ });
+
describe('when dangerouslyAllowAutoUploadDownloadFiles is false', () => {
beforeEach(async () => {
context.tools = new Tools(mockClient as unknown as ComposioClient, {
@@ -2126,6 +2263,141 @@ describe('Tools with dangerouslyAllowAutoUploadDownloadFiles', () => {
expect(mockClient.tools.execute.mock.calls[0]?.[1]?.arguments).toEqual({ text: 'keep' });
});
+ it('cleans typeless session file schemas without allowing prototype-key injection', async () => {
+ const staged = { name: 'a.txt', mimetype: 'text/plain', s3key: 'staged/a.txt' };
+ const argumentsWithPrototypeKey: Record<string, unknown> = JSON.parse(
+ '{"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"}'
+ );
+ const tool: Tool = {
+ ...mockToolWithFileUpload,
+ inputParameters: {
+ properties: {
+ file: { type: 'string', file_uploadable: true },
+ staged: { type: 'object', file_uploadable: true },
+ nullable: {
+ anyOf: [{ type: 'object', file_uploadable: true }, { type: 'null' }],
+ },
+ nested: {
+ properties: {
+ file: { type: 'string', file_uploadable: true },
+ text: { type: 'string' },
+ },
+ },
+ text: { type: 'string' },
+ },
+ },
+ };
+ const beforeExecute = vi.fn(({ params }) => params);
+ mockClient.toolRouter.session.execute.mockResolvedValueOnce({
+ data: { ok: true },
+ error: null,
+ log_id: 'session-log',
+ });
+
+ await context.tools.executeSessionTool(
+ 'COMPOSIO_TOOL',
+ { sessionId: 'session-123', arguments: argumentsWithPrototypeKey },
+ { beforeExecute },
+ tool
+ );
+
+ const hookArguments = beforeExecute.mock.calls[0]?.[0].params as Record<string, unknown>;
+ expect(Object.getPrototypeOf(hookArguments)).toBe(Object.prototype);
+ expect(Object.hasOwn(hookArguments, '__proto__')).toBe(true);
+ expect(Object.keys(hookArguments)).toContain('__proto__');
+ expect(hookArguments).not.toHaveProperty('file');
+ expect(hookArguments.__proto__).toEqual({ polluted: true });
+ expect(hookArguments.polluted).toBeUndefined();
+ expect(hookArguments.staged).toEqual(staged);
+ expect(hookArguments.nullable).toBeNull();
+ expect(hookArguments.text).toBe('keep');
+ const hookNested = hookArguments.nested as Record<string, unknown>;
+ expect(Object.getPrototypeOf(hookNested)).toBe(Object.prototype);
+ expect(Object.hasOwn(hookNested, '__proto__')).toBe(true);
+ expect(Object.keys(hookNested)).toContain('__proto__');
+ expect(hookNested).not.toHaveProperty('file');
+ expect(hookNested.__proto__).toEqual({ nestedPolluted: true });
+ expect(hookNested.nestedPolluted).toBeUndefined();
+ expect(hookNested.text).toBe('nested keep');
+
+ const requestArguments = mockClient.toolRouter.session.execute.mock.calls[0]?.[1]
+ ?.arguments as Record<string, unknown>;
+ expect(Object.getPrototypeOf(requestArguments)).toBe(Object.prototype);
+ expect(Object.hasOwn(requestArguments, '__proto__')).toBe(true);
+ expect(Object.keys(requestArguments)).toContain('__proto__');
+ expect(requestArguments.__proto__).toEqual({ polluted: true });
+ expect(requestArguments.polluted).toBeUndefined();
+ expect(requestArguments.staged).toEqual(staged);
+ expect(requestArguments.nullable).toBeNull();
+ const requestNested = requestArguments.nested as Record<string, unknown>;
+ expect(Object.getPrototypeOf(requestNested)).toBe(Object.prototype);
+ expect(Object.hasOwn(requestNested, '__proto__')).toBe(true);
+ expect(Object.keys(requestNested)).toContain('__proto__');
+ expect(requestNested).not.toHaveProperty('file');
+ expect(requestNested.__proto__).toEqual({ nestedPolluted: true });
+ expect(requestNested.nestedPolluted).toBeUndefined();
+ expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
+ });
+
+ it('uses raw session schemas for cleanup when modifySchema removes file flags', async () => {
+ const provider = new MockProvider();
+ const session = new ToolRouterSession(
+ mockClient as unknown as ComposioClient,
+ {
+ apiKey: 'test-api-key',
+ provider,
+ dangerouslyAllowAutoUploadDownloadFiles: false,
+ },
+ 'session-123',
+ { type: 'http', url: 'https://mcp.example.com/session-123' }
+ );
+ mockClient.toolRouter.session.tools.mockResolvedValueOnce({
+ items: [mockRawToolWithFileUpload],
+ next_cursor: null,
+ });
+ mockClient.toolRouter.session.execute.mockResolvedValueOnce({
+ data: { ok: true },
+ error: null,
+ log_id: 'session-log',
+ });
+ provider.wrapTools.mockImplementation(tools => tools);
+
+ await session.tools({
+ modifySchema: ({ schema }) => ({
+ ...schema,
+ inputParameters: {
+ type: 'object',
+ properties: {
+ file: { type: 'string' },
+ text: { type: 'string' },
+ },
+ },
+ }),
+ });
+
+ const displayTools = provider.wrapTools.mock.calls[0]?.[0] as Tool[];
+ expect(displayTools[0]?.inputParameters?.properties?.file).not.toHaveProperty(
+ 'file_uploadable'
+ );
+
+ const executeTool = provider.wrapTools.mock.calls[0]?.[1] as (
+ toolSlug: string,
+ input: Record<string, unknown>
+ ) => Promise<unknown>;
+ await executeTool('COMPOSIO_TOOL', { file: '', text: 'keep' });
+
+ expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
+ 'session-123',
+ {
+ tool_slug: 'COMPOSIO_TOOL',
+ arguments: { text: 'keep' },
+ enable_auto_workbench_offload: true,
+ },
+ undefined
+ );
+ });
+
it('warns once per tool when auto-upload is off and the tool has a file-uploadable input', async () => {
const warnSpy = vi.spyOn((await import('../../src/utils/logger')).default, 'warn');
warnSpy.mockImplementation(() => {}); // silence the log in test output