@devries-cameron20 / composio Mirror · read-only / commits / 48ad7caeb
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, 00:45 UTC

Fix CLI tool execution file uploads and in-band warnings (#3078)

## Summary - Hydrate `file_uploadable` tool inputs before CLI tool execution, including nested object and array payloads. - Add temporary-file handling for `execute` payloads so File/Blob data can be passed safely through the CLI. - Surface in-band tool errors as warnings without overriding a successful execution result. - Improve execute temp-file uniqueness and guard in-band error detection against null or undefined data. - Add coverage for upload hydration and execute command behavior. ## Testing - `pnpm test ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts` - `pnpm test ts/packages/cli/test/src/commands/run.cmd.test.ts` - Not run: full repository test suite --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Rahul Tarak committed Mar 31, 2026 at 03:25 UTC 48ad7caeb3bbbc385b014d903fbd1870ef33c5d4
11 files changed +1168 -28
ts/packages/cli/src/commands/root-help.ts
+24 -8
@@ -35,7 +35,7 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [
35 description:
36 'Execute a tool. Validates inputs and connections automatically; use it aggressively.',
37 usage:
38 - 'execute <slug> [-d, --data text] [--dry-run] [--get-schema] | execute -p <slug> -d <text> <slug> -d <text> ...',
38 + 'execute <slug> [-d, --data text] [--file path] [--dry-run] [--get-schema] | execute -p <slug> -d <text> <slug> -d <text> ...',
39 options: [
40 { name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' },
41 {
@@ -47,8 +47,12 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [
47 name: '-p, --parallel',
48 description: 'Execute repeated <slug> -d <text> pairs concurrently',
49 },
50 + {
51 + name: '--file',
52 + description: 'Inject a local file path into the single file_uploadable input',
53 + },
54 { name: '--dry-run', description: 'Validate and preview the tool call without executing it' },
51 - { name: '--get-schema', description: 'Fetch and print the raw tool schema' },
55 + { name: '--get-schema', description: 'Fetch and print the CLI-facing input schema' },
56 ],
57 },
58 {
@@ -192,7 +196,8 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
196 ],
197 },
198 execute: {
195 - usage: 'composio execute <slug> [-d, --data text] [--dry-run] [--get-schema] [--parallel]',
199 + usage:
200 + 'composio execute <slug> [-d, --data text] [--file path] [--dry-run] [--get-schema] [--parallel]',
201 description:
202 'Execute a tool by slug. Validates inputs against cached schemas and checks connections automatically — just try it and it will tell you what to fix.',
203 args: [
@@ -212,9 +217,13 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
217 name: '-p, --parallel',
218 description: 'Execute repeated TOOL_SLUG -d <text> groups concurrently',
219 },
220 + {
221 + name: '--file <path>',
222 + description: 'Inject a local file path into the single file_uploadable input',
223 + },
224 {
225 name: '--get-schema',
217 - description: 'Fetch and print the raw tool schema without executing',
226 + description: 'Fetch and print the CLI-facing input schema without executing',
227 },
228 {
229 name: '--dry-run',
@@ -281,7 +290,10 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
290 { name: '-f, --file <text>', description: 'Run a TS/JS file instead of inline code' },
291 { name: '--dry-run', description: 'Preview execute() calls without running them' },
292 { name: '--debug', description: 'Log helper steps while the script runs' },
284 - { name: '--logs-off', description: 'Hide the always-on experimental_subAgent streaming logs' },
293 + {
294 + name: '--logs-off',
295 + description: 'Hide the always-on experimental_subAgent streaming logs',
296 + },
297 ],
298 flags: [
299 { name: '--skip-connection-check', description: 'Skip the connected-account check' },
@@ -496,7 +508,7 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
508 'tools info': {
509 usage: 'composio tools info [<slug>]',
510 description:
499 - 'View a brief summary of a tool and cache the raw schema used by `composio execute --get-schema`.',
511 + 'View a brief summary of a tool and show the CLI-facing schema used by `composio execute --get-schema`.',
512 args: [{ name: '<slug>', description: 'Tool slug (e.g. "GMAIL_SEND_EMAIL")' }],
513 },
514
@@ -573,17 +585,21 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
585 },
586 'dev playground-execute': {
587 usage:
576 - 'composio dev playground-execute <slug> [-d, --data text] [--user-id text] [--project-name text] [--dry-run] [--get-schema]',
588 + 'composio dev playground-execute <slug> [-d, --data text] [--file path] [--user-id text] [--project-name text] [--dry-run] [--get-schema]',
589 description:
590 'Test tool executions against playground users using your developer project auth configs.',
591 args: [{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' }],
592 options: [
593 { name: '-d, --data <text>', description: 'JSON arguments, @file, or - for stdin' },
594 + {
595 + name: '--file <path>',
596 + description: 'Inject a local file path into the single file_uploadable input',
597 + },
598 { name: '--user-id <text>', description: 'Developer-project user ID override' },
599 { name: '--project-name <text>', description: 'Developer project name override' },
600 {
601 name: '--get-schema',
586 - description: 'Fetch and print the raw tool schema without executing',
602 + description: 'Fetch and print the CLI-facing input schema without executing',
603 },
604 { name: '--dry-run', description: 'Validate and preview without executing' },
605 ],
ts/packages/cli/src/commands/run.cmd.ts
-1
@@ -182,7 +182,6 @@ const resolveRunHelperModuleUrls = (): RunHelperModuleUrls => ({
182 })
183 ).href,
184 });
185 -
185 export const buildRunHelpersSource = (
186 cliPrefix: ReadonlyArray<string>,
187 context: RunHelperContext = {},
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+125 -9
@@ -48,6 +48,7 @@ import {
48 resolveCliSessionArtifacts,
49 } from 'src/services/cli-session-artifacts';
50 import { storeCliSessionArtifact } from 'src/services/cli-session-artifacts';
51 +import { findFileUploadablePaths, normalizeFileUploadSchema } from 'src/services/tool-file-uploads';
52 import {
53 ComposioNoActiveConnectionError,
54 mapComposioError,
@@ -64,6 +65,10 @@ const data = Options.text('data').pipe(
65 Options.withDescription('JSON arguments, @file, or - for stdin'),
66 Options.optional
67 );
68 +const file = Options.text('file').pipe(
69 + Options.withDescription('Inject a local file path into the single file_uploadable input'),
70 + Options.optional
71 +);
72
73 const userId = Options.text('user-id').pipe(
74 Options.optional,
@@ -76,7 +81,7 @@ const projectName = Options.text('project-name').pipe(
81 );
82
83 const getSchema = Options.boolean('get-schema').pipe(
79 - Options.withDescription('Fetch and print the raw tool schema without executing'),
84 + Options.withDescription('Fetch and print the CLI-facing input schema without executing'),
85 Options.withDefault(false)
86 );
87 const dryRun = Options.boolean('dry-run').pipe(
@@ -119,6 +124,88 @@ const parseArguments = (raw: string) =>
124 return parsed as Record<string, unknown>;
125 });
126
127 +const hasNestedKey = (
128 + record: Record<string, unknown>,
129 + pathParts: ReadonlyArray<string>
130 +): boolean => {
131 + let current: unknown = record;
132 + for (const key of pathParts) {
133 + if (typeof current !== 'object' || current === null || Array.isArray(current)) {
134 + return false;
135 + }
136 + if (!(key in (current as Record<string, unknown>))) {
137 + return false;
138 + }
139 + current = (current as Record<string, unknown>)[key];
140 + }
141 + return true;
142 +};
143 +
144 +const setNestedKey = (
145 + record: Record<string, unknown>,
146 + pathParts: ReadonlyArray<string>,
147 + value: unknown
148 +): Record<string, unknown> => {
149 + if (pathParts.length === 0) return record;
150 +
151 + const clone: Record<string, unknown> = { ...record };
152 + let current = clone;
153 +
154 + for (const [index, key] of pathParts.entries()) {
155 + if (index === pathParts.length - 1) {
156 + current[key] = value;
157 + break;
158 + }
159 +
160 + const next = current[key];
161 + const nextObject =
162 + typeof next === 'object' && next !== null && !Array.isArray(next)
163 + ? { ...(next as Record<string, unknown>) }
164 + : {};
165 + current[key] = nextObject;
166 + current = nextObject;
167 + }
168 +
169 + return clone;
170 +};
171 +
172 +const injectSingleFileArgument = (params: {
173 + readonly slug: string;
174 + readonly args: Record<string, unknown>;
175 + readonly filePath: string;
176 + readonly schema: Record<string, unknown>;
177 +}) =>
178 + Effect.gen(function* () {
179 + const uploadablePaths = findFileUploadablePaths(params.schema);
180 +
181 + if (uploadablePaths.length === 0) {
182 + return yield* Effect.fail(
183 + new Error(
184 + `Tool "${params.slug}" has no file_uploadable input. Remove --file or pass JSON via -d.`
185 + )
186 + );
187 + }
188 +
189 + if (uploadablePaths.length > 1) {
190 + return yield* Effect.fail(
191 + new Error(
192 + `Tool "${params.slug}" has multiple file_uploadable inputs (${uploadablePaths.map(parts => parts.join('.')).join(', ')}). Pass the target field explicitly with -d instead of --file.`
193 + )
194 + );
195 + }
196 +
197 + const targetPath = uploadablePaths[0] ?? [];
198 + if (hasNestedKey(params.args, targetPath)) {
199 + return yield* Effect.fail(
200 + new Error(
201 + `Cannot use --file because "${targetPath.join('.')}" is already set in -d. Remove that field or omit --file.`
202 + )
203 + );
204 + }
205 +
206 + return setNestedKey(params.args, targetPath, params.filePath);
207 + });
208 +
209 const connectionTips = (toolSlug: string, surface: 'root' | 'dev') => {
210 const toolkit = toolkitFromToolSlug(toolSlug);
211 const executeStep =
@@ -564,9 +651,12 @@ const handleExecutionError = (
651 return { error: mapped.message, slug: slugValue };
652 });
653
567 -class ToolExecutionError {
654 +class ToolExecutionError extends Error {
655 readonly _tag = 'ToolExecutionError';
569 - constructor(readonly message: string) {}
656 + constructor(readonly message: string) {
657 + super(message);
658 + this.name = 'ToolExecutionError';
659 + }
660 }
661
662 type CachedValidationDecision =
@@ -721,6 +811,7 @@ type DryRunSummary = {
811 type RunToolsExecuteParams = {
812 slug: string;
813 data: Option.Option<string>;
814 + file: Option.Option<string>;
815 userId: Option.Option<string>;
816 projectName: Option.Option<string>;
817 surface: 'root' | 'dev';
@@ -732,7 +823,7 @@ type RunToolsExecuteParams = {
823 skipChecks: boolean;
824 };
825
735 -type SharedRunToolsExecuteParams = Omit<RunToolsExecuteParams, 'slug' | 'data'>;
826 +type SharedRunToolsExecuteParams = Omit<RunToolsExecuteParams, 'slug' | 'data' | 'file'>;
827
828 type ParallelExecuteSpec = {
829 readonly slug: string;
@@ -792,6 +883,7 @@ const emitCachedSchema = (
883 }
884 ) =>
885 Effect.gen(function* () {
886 + const displaySchema = normalizeFileUploadSchema(definition.schema);
887 yield* ui.log.message(
888 `Schema saved, inspect keys like: jq '{required: (.inputSchema.required // []), keys: (.inputSchema.properties | keys)}' ${definition.schemaPath}`
889 );
@@ -801,7 +893,7 @@ const emitCachedSchema = (
893 slug,
894 version: definition.version,
895 schemaPath: definition.schemaPath,
804 - inputSchema: definition.schema,
896 + inputSchema: displaySchema,
897 },
898 null,
899 2
@@ -823,7 +915,7 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
915 const projectContext = yield* ProjectContext;
916
917 const input = (yield* resolveInput(params.data)) ?? '{}';
826 - const args = yield* parseArguments(input);
918 + const parsedArgs = yield* parseArguments(input);
919 const localProjectContext = yield* projectContext.resolve.pipe(
920 Effect.catchAll(() => Effect.succeed(Option.none()))
921 );
@@ -850,6 +942,21 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
942 orgId: resolvedProject.orgId,
943 projectId: resolvedProject.projectId,
944 });
945 + const args = Option.isSome(params.file)
946 + ? yield* getOrFetchToolInputDefinition(params.slug, {
947 + orgId: resolvedProject.orgId,
948 + projectId: resolvedProject.projectId,
949 + }).pipe(
950 + Effect.flatMap(definition =>
951 + injectSingleFileArgument({
952 + slug: params.slug,
953 + args: parsedArgs,
954 + filePath: Option.getOrThrow(params.file),
955 + schema: definition.schema,
956 + })
957 + )
958 + )
959 + : parsedArgs;
960 const executeOutputDir =
961 process.env.COMPOSIO_RUN_OUTPUT_DIR?.trim() ||
962 Option.getOrUndefined(
@@ -1545,7 +1652,7 @@ const runParallelSchemaFetchFromParsed = (params: ParsedParallelExecuteArgs) =>
1652 successful: true,
1653 version: definition.version,
1654 schemaPath: definition.schemaPath,
1548 - inputSchema: definition.schema,
1655 + inputSchema: normalizeFileUploadSchema(definition.schema),
1656 } satisfies Extract<
1657 ParallelExecuteResult,
1658 { readonly inputSchema: Record<string, unknown> }
@@ -1610,6 +1717,7 @@ const runParallelToolsExecuteFromParsed = (params: ParsedParallelExecuteArgs) =>
1717 resolveExecuteContext({
1718 slug: spec.slug,
1719 data: spec.data,
1720 + file: Option.none(),
1721 userId: params.userId,
1722 projectName: params.projectName,
1723 surface: params.surface,
@@ -1791,11 +1899,12 @@ export const runParallelToolsExecuteFromArgv = (argv: ReadonlyArray<string>) =>
1899
1900 export const rootToolsCmd$Execute = Command.make(
1901 'execute',
1794 - { slug, data, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, skipChecks },
1795 - ({ slug, data, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, skipChecks }) =>
1902 + { slug, data, file, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, skipChecks },
1903 + ({ slug, data, file, getSchema, dryRun, skipConnectionCheck, skipToolParamsCheck, skipChecks }) =>
1904 runToolsExecute({
1905 slug,
1906 data,
1907 + file,
1908 userId: Option.none(),
1909 projectName: Option.none(),
1910 surface: 'root',
@@ -1814,11 +1923,13 @@ export const rootToolsCmd$Execute = Command.make(
1923 '',
1924 'Examples:',
1925 ' composio execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1926 + ' composio execute SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK --file ./image.png -d \'{ channels: "C123" }\'',
1927 ' composio execute --parallel GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com" }\' GITHUB_CREATE_AN_ISSUE -d \'{ owner: "acme", repo: "app", title: "Bug" }\'',
1928 " composio execute GMAIL_SEND_EMAIL --dry-run -d '{ ... }' Preview without executing",
1929 ' composio execute GMAIL_SEND_EMAIL --get-schema Fetch and print the input schema',
1930 '',
1931 'Flags:',
1932 + ' --file <path> Inject a local file path into the single file_uploadable input',
1933 ' -p, --parallel Execute repeated TOOL_SLUG -d <json> groups concurrently',
1934 ' --skip-connection-check Skip the connected-account check',
1935 ' --skip-tool-params-check Skip input validation against cached schema',
@@ -1837,6 +1948,7 @@ export const devToolsCmd$Execute = Command.make(
1948 {
1949 slug,
1950 data,
1951 + file,
1952 userId,
1953 projectName,
1954 getSchema,
@@ -1848,6 +1960,7 @@ export const devToolsCmd$Execute = Command.make(
1960 ({
1961 slug,
1962 data,
1963 + file,
1964 userId,
1965 projectName,
1966 getSchema,
@@ -1859,6 +1972,7 @@ export const devToolsCmd$Execute = Command.make(
1972 runToolsExecute({
1973 slug,
1974 data,
1975 + file,
1976 userId,
1977 projectName,
1978 surface: 'dev',
@@ -1878,10 +1992,12 @@ export const devToolsCmd$Execute = Command.make(
1992 '',
1993 'Examples:',
1994 ' composio dev playground-execute GMAIL_SEND_EMAIL -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1995 + ' composio dev playground-execute SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK --file ./image.png -d \'{ channels: "C123" }\'',
1996 ' composio dev playground-execute GMAIL_SEND_EMAIL --dry-run -d \'{ recipient_email: "a@b.com", body: "Hello" }\'',
1997 ' composio dev playground-execute GMAIL_SEND_EMAIL --get-schema',
1998 '',
1999 'Flags:',
2000 + ' --file <path> Inject a local file path into the single file_uploadable input',
2001 ' -p, --parallel Execute repeated TOOL_SLUG -d <json> groups concurrently',
2002 ].join('\n')
2003 )
ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts
+7 -2
@@ -5,6 +5,7 @@ import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { handleHttpServerError } from 'src/effects/handle-http-error';
7 import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
8 +import { normalizeFileUploadSchema } from 'src/services/tool-file-uploads';
9 import { bold } from 'src/ui/colors';
10 import { commandHintExample, commandHintStep } from 'src/services/command-hints';
11
@@ -31,7 +32,9 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
32 // Missing slug guard
33 if (Option.isNone(slug)) {
34 yield* ui.log.warn('Missing required argument: <slug>');
34 - yield* ui.log.step('Try specifying a tool slug, e.g.:\n> composio tools info "GMAIL_SEND_EMAIL"');
35 + yield* ui.log.step(
36 + 'Try specifying a tool slug, e.g.:\n> composio tools info "GMAIL_SEND_EMAIL"'
37 + );
38 return;
39 }
40
@@ -69,6 +72,7 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
72
73 const tool = toolOpt.value;
74 const definition = yield* getOrFetchToolInputDefinition(slugValue);
75 + const displaySchema = normalizeFileUploadSchema(definition.schema);
76
77 const summary = [
78 `${bold('Slug:')} ${tool.slug}`,
@@ -97,6 +101,7 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
101 toolkit: tool.toolkit.slug,
102 version: definition.version,
103 schemaPath: definition.schemaPath,
104 + inputSchema: displaySchema,
105 },
106 null,
107 2
@@ -105,6 +110,6 @@ export const toolsCmd$Info = Command.make('info', { slug }, ({ slug }) =>
110 })
111 ).pipe(
112 Command.withDescription(
108 - 'View a brief summary of a tool and cache the same raw schema used by `composio execute --get-schema`.'
113 + 'View a brief summary of a tool and show the CLI-facing input schema used by `composio execute`.'
114 )
115 );
ts/packages/cli/src/services/run-helpers-runtime.ts
+68 -2
@@ -1,8 +1,10 @@
1 import * as fs from 'node:fs';
2 +import * as os from 'node:os';
3 +import * as path from 'node:path';
4 import process from 'node:process';
5 import { z } from 'zod';
6 import type { MasterKind } from 'src/services/master-detector';
5 -import { isAcpInvokeError, type InvokeAgentTarget } from 'src/services/run-subagent-shared';
7 +import { isAcpInvokeError } from 'src/services/run-subagent-shared';
8 import { invokeAcpSubAgent } from 'src/services/run-subagent-acp';
9 import { invokeLegacySubAgent } from 'src/services/run-subagent-legacy';
10
@@ -209,6 +211,7 @@ export const installRunHelpers = async ({
211 if (!perfDebugEnabled) return;
212 const elapsedMs = Date.now() - perfDebugStart;
213 const payload = { phase, label, elapsedMs, ...details };
214 + // eslint-disable-next-line no-console
215 console.error(`[perf] ${JSON.stringify(payload)}`);
216 };
217
@@ -348,6 +351,67 @@ export const installRunHelpers = async ({
351 return value;
352 };
353
354 + const isPlainObjectForExecute = (value: unknown): value is Record<string, unknown> =>
355 + typeof value === 'object' && value !== null && !Array.isArray(value);
356 +
357 + const runFileExtensionFromMimeType = (mimeType: string | undefined): string => {
358 + if (typeof mimeType !== 'string' || mimeType.trim().length === 0) return 'bin';
359 + const normalized = mimeType.split(';')[0]?.trim().toLowerCase() ?? '';
360 + const explicit: Record<string, string> = {
361 + 'text/plain': 'txt',
362 + 'application/json': 'json',
363 + 'application/pdf': 'pdf',
364 + 'image/jpeg': 'jpg',
365 + 'image/png': 'png',
366 + 'image/webp': 'webp',
367 + 'image/gif': 'gif',
368 + };
369 + if (explicit[normalized]) return explicit[normalized];
370 + const subtype = normalized.split('/')[1] || 'bin';
371 + return subtype.includes('+') ? (subtype.split('+').pop() ?? 'bin') : subtype;
372 + };
373 +
374 + const writeTempExecuteFile = async (value: unknown): Promise<unknown> => {
375 + const outputDir = sharedRunOutputDir || path.join(os.tmpdir(), 'composio-run-files');
376 + fs.mkdirSync(outputDir, { recursive: true });
377 + if (typeof File !== 'undefined' && value instanceof File) {
378 + const safeName =
379 + typeof value.name === 'string' && value.name.trim().length > 0
380 + ? value.name
381 + : `file-${executeId()}.${runFileExtensionFromMimeType(value.type)}`;
382 + const filePath = path.join(outputDir, `${executeId()}-${safeName}`);
383 + fs.writeFileSync(filePath, new Uint8Array(await value.arrayBuffer()));
384 + return filePath;
385 + }
386 + if (typeof Blob !== 'undefined' && value instanceof Blob) {
387 + const filePath = path.join(
388 + outputDir,
389 + `${executeId()}.${runFileExtensionFromMimeType(value.type)}`
390 + );
391 + fs.writeFileSync(filePath, new Uint8Array(await value.arrayBuffer()));
392 + return filePath;
393 + }
394 + return value;
395 + };
396 +
397 + const materializeExecutePayload = async (value: unknown): Promise<unknown> => {
398 + if (typeof File !== 'undefined' && value instanceof File) return writeTempExecuteFile(value);
399 + if (typeof Blob !== 'undefined' && value instanceof Blob) return writeTempExecuteFile(value);
400 + if (Array.isArray(value)) {
401 + return Promise.all(value.map(item => materializeExecutePayload(item)));
402 + }
403 + if (isPlainObjectForExecute(value)) {
404 + const entries = await Promise.all(
405 + Object.entries(value).map(async ([key, entryValue]) => [
406 + key,
407 + await materializeExecutePayload(entryValue),
408 + ])
409 + );
410 + return Object.fromEntries(entries);
411 + }
412 + return value;
413 + };
414 +
415 const maybeLoadStoredCliResult = (result: RunCliResult): RunCliResult => {
416 if (!result || typeof result !== 'object' || result.storedInFile !== true) {
417 return attachPromptMethod(result);
@@ -682,7 +746,9 @@ export const installRunHelpers = async ({
746 if (helperContext.skipToolParamsCheck === true) args.push('--skip-tool-params-check');
747 if (helperContext.skipChecks === true) args.push('--skip-checks');
748 if (data !== undefined) {
685 - const serialized = typeof data === 'string' ? data : JSON.stringify(data);
749 + const preparedData = await materializeExecutePayload(data);
750 + const serialized =
751 + typeof preparedData === 'string' ? preparedData : JSON.stringify(preparedData);
752 if (sharedRunOutputDir) {
753 const tmpFile = `${sharedRunOutputDir}/execute-data-${slug}-${executeId()}.json`;
754 fs.writeFileSync(tmpFile, serialized, 'utf8');
ts/packages/cli/src/services/tool-file-uploads.ts new
+290
@@ -0,0 +1,290 @@
1 +import fs from 'node:fs/promises';
2 +import path from 'node:path';
3 +import type { Composio as RawComposioClient } from '@composio/client';
4 +import { toolkitFromToolSlug } from 'src/utils/toolkit-from-tool-slug';
5 +
6 +type JsonSchema = Record<string, unknown>;
7 +
8 +const isRecord = (value: unknown): value is Record<string, unknown> =>
9 + typeof value === 'object' && value !== null && !Array.isArray(value);
10 +
11 +const isFileLike = (value: unknown): value is File =>
12 + typeof File !== 'undefined' && value instanceof File;
13 +
14 +const isSchemaRecord = (value: unknown): value is JsonSchema => isRecord(value);
15 +
16 +const getSchemaVariants = (schema: JsonSchema | undefined): ReadonlyArray<JsonSchema> => [
17 + ...((Array.isArray(schema?.anyOf) ? schema.anyOf : []) as JsonSchema[]),
18 + ...((Array.isArray(schema?.oneOf) ? schema.oneOf : []) as JsonSchema[]),
19 + ...((Array.isArray(schema?.allOf) ? schema.allOf : []) as JsonSchema[]),
20 +];
21 +
22 +const transformSchema = (schema: JsonSchema): JsonSchema => {
23 + if (schema.file_uploadable === true) {
24 + return {
25 + title: schema.title,
26 + description: schema.description,
27 + format: 'path',
28 + type: 'string',
29 + file_uploadable: true,
30 + };
31 + }
32 +
33 + const transformed: JsonSchema = { ...schema };
34 +
35 + if (isSchemaRecord(schema.properties)) {
36 + transformed.properties = Object.fromEntries(
37 + Object.entries(schema.properties).map(([key, value]) => [
38 + key,
39 + isSchemaRecord(value) ? transformSchema(value) : value,
40 + ])
41 + );
42 + }
43 +
44 + for (const key of ['anyOf', 'oneOf', 'allOf'] as const) {
45 + if (Array.isArray(schema[key])) {
46 + transformed[key] = schema[key].map(value =>
47 + isSchemaRecord(value) ? transformSchema(value) : value
48 + );
49 + }
50 + }
51 +
52 + if (Array.isArray(schema.items)) {
53 + transformed.items = schema.items.map(value =>
54 + isSchemaRecord(value) ? transformSchema(value) : value
55 + );
56 + } else if (isSchemaRecord(schema.items)) {
57 + transformed.items = transformSchema(schema.items);
58 + }
59 +
60 + return transformed;
61 +};
62 +
63 +export const normalizeFileUploadSchema = (schema: JsonSchema): JsonSchema =>
64 + isSchemaRecord(schema) ? transformSchema(schema) : schema;
65 +
66 +export const schemaHasFileUploadable = (schema: JsonSchema | undefined): boolean => {
67 + if (!schema) return false;
68 + if (schema.file_uploadable === true) return true;
69 +
70 + if (isSchemaRecord(schema.properties)) {
71 + for (const property of Object.values(schema.properties)) {
72 + if (isSchemaRecord(property) && schemaHasFileUploadable(property)) {
73 + return true;
74 + }
75 + }
76 + }
77 +
78 + for (const variant of getSchemaVariants(schema)) {
79 + if (schemaHasFileUploadable(variant)) {
80 + return true;
81 + }
82 + }
83 +
84 + if (Array.isArray(schema.items)) {
85 + return schema.items.some(item => isSchemaRecord(item) && schemaHasFileUploadable(item));
86 + }
87 +
88 + if (isSchemaRecord(schema.items)) {
89 + return schemaHasFileUploadable(schema.items);
90 + }
91 +
92 + return false;
93 +};
94 +
95 +export const findFileUploadablePaths = (
96 + schema: JsonSchema | undefined,
97 + basePath: ReadonlyArray<string> = []
98 +): ReadonlyArray<ReadonlyArray<string>> => {
99 + if (!schema) return [];
100 +
101 + if (schema.file_uploadable === true) {
102 + return [basePath];
103 + }
104 +
105 + const directPropertyPaths = isSchemaRecord(schema.properties)
106 + ? Object.entries(schema.properties).flatMap(([key, property]) =>
107 + isSchemaRecord(property) ? findFileUploadablePaths(property, [...basePath, key]) : []
108 + )
109 + : [];
110 +
111 + const variantPaths = getSchemaVariants(schema).flatMap(variant =>
112 + findFileUploadablePaths(variant, basePath)
113 + );
114 +
115 + const itemPaths = Array.isArray(schema.items)
116 + ? schema.items.flatMap(item =>
117 + isSchemaRecord(item) ? findFileUploadablePaths(item, basePath) : []
118 + )
119 + : isSchemaRecord(schema.items)
120 + ? findFileUploadablePaths(schema.items, basePath)
121 + : [];
122 +
123 + const seen = new Set<string>();
124 + return [...directPropertyPaths, ...variantPaths, ...itemPaths].filter(pathParts => {
125 + const key = pathParts.join('.');
126 + if (seen.has(key)) return false;
127 + seen.add(key);
128 + return true;
129 + });
130 +};
131 +
132 +const readFileFromUrl = async (url: string) => {
133 + const response = await fetch(url);
134 + if (!response.ok) {
135 + throw new Error(`Failed to fetch file: ${response.statusText}`);
136 + }
137 +
138 + const bytes = new Uint8Array(await response.arrayBuffer());
139 + const parsedUrl = new URL(url);
140 + const fileName = path.basename(parsedUrl.pathname) || `file-${Date.now()}`;
141 +
142 + return {
143 + bytes,
144 + fileName,
145 + mimeType: response.headers.get('content-type') || 'application/octet-stream',
146 + };
147 +};
148 +
149 +const readFileFromDisk = async (filePath: string) => ({
150 + bytes: new Uint8Array(await fs.readFile(filePath)),
151 + fileName: path.basename(filePath),
152 + mimeType: 'application/octet-stream',
153 +});
154 +
155 +const readUploadSource = async (file: string | File) => {
156 + if (isFileLike(file)) {
157 + return {
158 + bytes: new Uint8Array(await file.arrayBuffer()),
159 + fileName: file.name || `file-${Date.now()}`,
160 + mimeType: file.type || 'application/octet-stream',
161 + };
162 + }
163 +
164 + if (typeof file === 'string' && /^https?:\/\//i.test(file)) {
165 + return readFileFromUrl(file);
166 + }
167 +
168 + if (typeof file === 'string') {
169 + return readFileFromDisk(file);
170 + }
171 +
172 + throw new Error('Unsupported upload source');
173 +};
174 +
175 +const uploadFile = async (params: {
176 + readonly file: string | File;
177 + readonly toolSlug: string;
178 + readonly toolkitSlug: string;
179 + readonly client: RawComposioClient;
180 +}) => {
181 + const fileData = await readUploadSource(params.file);
182 + const { createHash } = await import('node:crypto');
183 + const md5 = createHash('md5').update(fileData.bytes).digest('hex');
184 + const presigned = await params.client.files.createPresignedURL({
185 + filename: fileData.fileName,
186 + mimetype: fileData.mimeType,
187 + md5,
188 + tool_slug: params.toolSlug,
189 + toolkit_slug: params.toolkitSlug,
190 + });
191 +
192 + const uploadResponse = await fetch(presigned.new_presigned_url, {
193 + method: 'PUT',
194 + body: fileData.bytes,
195 + headers: {
196 + 'Content-Type': fileData.mimeType,
197 + 'Content-Length': fileData.bytes.byteLength.toString(),
198 + },
199 + });
200 +
201 + if (!uploadResponse.ok) {
202 + throw new Error(`Failed to upload file to S3: ${uploadResponse.statusText}`);
203 + }
204 +
205 + return {
206 + name: fileData.fileName,
207 + mimetype: fileData.mimeType,
208 + s3key: presigned.key,
209 + };
210 +};
211 +
212 +const hydrateFileUploads = async (
213 + value: unknown,
214 + schema: JsonSchema | undefined,
215 + ctx: {
216 + readonly toolSlug: string;
217 + readonly toolkitSlug: string;
218 + readonly client: RawComposioClient;
219 + }
220 +): Promise<unknown> => {
221 + if (schema?.file_uploadable === true) {
222 + if (typeof value !== 'string' && !isFileLike(value)) {
223 + return value;
224 + }
225 +
226 + return uploadFile({
227 + file: value,
228 + toolSlug: ctx.toolSlug,
229 + toolkitSlug: ctx.toolkitSlug,
230 + client: ctx.client,
231 + });
232 + }
233 +
234 + const uploadableVariants = getSchemaVariants(schema).filter(schemaHasFileUploadable);
235 + if (uploadableVariants.length > 0) {
236 + let nextValue = value;
237 + for (const variant of uploadableVariants) {
238 + nextValue = await hydrateFileUploads(nextValue, variant, ctx);
239 + }
240 + return nextValue;
241 + }
242 +
243 + if (isSchemaRecord(schema?.properties) && isRecord(value)) {
244 + const entries = await Promise.all(
245 + Object.entries(value).map(async ([key, entryValue]) => [
246 + key,
247 + await hydrateFileUploads(
248 + entryValue,
249 + isSchemaRecord((schema.properties as Record<string, unknown>)[key])
250 + ? ((schema.properties as Record<string, unknown>)[key] as JsonSchema)
251 + : undefined,
252 + ctx
253 + ),
254 + ])
255 + );
256 + return Object.fromEntries(entries);
257 + }
258 +
259 + if (schema?.type === 'array' && Array.isArray(value) && schema.items) {
260 + const itemSchema = Array.isArray(schema.items)
261 + ? schema.items.find(isSchemaRecord)
262 + : isSchemaRecord(schema.items)
263 + ? schema.items
264 + : undefined;
265 +
266 + return Promise.all(value.map(item => hydrateFileUploads(item, itemSchema, ctx)));
267 + }
268 +
269 + return value;
270 +};
271 +
272 +export const uploadToolInputFiles = async (params: {
273 + readonly toolSlug: string;
274 + readonly arguments_: Record<string, unknown>;
275 + readonly inputSchema: JsonSchema;
276 + readonly client: RawComposioClient;
277 + readonly toolkitSlug?: string;
278 +}): Promise<Record<string, unknown>> => {
279 + if (!schemaHasFileUploadable(params.inputSchema)) {
280 + return params.arguments_;
281 + }
282 +
283 + const hydrated = await hydrateFileUploads(params.arguments_, params.inputSchema, {
284 + toolSlug: params.toolSlug,
285 + toolkitSlug: params.toolkitSlug ?? toolkitFromToolSlug(params.toolSlug) ?? 'unknown',
286 + client: params.client,
287 + });
288 +
289 + return isRecord(hydrated) ? hydrated : params.arguments_;
290 +};
ts/packages/cli/src/services/tool-input-validation.ts
+3 -1
@@ -6,6 +6,7 @@ import { z } from 'zod/v3';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 import { ComposioToolkitsRepository, getLatestToolVersion } from 'src/services/composio-clients';
8 import { isToolDebugEnabled } from 'src/services/runtime-debug-flags';
9 +import { normalizeFileUploadSchema } from 'src/services/tool-file-uploads';
10 import { ComposioUserContext } from 'src/services/user-context';
11
12 const TOOL_DEFINITIONS_DIR = 'tool_definitions';
@@ -373,9 +374,10 @@ export const validateToolInputArgumentsWithDefinition = (
374 Effect.gen(function* () {
375 const { schemaPath, schema } = definition;
376 const allowedKeys = getObjectSchemaProperties(schema);
377 + const normalizedSchema = normalizeFileUploadSchema(schema);
378
379 const zodSchema = yield* Effect.try({
378 - try: () => jsonSchemaToZodSchema<z.ZodTypeAny>(schema),
380 + try: () => jsonSchemaToZodSchema<z.ZodTypeAny>(normalizedSchema),
381 catch: error =>
382 new ToolInputValidationError(
383 slug,
ts/packages/cli/src/services/tools-executor.ts
+32 -4
@@ -5,12 +5,18 @@ import type {
5 SessionExecuteMetaResponse,
6 SessionExecuteMetaParams,
7 } from '@composio/client/resources/tool-router';
8 +import type { FileSystem } from '@effect/platform';
9 import { ComposioClientSingleton } from 'src/services/composio-clients';
10 import { createToolRouterSession } from 'src/effects/create-tool-router-session';
11 import {
12 ComposioNoActiveConnectionError,
13 mapComposioError,
14 } from 'src/services/composio-error-overrides';
15 +import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
16 +import { uploadToolInputFiles } from 'src/services/tool-file-uploads';
17 +import type { NodeOs } from 'src/services/node-os';
18 +import type { ComposioUserContext } from 'src/services/user-context';
19 +import type { ComposioToolkitsRepository } from 'src/services/composio-clients';
20
21 /**
22 * Parameters accepted by the Tool Router-based executor.
@@ -35,7 +41,11 @@ export interface ToolsExecutor {
41 readonly execute: (
42 slug: string,
43 params: ToolExecuteParams
38 - ) => Effect.Effect<ToolExecuteResponse, unknown>;
44 + ) => Effect.Effect<
45 + ToolExecuteResponse,
46 + unknown,
47 + FileSystem.FileSystem | NodeOs | ComposioUserContext | ComposioToolkitsRepository
48 + >;
49 }
50
51 export const ToolsExecutor = Context.GenericTag<ToolsExecutor>('services/ToolsExecutor');
@@ -103,7 +113,6 @@ export const detectInBandWarning = (
113 if (typeof data.message === 'string') return data.message;
114 return 'Tool response indicates unsuccessful execution';
115 }
106 -
116 return null;
117 };
118
@@ -124,18 +133,37 @@ export const ToolsExecutorLive = Layer.effect(
133 const sessionId = yield* createToolRouterSession(resolvedClient, params.userId, {
134 manageConnections: true,
135 });
136 + const normalizedArguments = isMetaToolSlug(slug)
137 + ? params.arguments
138 + : yield* getOrFetchToolInputDefinition(slug).pipe(
139 + Effect.catchAll(() => Effect.succeed(null)),
140 + Effect.flatMap(definition => {
141 + if (!definition) {
142 + return Effect.succeed(params.arguments);
143 + }
144 +
145 + return Effect.tryPromise(() =>
146 + uploadToolInputFiles({
147 + toolSlug: slug,
148 + arguments_: params.arguments,
149 + inputSchema: definition.schema,
150 + client: resolvedClient,
151 + })
152 + );
153 + })
154 + );
155
156 const raw: SessionExecuteResponse | SessionExecuteMetaResponse = yield* Effect.tryPromise(
157 () => {
158 if (isMetaToolSlug(slug)) {
159 return resolvedClient.toolRouter.session.executeMeta(sessionId, {
160 slug,
133 - arguments: params.arguments,
161 + arguments: normalizedArguments,
162 });
163 }
164 return resolvedClient.toolRouter.session.execute(sessionId, {
165 tool_slug: slug,
138 - arguments: params.arguments,
166 + arguments: normalizedArguments,
167 });
168 }
169 );
ts/packages/cli/test/__utils__/services/test-layer.ts
+12
@@ -979,6 +979,18 @@ export const TestLayer = (input?: TestLiveInput) =>
979 };
980 },
981 },
982 + files: {
983 + createPresignedURL: async (params: {
984 + filename: string;
985 + mimetype: string;
986 + md5: string;
987 + tool_slug: string;
988 + toolkit_slug: string;
989 + }) => ({
990 + key: `uploads/${params.filename}`,
991 + new_presigned_url: 'https://s3.test.composio.dev/upload',
992 + }),
993 + },
994 toolRouter: {
995 session: {
996 create:
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+539 -1
@@ -1,4 +1,6 @@
1 import * as fs from 'node:fs';
2 +import * as os from 'node:os';
3 +import * as path from 'node:path';
4 import { describe, expect, layer } from '@effect/vitest';
5 import { vi, beforeEach, afterEach } from 'vitest';
6 import { ConfigProvider, Effect, Option } from 'effect';
@@ -86,6 +88,70 @@ describe('CLI: composio execute', () => {
88 );
89 });
90
91 + layer(
92 + TestLive({
93 + baseConfigProvider: testConfigProvider,
94 + fixture: 'global-test-user-id',
95 + toolkitsData: {
96 + tools: [
97 + {
98 + name: 'Upload Slack File',
99 + slug: 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK',
100 + description: 'Uploads a file to Slack',
101 + tags: ['slack'],
102 + available_versions: ['20260316_00'],
103 + input_parameters: {
104 + type: 'object',
105 + properties: {
106 + channels: { type: 'string' },
107 + file: {
108 + type: 'object',
109 + file_uploadable: true,
110 + title: 'File',
111 + description: 'Local file accepted by CLI',
112 + properties: {
113 + name: { type: 'string' },
114 + mimetype: { type: 'string' },
115 + s3key: { type: 'string' },
116 + },
117 + required: ['name', 'mimetype', 's3key'],
118 + },
119 + },
120 + },
121 + output_parameters: {
122 + type: 'object',
123 + properties: {},
124 + },
125 + },
126 + ],
127 + } satisfies TestLiveInput['toolkitsData'],
128 + })
129 + )('[Given] file_uploadable schema [Then] execute --get-schema shows a path string input', it => {
130 + it.scoped('renders the CLI-facing schema instead of the raw FileUploadable object', () =>
131 + Effect.gen(function* () {
132 + yield* cli(['execute', 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK', '--get-schema']);
133 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
134 + const output = parseLastJson(lines) as unknown as {
135 + inputSchema: Record<string, unknown>;
136 + };
137 +
138 + expect(output.inputSchema).toEqual({
139 + type: 'object',
140 + properties: {
141 + channels: { type: 'string' },
142 + file: {
143 + title: 'File',
144 + description: 'Local file accepted by CLI',
145 + format: 'path',
146 + type: 'string',
147 + file_uploadable: true,
148 + },
149 + },
150 + });
151 + })
152 + );
153 + });
154 +
155 layer(
156 TestLive({
157 baseConfigProvider: testConfigProvider,
@@ -586,6 +652,478 @@ describe('CLI: composio execute', () => {
652 );
653 });
654
655 + layer(
656 + TestLive({
657 + baseConfigProvider: testConfigProvider,
658 + fixture: 'global-test-user-id',
659 + stdin: { isTTY: true, data: '' },
660 + toolkitsData: {
661 + tools: [
662 + {
663 + name: 'Send Email',
664 + slug: 'GMAIL_SEND_EMAIL',
665 + description: 'Send an email with attachment',
666 + tags: ['email'],
667 + available_versions: ['20260316_00'],
668 + input_parameters: {
669 + type: 'object',
670 + properties: {
671 + recipient_email: { type: 'string' },
672 + attachment: {
673 + file_uploadable: true,
674 + title: 'Attachment',
675 + description: 'Local path or URL to upload',
676 + },
677 + },
678 + },
679 + output_parameters: {
680 + type: 'object',
681 + properties: {
682 + message_id: { type: 'string' },
683 + },
684 + },
685 + },
686 + ],
687 + } satisfies TestLiveInput['toolkitsData'],
688 + })
689 + )(
690 + '[Given] file_uploadable input as a local path [Then] execute uploads and sends s3key data',
691 + it => {
692 + it.scoped('uploads local file paths before Tool Router execution', () =>
693 + Effect.gen(function* () {
694 + const tempFile = path.join(os.tmpdir(), `composio-upload-${Date.now()}.txt`);
695 + fs.writeFileSync(tempFile, 'hello from cli upload', 'utf8');
696 +
697 + const originalFetch = globalThis.fetch;
698 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {
699 + const url =
700 + typeof input === 'string'
701 + ? input
702 + : input instanceof URL
703 + ? input.toString()
704 + : input.url;
705 + if (url === 'https://s3.test.composio.dev/upload') {
706 + return Promise.resolve(new Response(null, { status: 200 }));
707 + }
708 + return originalFetch(input, init);
709 + });
710 +
711 + yield* cli([
712 + 'execute',
713 + 'GMAIL_SEND_EMAIL',
714 + '-d',
715 + JSON.stringify({
716 + recipient_email: 'a@b.com',
717 + attachment: tempFile,
718 + }),
719 + ]);
720 +
721 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
722 + const output = parseLastJson(lines);
723 +
724 + expect(output.successful).toBe(true);
725 + expect(output.data.arguments).toEqual({
726 + recipient_email: 'a@b.com',
727 + attachment: {
728 + name: path.basename(tempFile),
729 + mimetype: 'application/octet-stream',
730 + s3key: `uploads/${path.basename(tempFile)}`,
731 + },
732 + });
733 + expect(fetchSpy).toHaveBeenCalledWith(
734 + 'https://s3.test.composio.dev/upload',
735 + expect.objectContaining({
736 + method: 'PUT',
737 + headers: expect.objectContaining({
738 + 'Content-Type': 'application/octet-stream',
739 + }),
740 + })
741 + );
742 +
743 + fs.rmSync(tempFile, { force: true });
744 + })
745 + );
746 + }
747 + );
748 +
749 + layer(
750 + TestLive({
751 + baseConfigProvider: testConfigProvider,
752 + fixture: 'global-test-user-id',
753 + stdin: { isTTY: true, data: '' },
754 + toolkitsData: {
755 + tools: [
756 + {
757 + name: 'Upload Slack File',
758 + slug: 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK',
759 + description: 'Uploads a file to Slack',
760 + tags: ['slack'],
761 + available_versions: ['20260316_00'],
762 + input_parameters: {
763 + type: 'object',
764 + properties: {
765 + channels: { type: 'string' },
766 + file: {
767 + type: 'object',
768 + file_uploadable: true,
769 + title: 'File',
770 + description: 'Local file accepted by CLI',
771 + properties: {
772 + name: { type: 'string' },
773 + mimetype: { type: 'string' },
774 + s3key: { type: 'string' },
775 + },
776 + required: ['name', 'mimetype', 's3key'],
777 + },
778 + },
779 + },
780 + output_parameters: {
781 + type: 'object',
782 + properties: {},
783 + },
784 + },
785 + ],
786 + } satisfies TestLiveInput['toolkitsData'],
787 + })
788 + )(
789 + '[Given] --file for a tool with one file_uploadable input [Then] execute injects it automatically',
790 + it => {
791 + it.scoped('injects into the single file_uploadable field before upload hydration', () =>
792 + Effect.gen(function* () {
793 + const tempFile = path.join(os.tmpdir(), `composio-inject-${Date.now()}.png`);
794 + fs.writeFileSync(tempFile, 'png-binary-ish', 'utf8');
795 +
796 + const originalFetch = globalThis.fetch;
797 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {
798 + const url =
799 + typeof input === 'string'
800 + ? input
801 + : input instanceof URL
802 + ? input.toString()
803 + : input.url;
804 + if (url === 'https://s3.test.composio.dev/upload') {
805 + return Promise.resolve(new Response(null, { status: 200 }));
806 + }
807 + return originalFetch(input, init);
808 + });
809 +
810 + yield* cli([
811 + 'execute',
812 + 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK',
813 + '--skip-connection-check',
814 + '--file',
815 + tempFile,
816 + '-d',
817 + JSON.stringify({ channels: 'C123' }),
818 + ]);
819 +
820 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
821 + const output = parseLastJson(lines);
822 +
823 + expect(output.successful).toBe(true);
824 + expect(output.data.arguments).toEqual({
825 + channels: 'C123',
826 + file: {
827 + name: path.basename(tempFile),
828 + mimetype: 'application/octet-stream',
829 + s3key: `uploads/${path.basename(tempFile)}`,
830 + },
831 + });
832 + expect(fetchSpy).toHaveBeenCalled();
833 +
834 + fs.rmSync(tempFile, { force: true });
835 + })
836 + );
837 + }
838 + );
839 +
840 + layer(
841 + TestLive({
842 + baseConfigProvider: testConfigProvider,
843 + fixture: 'global-test-user-id',
844 + stdin: { isTTY: true, data: '' },
845 + toolkitsData: {
846 + tools: [
847 + {
848 + name: 'Nested Upload',
849 + slug: 'NESTED_UPLOAD_TOOL',
850 + description: 'Uploads a nested file',
851 + tags: ['test'],
852 + available_versions: ['20260316_00'],
853 + input_parameters: {
854 + type: 'object',
855 + properties: {
856 + payload: {
857 + properties: {
858 + file: {
859 + file_uploadable: true,
860 + title: 'File',
861 + description: 'Nested file path',
862 + properties: {
863 + name: { type: 'string' },
864 + mimetype: { type: 'string' },
865 + s3key: { type: 'string' },
866 + },
867 + },
868 + },
869 + },
870 + },
871 + },
872 + output_parameters: {
873 + type: 'object',
874 + properties: {},
875 + },
876 + },
877 + ],
878 + } satisfies TestLiveInput['toolkitsData'],
879 + })
880 + )(
881 + '[Given] a nested file_uploadable path under properties without explicit object type [Then] hydration still uploads it',
882 + it => {
883 + it.scoped('treats property-bearing schema nodes as object-like during upload hydration', () =>
884 + Effect.gen(function* () {
885 + const tempFile = path.join(os.tmpdir(), `composio-nested-${Date.now()}.png`);
886 + fs.writeFileSync(tempFile, 'nested-png-binary-ish', 'utf8');
887 +
888 + const originalFetch = globalThis.fetch;
889 + vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {
890 + const url =
891 + typeof input === 'string'
892 + ? input
893 + : input instanceof URL
894 + ? input.toString()
895 + : input.url;
896 + if (url === 'https://s3.test.composio.dev/upload') {
897 + return Promise.resolve(new Response(null, { status: 200 }));
898 + }
899 + return originalFetch(input, init);
900 + });
901 +
902 + yield* cli([
903 + 'execute',
904 + 'NESTED_UPLOAD_TOOL',
905 + '--skip-connection-check',
906 + '--file',
907 + tempFile,
908 + '-d',
909 + JSON.stringify({ payload: {} }),
910 + ]);
911 +
912 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
913 + const output = parseLastJson(lines);
914 +
915 + expect(output.successful).toBe(true);
916 + expect(output.data.arguments).toEqual({
917 + payload: {
918 + file: {
919 + name: path.basename(tempFile),
920 + mimetype: 'application/octet-stream',
921 + s3key: `uploads/${path.basename(tempFile)}`,
922 + },
923 + },
924 + });
925 +
926 + fs.rmSync(tempFile, { force: true });
927 + })
928 + );
929 + }
930 + );
931 +
932 + layer(
933 + TestLive({
934 + baseConfigProvider: testConfigProvider,
935 + fixture: 'global-test-user-id',
936 + stdin: { isTTY: true, data: '' },
937 + toolkitsData: {
938 + tools: [
939 + {
940 + name: 'Send Email',
941 + slug: 'GMAIL_SEND_EMAIL',
942 + description: 'Send an email with attachment',
943 + tags: ['email'],
944 + available_versions: ['20260316_00'],
945 + input_parameters: {
946 + type: 'object',
947 + properties: {
948 + recipient_email: { type: 'string' },
949 + attachment: {
950 + file_uploadable: true,
951 + title: 'Attachment',
952 + description: 'Local path or URL to upload',
953 + properties: {
954 + name: { type: 'string' },
955 + mimetype: { type: 'string' },
956 + s3key: { type: 'string' },
957 + },
958 + },
959 + },
960 + },
961 + output_parameters: {
962 + type: 'object',
963 + properties: {},
964 + },
965 + },
966 + ],
967 + } satisfies TestLiveInput['toolkitsData'],
968 + })
969 + )(
970 + '[Given] an S3 upload failure [Then] execute surfaces the upload error instead of sending a raw path',
971 + it => {
972 + it.scoped('propagates upload failures from file hydration', () =>
973 + Effect.gen(function* () {
974 + const tempFile = path.join(os.tmpdir(), `composio-upload-fail-${Date.now()}.txt`);
975 + fs.writeFileSync(tempFile, 'hello from failed cli upload', 'utf8');
976 +
977 + const originalFetch = globalThis.fetch;
978 + vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {
979 + const url =
980 + typeof input === 'string'
981 + ? input
982 + : input instanceof URL
983 + ? input.toString()
984 + : input.url;
985 + if (url === 'https://s3.test.composio.dev/upload') {
986 + return Promise.resolve(
987 + new Response('Upload failed', { status: 500, statusText: 'Upload Failed' })
988 + );
989 + }
990 + return originalFetch(input, init);
991 + });
992 +
993 + const failure = yield* cli([
994 + 'execute',
995 + 'GMAIL_SEND_EMAIL',
996 + '--skip-connection-check',
997 + '-d',
998 + JSON.stringify({
999 + recipient_email: 'a@b.com',
1000 + attachment: tempFile,
1001 + }),
1002 + ]).pipe(
1003 + Effect.flip,
1004 + Effect.map(error => (error instanceof Error ? error.message : String(error)))
1005 + );
1006 +
1007 + expect(failure).toContain('Failed to upload file to S3');
1008 +
1009 + fs.rmSync(tempFile, { force: true });
1010 + })
1011 + );
1012 + }
1013 + );
1014 +
1015 + layer(
1016 + TestLive({
1017 + baseConfigProvider: testConfigProvider,
1018 + fixture: 'global-test-user-id',
1019 + stdin: { isTTY: true, data: '' },
1020 + toolkitsData: {
1021 + tools: [
1022 + {
1023 + name: 'Send Email',
1024 + slug: 'GMAIL_SEND_EMAIL',
1025 + description: 'Send an email',
1026 + tags: ['email'],
1027 + available_versions: ['20260316_00'],
1028 + input_parameters: {
1029 + type: 'object',
1030 + properties: {
1031 + recipient_email: { type: 'string' },
1032 + },
1033 + },
1034 + output_parameters: {
1035 + type: 'object',
1036 + properties: {},
1037 + },
1038 + },
1039 + ],
1040 + } satisfies TestLiveInput['toolkitsData'],
1041 + })
1042 + )('[Given] --file for a tool with no file_uploadable input [Then] execute fails clearly', it => {
1043 + it.scoped('rejects the convenience flag when the schema has no file input', () =>
1044 + Effect.gen(function* () {
1045 + const failure = yield* cli([
1046 + 'execute',
1047 + 'GMAIL_SEND_EMAIL',
1048 + '--file',
1049 + '/tmp/example.txt',
1050 + ]).pipe(
1051 + Effect.flip,
1052 + Effect.map(error => (error instanceof Error ? error.message : String(error)))
1053 + );
1054 +
1055 + expect(failure).toContain('has no file_uploadable input');
1056 + })
1057 + );
1058 + });
1059 +
1060 + layer(
1061 + TestLive({
1062 + baseConfigProvider: testConfigProvider,
1063 + fixture: 'global-test-user-id',
1064 + stdin: { isTTY: true, data: '' },
1065 + toolkitsData: {
1066 + tools: [
1067 + {
1068 + name: 'Multi Upload',
1069 + slug: 'MULTI_UPLOAD_TOOL',
1070 + description: 'Tool with two uploadable fields',
1071 + tags: ['test'],
1072 + available_versions: ['20260316_00'],
1073 + input_parameters: {
1074 + type: 'object',
1075 + properties: {
1076 + avatar: {
1077 + type: 'object',
1078 + file_uploadable: true,
1079 + properties: {
1080 + name: { type: 'string' },
1081 + mimetype: { type: 'string' },
1082 + s3key: { type: 'string' },
1083 + },
1084 + },
1085 + resume: {
1086 + type: 'object',
1087 + file_uploadable: true,
1088 + properties: {
1089 + name: { type: 'string' },
1090 + mimetype: { type: 'string' },
1091 + s3key: { type: 'string' },
1092 + },
1093 + },
1094 + },
1095 + },
1096 + output_parameters: {
1097 + type: 'object',
1098 + properties: {},
1099 + },
1100 + },
1101 + ],
1102 + } satisfies TestLiveInput['toolkitsData'],
1103 + })
1104 + )(
1105 + '[Given] --file for a tool with multiple file_uploadable inputs [Then] execute asks for explicit JSON',
1106 + it => {
1107 + it.scoped('fails instead of guessing which file field to use', () =>
1108 + Effect.gen(function* () {
1109 + const failure = yield* cli([
1110 + 'execute',
1111 + 'MULTI_UPLOAD_TOOL',
1112 + '--file',
1113 + '/tmp/example.txt',
1114 + ]).pipe(
1115 + Effect.flip,
1116 + Effect.map(error => (error instanceof Error ? error.message : String(error)))
1117 + );
1118 +
1119 + expect(failure).toContain('has multiple file_uploadable inputs');
1120 + expect(failure).toContain('avatar');
1121 + expect(failure).toContain('resume');
1122 + })
1123 + );
1124 + }
1125 + );
1126 +
1127 layer(
1128 TestLive({
1129 baseConfigProvider: testConfigProvider,
@@ -887,7 +1425,7 @@ describe('CLI: composio execute', () => {
1425
1426 expect(output).toContain('USAGE');
1427 expect(output).toContain(
890 - 'composio execute <slug> [-d, --data text] [--dry-run] [--get-schema] [--parallel]'
1428 + 'composio execute <slug> [-d, --data text] [--file path] [--dry-run] [--get-schema] [--parallel]'
1429 );
1430 expect(output).toContain('composio execute GMAIL_SEND_EMAIL --get-schema');
1431 expect(output).toContain('--parallel');
ts/packages/cli/test/src/commands/tools/tools.info.cmd.test.ts
+68
@@ -5,6 +5,19 @@ import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
6 import type { Tools } from 'src/models/tools';
7
8 +const parseLastJson = (lines: ReadonlyArray<string>) => {
9 + for (let i = lines.length - 1; i >= 0; i -= 1) {
10 + const line = lines[i];
11 + if (!line) continue;
12 + try {
13 + return JSON.parse(line) as Record<string, unknown>;
14 + } catch {
15 + // continue
16 + }
17 + }
18 + throw new Error('Expected JSON output but none found');
19 +};
20 +
21 const testTools: Tools = [
22 {
23 name: 'Send Email',
@@ -39,6 +52,32 @@ const testTools: Tools = [
52 input_parameters: { type: 'object', properties: {} },
53 output_parameters: { type: 'object', properties: {} },
54 },
55 + {
56 + name: 'Slack Upload',
57 + slug: 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK',
58 + description: 'Uploads a file to Slack',
59 + tags: ['files', 'slack'],
60 + available_versions: ['20260101_00'],
61 + input_parameters: {
62 + type: 'object',
63 + properties: {
64 + channels: { type: 'string', description: 'Slack channel ID' },
65 + file: {
66 + type: 'object',
67 + file_uploadable: true,
68 + title: 'File',
69 + description: 'Local file accepted by CLI',
70 + properties: {
71 + name: { type: 'string' },
72 + mimetype: { type: 'string' },
73 + s3key: { type: 'string' },
74 + },
75 + required: ['name', 'mimetype', 's3key'],
76 + },
77 + },
78 + },
79 + output_parameters: { type: 'object', properties: {} },
80 + },
81 ];
82
83 const toolkitsData = {
@@ -73,6 +112,35 @@ describe('CLI: composio tools info', () => {
112 }
113 );
114
115 + layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
116 + '[Given] file_uploadable tool info [Then] it shows the CLI-facing file schema',
117 + it => {
118 + it.scoped('renders file inputs as path strings in JSON output', () =>
119 + Effect.gen(function* () {
120 + yield* cli(['tools', 'info', 'SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK']);
121 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
122 + const output = parseLastJson(lines) as {
123 + inputSchema: Record<string, unknown>;
124 + };
125 +
126 + expect(output.inputSchema).toEqual({
127 + type: 'object',
128 + properties: {
129 + channels: { type: 'string', description: 'Slack channel ID' },
130 + file: {
131 + title: 'File',
132 + description: 'Local file accepted by CLI',
133 + format: 'path',
134 + type: 'string',
135 + file_uploadable: true,
136 + },
137 + },
138 + });
139 + })
140 + );
141 + }
142 + );
143 +
144 layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
145 '[Given] no slug [Then] warns missing argument',
146 it => {