@devries-cameron20 / composio-1 / commits / 095c71585
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.

Add batched multi-query tool search (#3031)

## Summary - Added support for passing multiple semantic queries to `composio search` and `ToolRouterSession.search` in a single batched request. - Updated CLI output to render one result section per query, with per-query tool lists and plan guidance. - Adjusted search session typing, docs, and help text to reflect the new `string | string[]` query shape. - Expanded test coverage in both CLI and core to verify batched query handling and request payloads. ## Testing - `pnpm test ts/packages/core/test/models/toolRouter.test.ts` - `pnpm test ts/packages/cli/src/commands/tools/tools.search.cmd.test.ts` - Not run: full repository test suite

Rahul Tarak committed Mar 26, 2026 at 19:52 UTC 095c71585af947034328c559b3cabb752e4f433d
5 files changed +672 -210
ts/packages/cli/src/commands/root-help.ts
+29 -9
@@ -19,18 +19,23 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [
19 {
20 name: 'search',
21 description: 'Find tools by use case across all toolkits/apps.',
22 - usage: 'search <query> [--toolkits text] [--limit integer]',
22 + usage: 'search <query...> [--toolkits text] [--limit integer] [--human]',
23 options: [
24 - { name: '<query>', description: 'Semantic use-case query (e.g. "send emails")' },
24 + {
25 + name: '<query...>',
26 + description: 'One or more semantic use-case queries (e.g. "send emails" "github issues")',
27 + },
28 { name: '--toolkits', description: 'Filter by toolkit slugs, comma-separated' },
29 { name: '--limit', description: 'Maximum number of results (1-1000)' },
30 + { name: '--human', description: 'Show formatted output instead of default JSON' },
31 ],
32 },
33 {
34 name: 'execute',
35 description:
36 'Execute a tool. Validates inputs and connections automatically; use it aggressively.',
33 - usage: 'execute <slug> [-d, --data text] [--dry-run] [--get-schema]',
37 + usage:
38 + 'execute <slug> [-d, --data text] [--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 {
@@ -38,6 +43,10 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [
43 description:
44 'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',
45 },
46 + {
47 + name: '-p, --parallel',
48 + description: 'Execute repeated <slug> -d <text> pairs concurrently',
49 + },
50 { 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' },
52 ],
@@ -145,23 +154,28 @@ type SubcommandHelp = {
154
155 const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
156 search: {
148 - usage: 'composio search <query> [--toolkits text] [--limit integer]',
157 + usage: 'composio search <query...> [--toolkits text] [--limit integer] [--human]',
158 description:
150 - 'Find tools by use case. Returns matching tools with slugs you can pass directly to execute.',
159 + 'Find tools by use case. Defaults to JSON output; use --human for formatted output.',
160 args: [
161 {
153 - name: '<query>',
154 - description: 'Semantic use-case query (e.g. "send an email", "create github issue")',
162 + name: '<query...>',
163 + description:
164 + 'One or more semantic use-case queries (e.g. "send an email", "create github issue")',
165 },
166 ],
167 options: [
168 { name: '--toolkits <text>', description: 'Filter by toolkit slugs, comma-separated' },
169 { name: '--limit <integer>', description: 'Maximum number of results (1-1000)' },
170 + { name: '--human', description: 'Show formatted human-readable search output' },
171 ],
172 examples: [
173 '# Find tools for a use case',
174 'composio search "send an email"',
175 + 'composio search "send an email" "create github issue"',
176 + 'composio search "my emails" "my github issues" --toolkits gmail,github',
177 'composio search "create issue" --toolkits github',
178 + 'composio search "send an email" --human',
179 '',
180 '# Cross-app workflow discovery',
181 'composio search "post a message to a slack channel"',
@@ -180,7 +194,13 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
194 usage: 'composio execute <slug> [-d, --data text] [--dry-run] [--get-schema] [--parallel]',
195 description:
196 '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.',
183 - args: [{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' }],
197 + args: [
198 + {
199 + name: '<slug>',
200 + description:
201 + 'Tool slug for single execute, or repeated <slug> -d <text> pairs when using -p/--parallel',
202 + },
203 + ],
204 options: [
205 {
206 name: '-d, --data <text>',
@@ -225,7 +245,7 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
245 'composio execute GITHUB_CREATE_ISSUE -d @issue.json',
246 '',
247 '# Execute multiple tools concurrently',
228 - `composio execute --parallel GMAIL_SEND_EMAIL -d '{ recipient_email: "a@b.com" }' GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,
248 + `composio execute -p GMAIL_SEND_EMAIL -d '{ recipient_email: "a@b.com" }' GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,
249 ],
250 seeAlso: [
251 'composio search "<query>" Find tool slugs by use case',
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+385 -164
@@ -2,6 +2,7 @@ import { Args, Command, Options } from '@effect/cli';
2 import { Effect, Option } from 'effect';
3 import { TerminalUI } from 'src/services/terminal-ui';
4 import { requireAuth } from 'src/effects/require-auth';
5 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
6 import { clampLimit } from 'src/ui/clamp-limit';
7 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
8 import { buildMinimalPayloadFromSchema } from 'src/ui/build-minimal-payload';
@@ -14,12 +15,16 @@ import {
15 formatResolveCommandProjectError,
16 } from 'src/services/command-project';
17 import { commandHintExample, commandHintStep } from 'src/services/command-hints';
17 -import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
18 +import {
19 + primeConsumerConnectedToolkitsCacheInBackground,
20 + writeConsumerConnectedToolkitsCache,
21 +} from 'src/services/consumer-short-term-cache';
22 import { appendCliSessionHistory } from 'src/services/cli-session-artifacts';
23 +import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
24
20 -const query = Args.text({ name: 'query' }).pipe(
25 +const query = Args.repeated(Args.text({ name: 'query' })).pipe(
26 Args.withDescription(
22 - 'Semantic use-case query (e.g. "onboard a new GitHub repo and notify Slack").'
27 + 'One or more semantic use-case queries (e.g. "onboard a new GitHub repo", "notify Slack").'
28 )
29 );
30
@@ -43,12 +48,252 @@ const limit = Options.integer('limit').pipe(
48 Options.withDescription('Number of results per page (1-1000)')
49 );
50
51 +const json = Options.boolean('json').pipe(
52 + Options.withDefault(false),
53 + Options.withDescription('Print the full search response as JSON (default behavior)')
54 +);
55 +
56 +const human = Options.boolean('human').pipe(
57 + Options.withDefault(false),
58 + Options.withDescription('Show formatted human-readable search output')
59 +);
60 +
61 +type SearchToolSchema = {
62 + tool_slug: string;
63 + toolkit: string;
64 + description?: string;
65 + input_schema?: Record<string, unknown>;
66 + output_schema?: Record<string, unknown>;
67 +};
68 +
69 +type SearchResultRecord = {
70 + use_case: string;
71 + primary_tool_slugs: string[];
72 + related_tool_slugs: string[];
73 + recommended_plan_steps?: string[];
74 + reference_workbench_snippets?: unknown;
75 + plan_id?: string;
76 +};
77 +
78 +type ToolkitConnectionStatusRecord = {
79 + toolkit: string;
80 + has_active_connection: boolean;
81 +};
82 +
83 +type SearchResponseRecord = {
84 + results: SearchResultRecord[];
85 + toolkit_connection_statuses: ToolkitConnectionStatusRecord[];
86 + tool_schemas: Record<string, SearchToolSchema>;
87 + next_steps_guidance: string[];
88 + error: string | null;
89 +};
90 +
91 +const stripSearchResultMetadata = <
92 + T extends { reference_workbench_snippets?: unknown; plan_id?: unknown },
93 +>(
94 + result: T
95 +) => {
96 + const {
97 + reference_workbench_snippets: _referenceWorkbenchSnippets,
98 + plan_id: _planId,
99 + ...rest
100 + } = result;
101 + return rest;
102 +};
103 +
104 +const TOOL_SCHEMA_PATH_FORMAT = '~/.composio/tool_definitions/<TOOL_SLUG>.json';
105 +
106 +const toHomeRelativePath = (cacheDir: string, absolutePath: string) =>
107 + absolutePath.startsWith(cacheDir) ? absolutePath.replace(cacheDir, '~/.composio') : absolutePath;
108 +
109 +const collectToolsForResult = (params: {
110 + result: {
111 + primary_tool_slugs: string[];
112 + related_tool_slugs: string[];
113 + };
114 + toolSchemas: Record<string, SearchToolSchema>;
115 + toolkitSet?: Set<string>;
116 + limit: number;
117 +}): Tool[] => {
118 + const mergedSlugs: string[] = [];
119 + const seen = new Set<string>();
120 + for (const slug of [...params.result.primary_tool_slugs, ...params.result.related_tool_slugs]) {
121 + if (!seen.has(slug)) {
122 + seen.add(slug);
123 + mergedSlugs.push(slug);
124 + }
125 + }
126 +
127 + const toolsList: Tool[] = [];
128 + for (const slug of mergedSlugs) {
129 + const schema = params.toolSchemas[slug];
130 + if (!schema) continue;
131 + if (params.toolkitSet && !params.toolkitSet.has(schema.toolkit.toLowerCase())) continue;
132 +
133 + toolsList.push({
134 + slug: schema.tool_slug,
135 + name: schema.tool_slug,
136 + description: schema.description ?? '',
137 + tags: [],
138 + available_versions: [],
139 + input_parameters: (schema.input_schema ?? {}) as Record<string, unknown>,
140 + output_parameters: (schema.output_schema ?? {}) as Record<string, unknown>,
141 + } as Tool);
142 +
143 + if (toolsList.length >= params.limit) break;
144 + }
145 +
146 + return toolsList;
147 +};
148 +
149 +const buildSearchCta = (params: {
150 + firstSlug?: string;
151 + firstToolkit?: string;
152 + firstDataArg: string;
153 + rootOnly: boolean;
154 +}) => {
155 + const cta: Array<{ action: string; command: string }> = [];
156 + if (params.firstSlug) {
157 + cta.push({
158 + action: 'Execute a tool',
159 + command: params.rootOnly
160 + ? commandHintExample('root.execute', { slug: params.firstSlug, data: params.firstDataArg })
161 + : commandHintExample('dev.playgroundExecute', {
162 + slug: params.firstSlug,
163 + userId: '<user-id>',
164 + data: params.firstDataArg,
165 + }),
166 + });
167 + }
168 + if (params.firstToolkit) {
169 + cta.push({
170 + action: 'Connect a user account',
171 + command: params.rootOnly
172 + ? commandHintExample('root.link', { toolkit: String(params.firstToolkit).toLowerCase() })
173 + : commandHintExample('dev.connectedAccounts.link', {
174 + toolkit: String(params.firstToolkit).toLowerCase(),
175 + userId: '<user-id>',
176 + }),
177 + });
178 + }
179 + return cta;
180 +};
181 +
182 +const buildSearchJsonPayload = (params: {
183 + searchResponse: SearchResponseRecord;
184 + cacheScope: { orgId?: string; consumerUserId?: string };
185 + projectScope: { orgId: string; projectId: string };
186 + cta: Array<{ action: string; command: string }>;
187 +}) =>
188 + Effect.gen(function* () {
189 + const cacheDir = yield* setupCacheDir;
190 + const primaryToolSlugs = Array.from(
191 + new Set(params.searchResponse.results.flatMap(result => result.primary_tool_slugs))
192 + );
193 + const primaryToolSchemaPaths = Object.fromEntries(
194 + yield* Effect.forEach(primaryToolSlugs, slug =>
195 + Effect.gen(function* () {
196 + const definition = yield* getOrFetchToolInputDefinition(slug, params.projectScope);
197 + return [slug, toHomeRelativePath(cacheDir, definition.schemaPath)] as const;
198 + })
199 + )
200 + );
201 + const connectedToolkits = Array.from(
202 + new Set(
203 + params.searchResponse.toolkit_connection_statuses
204 + .filter(status => status.has_active_connection)
205 + .map(status => status.toolkit.toLowerCase())
206 + )
207 + );
208 +
209 + if (params.cacheScope.orgId && params.cacheScope.consumerUserId) {
210 + yield* writeConsumerConnectedToolkitsCache({
211 + orgId: params.cacheScope.orgId,
212 + consumerUserId: params.cacheScope.consumerUserId,
213 + toolkits: connectedToolkits,
214 + }).pipe(Effect.catchAll(() => Effect.void));
215 + }
216 +
217 + return {
218 + results: params.searchResponse.results.map(stripSearchResultMetadata),
219 + tool_schemas: {
220 + primary: primaryToolSchemaPaths,
221 + related_tools_path_format: TOOL_SCHEMA_PATH_FORMAT,
222 + },
223 + connected_toolkits: connectedToolkits,
224 + ...(params.searchResponse.error ? { error: params.searchResponse.error } : {}),
225 + CTA: params.cta,
226 + } as const;
227 + });
228 +
229 +const emitHumanSearchOutput = (params: {
230 + ui: TerminalUI;
231 + queries: ReadonlyArray<string>;
232 + resultsWithTools: Array<{ result: SearchResultRecord; tools: Tool[] }>;
233 + nextStepsGuidance: ReadonlyArray<string>;
234 + firstSlug?: string;
235 + firstDataArg: string;
236 + rootOnly: boolean;
237 + error: string | null;
238 +}) =>
239 + Effect.gen(function* () {
240 + for (const { result, tools } of params.resultsWithTools) {
241 + if (params.queries.length > 1) {
242 + yield* params.ui.log.info(`Results for "${result.use_case}"`);
243 + }
244 +
245 + if (tools.length === 0) {
246 + yield* params.ui.log.warn(`No tools found for "${result.use_case}".`);
247 + continue;
248 + }
249 +
250 + yield* params.ui.log.info(`Found ${tools.length} tools\n\n${formatToolsTable(tools)}`);
251 +
252 + const planSteps = Array.from(new Set(result.recommended_plan_steps ?? []));
253 + if (planSteps.length > 0) {
254 + yield* params.ui.log.info(
255 + `Plan:\n${planSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}`
256 + );
257 + } else if (params.queries.length === 1 && params.nextStepsGuidance.length > 0) {
258 + yield* params.ui.log.info(
259 + `Plan:\n${params.nextStepsGuidance.map((step, i) => `${i + 1}. ${step}`).join('\n')}`
260 + );
261 + }
262 + }
263 +
264 + if (params.firstSlug) {
265 + const executeHint = params.rootOnly
266 + ? commandHintStep('Execute a tool', 'root.execute', {
267 + slug: params.firstSlug,
268 + data: params.firstDataArg,
269 + })
270 + : commandHintStep('Test a tool against a playground user', 'dev.playgroundExecute', {
271 + slug: params.firstSlug,
272 + userId: '<user-id>',
273 + data: params.firstDataArg,
274 + });
275 + const linkHint = params.rootOnly
276 + ? commandHintStep('Link an account', 'root.link', { toolkit: '<toolkit>' })
277 + : commandHintStep('Link an account', 'dev.connectedAccounts.link', {
278 + toolkit: '<toolkit>',
279 + userId: '<user-id>',
280 + });
281 + yield* params.ui.log.step([executeHint, linkHint].join('\n'));
282 + }
283 +
284 + if (params.error) {
285 + yield* params.ui.log.warn(params.error);
286 + }
287 + });
288 +
289 const runToolsSearch = (params: {
47 - query: string;
290 + query: ReadonlyArray<string>;
291 toolkits: Option.Option<string>;
292 userId: Option.Option<string>;
293 projectName: Option.Option<string>;
294 limit: number;
295 + json: boolean;
296 + human: boolean;
297 rootOnly: boolean;
298 }) =>
299 Effect.gen(function* () {
@@ -58,6 +303,12 @@ const runToolsSearch = (params: {
303 const userContext = yield* ComposioUserContext;
304
305 const clampedLimit = clampLimit(params.limit);
306 + const emitHuman = params.human;
307 + const emitJson = params.json || !emitHuman;
308 + const queries = params.query.map(q => q.trim()).filter(Boolean);
309 + if (queries.length === 0) {
310 + return yield* Effect.fail(new Error('At least one query is required.'));
311 + }
312 const toolkitFilter = Option.getOrUndefined(params.toolkits);
313 const toolkitList =
314 toolkitFilter && toolkitFilter.trim().length > 0
@@ -67,115 +318,98 @@ const runToolsSearch = (params: {
318 .filter(Boolean)
319 : undefined;
320
70 - const searchResult = yield* ui.withSpinner(
71 - `Searching tools for "${params.query}"...`,
72 - Effect.gen(function* () {
73 - const resolvedProject = yield* resolveCommandProject({
74 - mode: 'consumer',
75 - projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
76 - }).pipe(Effect.mapError(formatResolveCommandProjectError));
77 - const resolvedUserId =
78 - resolvedProject.projectType === 'CONSUMER'
79 - ? Option.fromNullable(resolvedProject.consumerUserId)
80 - : Option.match(params.userId, {
81 - onSome: value => Option.some(value),
82 - onNone: () => userContext.data.testUserId,
83 - });
84 - if (Option.isNone(resolvedUserId)) {
85 - return yield* Effect.fail(
86 - new Error(
87 - 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
88 - )
89 - );
90 - }
91 - const clientSingleton = yield* ComposioClientSingleton;
92 - const client = yield* clientSingleton.getFor({
321 + const runSearchRequest = Effect.gen(function* () {
322 + const resolvedProject = yield* resolveCommandProject({
323 + mode: 'consumer',
324 + projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
325 + }).pipe(Effect.mapError(formatResolveCommandProjectError));
326 + const resolvedUserId =
327 + resolvedProject.projectType === 'CONSUMER'
328 + ? Option.fromNullable(resolvedProject.consumerUserId)
329 + : Option.match(params.userId, {
330 + onSome: value => Option.some(value),
331 + onNone: () => userContext.data.testUserId,
332 + });
333 + if (Option.isNone(resolvedUserId)) {
334 + return yield* Effect.fail(
335 + new Error(
336 + 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
337 + )
338 + );
339 + }
340 + const clientSingleton = yield* ComposioClientSingleton;
341 + const client = yield* clientSingleton.getFor({
342 + orgId: resolvedProject.orgId,
343 + projectId: resolvedProject.projectId,
344 + });
345 + if (resolvedProject.projectType === 'CONSUMER') {
346 + yield* primeConsumerConnectedToolkitsCacheInBackground({
347 orgId: resolvedProject.orgId,
94 - projectId: resolvedProject.projectId,
348 + consumerUserId: resolvedUserId.value,
349 });
96 - if (resolvedProject.projectType === 'CONSUMER') {
97 - yield* primeConsumerConnectedToolkitsCacheInBackground({
98 - orgId: resolvedProject.orgId,
99 - consumerUserId: resolvedUserId.value,
100 - });
101 - }
102 - const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
103 - toolkits: toolkitList,
104 - });
105 - const searchResponse = yield* Effect.tryPromise(() =>
106 - client.toolRouter.session.search(sessionId, {
107 - queries: [{ use_case: params.query }],
108 - })
109 - );
110 - return {
111 - searchResponse,
112 - historyScope:
113 - resolvedProject.projectType === 'CONSUMER'
114 - ? {
115 - orgId: resolvedProject.orgId,
116 - consumerUserId: resolvedUserId.value,
117 - toolRouterSessionId: sessionId,
118 - }
119 - : undefined,
120 - };
121 - })
122 - );
350 + }
351 + const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
352 + toolkits: toolkitList,
353 + });
354 + const searchResponse = yield* Effect.tryPromise(() =>
355 + client.toolRouter.session.search(sessionId, {
356 + queries: queries.map(query => ({ use_case: query })),
357 + })
358 + );
359 + return {
360 + searchResponse,
361 + projectScope: {
362 + orgId: resolvedProject.orgId,
363 + projectId: resolvedProject.projectId,
364 + },
365 + historyScope:
366 + resolvedProject.projectType === 'CONSUMER'
367 + ? {
368 + orgId: resolvedProject.orgId,
369 + consumerUserId: resolvedUserId.value,
370 + toolRouterSessionId: sessionId,
371 + }
372 + : undefined,
373 + };
374 + });
375 +
376 + const searchResult = emitHuman
377 + ? yield* ui.withSpinner(
378 + queries.length === 1
379 + ? `Searching tools for "${queries[0]}"...`
380 + : `Searching tools for ${queries.length} queries...`,
381 + runSearchRequest
382 + )
383 + : yield* runSearchRequest;
384 const searchResponse = searchResult.searchResponse;
385
386 const toolkitSet = toolkitList && toolkitList.length > 0 ? new Set(toolkitList) : undefined;
387
127 - const mergedSlugs: string[] = [];
128 - const seen = new Set<string>();
129 - for (const item of searchResponse.results) {
130 - for (const slug of [...item.primary_tool_slugs, ...item.related_tool_slugs]) {
131 - if (!seen.has(slug)) {
132 - seen.add(slug);
133 - mergedSlugs.push(slug);
134 - }
135 - }
136 - }
137 -
138 - const toolsList: Tool[] = [];
139 - for (const slug of mergedSlugs) {
140 - const schema = searchResponse.tool_schemas[slug];
141 - if (!schema) continue;
142 - if (toolkitSet && !toolkitSet.has(schema.toolkit.toLowerCase())) continue;
143 -
144 - toolsList.push({
145 - slug: schema.tool_slug,
146 - name: schema.tool_slug,
147 - description: schema.description ?? '',
148 - tags: [],
149 - available_versions: [],
150 - input_parameters: (schema.input_schema ?? {}) as Record<string, unknown>,
151 - output_parameters: (schema.output_schema ?? {}) as Record<string, unknown>,
152 - } as Tool);
153 -
154 - if (toolsList.length >= clampedLimit) break;
155 - }
388 + const resultsWithTools = searchResponse.results.map(result => ({
389 + result,
390 + tools: collectToolsForResult({
391 + result,
392 + toolSchemas: searchResponse.tool_schemas,
393 + toolkitSet,
394 + limit: clampedLimit,
395 + }),
396 + }));
397
157 - if (toolsList.length === 0) {
158 - yield* ui.log.warn(`No tools found matching "${params.query}". Try broadening your search.`);
398 + const totalToolCount = resultsWithTools.reduce((sum, item) => sum + item.tools.length, 0);
399 + if (totalToolCount === 0) {
400 + const description =
401 + queries.length === 1 ? `"${queries[0]}"` : `the provided ${queries.length} queries`;
402 + if (emitHuman) {
403 + yield* ui.log.warn(`No tools found matching ${description}. Try broadening your search.`);
404 + } else if (emitJson) {
405 + yield* ui.log.message('[]');
406 + yield* ui.output('[]');
407 + }
408 return;
409 }
410
162 - const showing = toolsList.length;
163 - yield* ui.log.info(`Found ${showing} tools\n\n${formatToolsTable(toolsList)}`);
164 -
165 - const planSteps = Array.from(
166 - new Set(searchResponse.results.flatMap(result => result.recommended_plan_steps ?? []))
167 - );
168 - if (planSteps.length > 0) {
169 - yield* ui.log.info(`Plan:\n${planSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}`);
170 - } else if (searchResponse.next_steps_guidance.length > 0) {
171 - yield* ui.log.info(
172 - `Plan:\n${searchResponse.next_steps_guidance
173 - .map((step, i) => `${i + 1}. ${step}`)
174 - .join('\n')}`
175 - );
176 - }
177 -
178 - const firstSlug = toolsList[0]?.slug;
411 + const firstToolsList = resultsWithTools.find(item => item.tools.length > 0)?.tools ?? [];
412 + const firstSlug = firstToolsList[0]?.slug;
413 const firstSchema =
414 firstSlug && searchResponse.tool_schemas[firstSlug]
415 ? searchResponse.tool_schemas[firstSlug]
@@ -188,88 +422,71 @@ const runToolsSearch = (params: {
422 const firstDataArg =
423 Object.keys(firstPayload).length === 0 ? '-d "{}"' : `-d '${firstPayloadJson}'`;
424
191 - if (firstSlug) {
192 - const executeHint = params.rootOnly
193 - ? commandHintStep('Execute a tool', 'root.execute', {
194 - slug: firstSlug,
195 - data: firstDataArg,
196 - })
197 - : commandHintStep('Test a tool against a playground user', 'dev.playgroundExecute', {
198 - slug: firstSlug,
199 - userId: '<user-id>',
200 - data: firstDataArg,
201 - });
202 - const linkHint = params.rootOnly
203 - ? commandHintStep('Link an account', 'root.link', { toolkit: '<toolkit>' })
204 - : commandHintStep('Link an account', 'dev.connectedAccounts.link', {
205 - toolkit: '<toolkit>',
206 - userId: '<user-id>',
207 - });
208 - yield* ui.log.step([executeHint, linkHint].join('\n'));
209 - }
425 + const cta = buildSearchCta({
426 + firstSlug,
427 + firstToolkit,
428 + firstDataArg,
429 + rootOnly: params.rootOnly,
430 + });
431
211 - if (searchResponse.error) {
212 - yield* ui.log.warn(searchResponse.error);
213 - }
214 -
215 - const cta: Array<{ action: string; command: string }> = [];
216 - if (firstSlug) {
217 - cta.push({
218 - action: 'Execute a tool',
219 - command: params.rootOnly
220 - ? commandHintExample('root.execute', { slug: firstSlug, data: firstDataArg })
221 - : commandHintExample('dev.playgroundExecute', {
222 - slug: firstSlug,
223 - userId: '<user-id>',
224 - data: firstDataArg,
225 - }),
226 - });
227 - }
228 - if (firstToolkit) {
229 - cta.push({
230 - action: 'Connect a user account',
231 - command: params.rootOnly
232 - ? commandHintExample('root.link', { toolkit: String(firstToolkit).toLowerCase() })
233 - : commandHintExample('dev.connectedAccounts.link', {
234 - toolkit: String(firstToolkit).toLowerCase(),
235 - userId: '<user-id>',
236 - }),
237 - });
238 - }
432 + const outputForJq = yield* buildSearchJsonPayload({
433 + searchResponse,
434 + cacheScope: {
435 + orgId: searchResult.historyScope?.orgId,
436 + consumerUserId: searchResult.historyScope?.consumerUserId,
437 + },
438 + projectScope: searchResult.projectScope,
439 + cta,
440 + });
441
240 - const outputForJq = {
241 - ...searchResponse,
242 - CTA: cta,
243 - };
442 yield* appendCliSessionHistory({
443 orgId: searchResult.historyScope?.orgId,
444 consumerUserId: searchResult.historyScope?.consumerUserId,
445 entry: {
446 command: 'search',
249 - query: params.query,
447 + query: queries.join(' | '),
448 + queries,
449 toolkitFilter: toolkitList ?? [],
450 limit: clampedLimit,
252 - resultCount: toolsList.length,
451 + resultCount: totalToolCount,
452 toolRouterSessionId: searchResult.historyScope?.toolRouterSessionId,
453 nextSteps: searchResponse.next_steps_guidance,
454 },
455 }).pipe(Effect.catchAll(() => Effect.void));
257 - yield* ui.output(JSON.stringify(outputForJq, null, 2));
456 +
457 + if (emitHuman) {
458 + yield* emitHumanSearchOutput({
459 + ui,
460 + queries,
461 + resultsWithTools,
462 + nextStepsGuidance: searchResponse.next_steps_guidance,
463 + firstSlug,
464 + firstDataArg,
465 + rootOnly: params.rootOnly,
466 + error: searchResponse.error,
467 + });
468 + } else if (emitJson) {
469 + const outputJson = JSON.stringify(outputForJq, null, 2);
470 + yield* ui.log.message(outputJson);
471 + yield* ui.output(outputJson);
472 + }
473 });
474
475 export const toolsCmd$Search = Command.make(
476 'search',
262 - { query, toolkits, userId, projectName, limit },
263 - ({ query, toolkits, userId, projectName, limit }) =>
264 - runToolsSearch({ query, toolkits, userId, projectName, limit, rootOnly: false })
477 + { query, toolkits, userId, projectName, limit, json, human },
478 + ({ query, toolkits, userId, projectName, limit, json, human }) =>
479 + runToolsSearch({ query, toolkits, userId, projectName, limit, json, human, rootOnly: false })
480 ).pipe(
481 Command.withDescription(
482 [
268 - 'Find tools by use case. Returns matching tools with slugs you can pass directly to `execute`.',
483 + 'Find tools by use case. Defaults to full JSON output; use `--human` for formatted output.',
484 '',
485 'Examples:',
486 ' composio search "send an email"',
487 + ' composio search "send an email" "create a github issue"',
488 ' composio search "create issue" --toolkits github',
489 + ' composio search "send an email" --human',
490 ' composio search "list calendar events" --limit 5',
491 '',
492 'Next steps:',
@@ -282,24 +499,28 @@ export const toolsCmd$Search = Command.make(
499
500 export const rootToolsCmd$Search = Command.make(
501 'search',
285 - { query, toolkits, limit },
286 - ({ query, toolkits, limit }) =>
502 + { query, toolkits, limit, json, human },
503 + ({ query, toolkits, limit, json, human }) =>
504 runToolsSearch({
505 query,
506 toolkits,
507 userId: Option.none(),
508 projectName: Option.none(),
509 limit,
510 + json,
511 + human,
512 rootOnly: true,
513 })
514 ).pipe(
515 Command.withDescription(
516 [
298 - 'Find tools by use case. Returns matching tools with slugs you can pass directly to `execute`.',
517 + 'Find tools by use case. Defaults to full JSON output; use `--human` for formatted output.',
518 '',
519 'Examples:',
520 ' composio search "send an email"',
521 + ' composio search "send an email" "create a github issue"',
522 ' composio search "create issue" --toolkits github',
523 + ' composio search "send an email" --human',
524 ' composio search "list calendar events" --limit 5',
525 '',
526 'Next steps:',
ts/packages/cli/src/services/consumer-short-term-cache.ts
+25
@@ -211,6 +211,31 @@ export const refreshConsumerConnectedToolkitsCache = (params?: {
211 });
212 });
213
214 +export const writeConsumerConnectedToolkitsCache = (params: {
215 + readonly orgId: string;
216 + readonly consumerUserId: string;
217 + readonly toolkits: ReadonlyArray<string>;
218 +}) =>
219 + Effect.gen(function* () {
220 + const state = yield* readCache();
221 + const key = cacheKey(params.orgId, params.consumerUserId);
222 + const currentEntry = state[key];
223 + const proc = yield* NodeProcess;
224 + const searchSessionFields = resolveSearchSessionMetadata({
225 + currentEntry,
226 + cwd: proc.cwd,
227 + });
228 +
229 + yield* writeCache({
230 + ...state,
231 + [key]: {
232 + toolkits: [...new Set(params.toolkits.map(toolkit => toolkit.toLowerCase()))],
233 + expiresAt: new Date(Date.now() + CACHE_TTL_MS).toISOString(),
234 + ...searchSessionFields,
235 + },
236 + });
237 + });
238 +
239 export const primeConsumerConnectedToolkitsCacheInBackground = (params?: {
240 readonly orgId?: string;
241 readonly consumerUserId?: string;
ts/packages/cli/test/__utils__/services/test-layer.ts
+25 -20
@@ -857,18 +857,31 @@ export const TestLayer = (input?: TestLiveInput) =>
857 _sessionId: string,
858 params: SessionSearchParams
859 ): Promise<SessionSearchResponse> => {
860 - const queryUseCase = params.queries[0]?.use_case ?? '';
861 - const normalizedQuery = queryUseCase.toLowerCase();
862 - const matchedTools = toolkitsData.tools.filter(
863 - tool =>
864 - tool.name.toLowerCase().includes(normalizedQuery) ||
865 - tool.slug.toLowerCase().includes(normalizedQuery) ||
866 - tool.description.toLowerCase().includes(normalizedQuery)
867 - );
860 + const results = params.queries.map((query, index) => {
861 + const queryUseCase = query.use_case ?? '';
862 + const normalizedQuery = queryUseCase.toLowerCase();
863 + const matchedTools = toolkitsData.tools.filter(
864 + tool =>
865 + tool.name.toLowerCase().includes(normalizedQuery) ||
866 + tool.slug.toLowerCase().includes(normalizedQuery) ||
867 + tool.description.toLowerCase().includes(normalizedQuery)
868 + );
869 +
870 + return {
871 + index: index + 1,
872 + use_case: queryUseCase,
873 + primary_tool_slugs: matchedTools.map(tool => tool.slug),
874 + related_tool_slugs: [],
875 + toolkits: Array.from(
876 + new Set(matchedTools.map(tool => tool.slug.split('_')[0]?.toLowerCase() ?? '').filter(Boolean))
877 + ),
878 + matchedTools,
879 + };
880 + });
881
869 - const primaryToolSlugs = matchedTools.map(tool => tool.slug);
882 + const allMatchedTools = results.flatMap(result => result.matchedTools);
883 const toolSchemas = Object.fromEntries(
871 - matchedTools.map(tool => [
884 + allMatchedTools.map(tool => [
885 tool.slug,
886 {
887 tool_slug: tool.slug,
@@ -882,7 +895,7 @@ export const TestLayer = (input?: TestLiveInput) =>
895 );
896 const toolkitConnectionStatuses = Array.from(
897 new Set(
885 - matchedTools.map(tool => tool.slug.split('_')[0]?.toLowerCase() ?? '').filter(Boolean)
898 + allMatchedTools.map(tool => tool.slug.split('_')[0]?.toLowerCase() ?? '').filter(Boolean)
899 )
900 ).map(toolkitSlug => ({
901 toolkit: toolkitSlug,
@@ -894,15 +907,7 @@ export const TestLayer = (input?: TestLiveInput) =>
907 return {
908 success: true,
909 error: null,
897 - results: [
898 - {
899 - index: 1,
900 - use_case: queryUseCase,
901 - primary_tool_slugs: primaryToolSlugs,
902 - related_tool_slugs: [],
903 - toolkits: toolkitConnectionStatuses.map(t => t.toolkit),
904 - },
905 - ],
910 + results: results.map(({ matchedTools: _matchedTools, ...result }) => result),
911 tool_schemas: toolSchemas,
912 toolkit_connection_statuses: toolkitConnectionStatuses,
913 next_steps_guidance: [],
ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+208 -17
@@ -54,42 +54,71 @@ const testLiveOptions = {
54 };
55
56 describe('CLI: composio search', () => {
57 - layer(TestLive(testLiveOptions))('[Given] query "send" [Then] returns matching tools', it => {
58 - it.scoped('returns matching tools', () =>
57 + layer(TestLive(testLiveOptions))('[Given] query "send" [Then] returns JSON by default', it => {
58 + it.scoped('returns JSON payload by default', () =>
59 Effect.gen(function* () {
60 yield* cli(['search', 'send']);
61 const lines = yield* MockConsole.getLines({ stripAnsi: true });
62 const output = lines.join('\n');
63
64 + expect(output).toContain('"results"');
65 + expect(output).toContain('"tool_schemas"');
66 + expect(output).toContain('"primary"');
67 + expect(output).toContain('"related_tools_path_format"');
68 + expect(output).toContain('"connected_toolkits"');
69 + expect(output).toContain('"CTA"');
70 + expect(output).not.toContain('"session"');
71 + expect(output).not.toContain('"time_info"');
72 + expect(output).not.toContain('"next_steps_guidance"');
73 + expect(output).not.toContain('"success"');
74 + expect(output).not.toContain('"error"');
75 expect(output).toContain('GMAIL_SEND_EMAIL');
76 expect(output).toContain('SLACK_SEND_MESSAGE');
66 - expect(output).not.toContain('GITHUB_CREATE_ISSUE');
67 - expect(output).toContain('Found 2 tools');
77 + expect(output).toContain('~/.composio/tool_definitions/GMAIL_SEND_EMAIL.json');
78 })
79 );
80 });
81
82 + layer(TestLive(testLiveOptions))(
83 + '[Given] multiple queries [Then] the CLI returns a batched JSON response',
84 + it => {
85 + it.scoped('returns batched results in JSON', () =>
86 + Effect.gen(function* () {
87 + yield* cli(['search', 'send', 'create issue']);
88 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
89 + const output = lines.join('\n');
90 +
91 + expect(output).toContain('"use_case": "send"');
92 + expect(output).toContain('"use_case": "create issue"');
93 + expect(output).toContain('GMAIL_SEND_EMAIL');
94 + expect(output).toContain('SLACK_SEND_MESSAGE');
95 + expect(output).toContain('GITHUB_CREATE_ISSUE');
96 + })
97 + );
98 + }
99 + );
100 +
101 layer(TestLive(testLiveOptions))(
102 '[Given] query with no results [Then] shows not found message',
103 it => {
75 - it.scoped('shows not found message', () =>
104 + it.scoped('shows empty json output', () =>
105 Effect.gen(function* () {
106 yield* cli(['search', 'nonexistent_query']);
107 const lines = yield* MockConsole.getLines({ stripAnsi: true });
108 const output = lines.join('\n');
109
81 - expect(output).toContain('No tools found');
110 + expect(output).toContain('[]');
111 })
112 );
113 }
114 );
115
116 layer(TestLive(testLiveOptions))(
88 - '[Given] query "send" --toolkits "gmail" [Then] scopes to toolkit',
117 + '[Given] query "send" --toolkits "gmail" --human [Then] scopes to toolkit',
118 it => {
119 it.scoped('scopes search to toolkit', () =>
120 Effect.gen(function* () {
92 - yield* cli(['search', 'send', '--toolkits', 'gmail']);
121 + yield* cli(['search', 'send', '--toolkits', 'gmail', '--human']);
122 const lines = yield* MockConsole.getLines({ stripAnsi: true });
123 const output = lines.join('\n');
124 const humanOutput = output.split('\n{')[0] ?? output;
@@ -103,20 +132,42 @@ describe('CLI: composio search', () => {
132 );
133
134 layer(TestLive(testLiveOptions))(
106 - '[Given] tools search [Then] JSON output includes full tool-router payload and CTA',
135 + '[Given] search --human [Then] it stays human-readable and omits raw JSON',
136 + it => {
137 + it.scoped('does not print raw JSON in human mode', () =>
138 + Effect.gen(function* () {
139 + yield* cli(['search', 'send', '--human']);
140 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
141 + const output = lines.join('\n');
142 +
143 + expect(output).not.toContain('"results"');
144 + expect(output).not.toContain('"tool_schemas"');
145 + expect(output).toContain('Found 2 tools');
146 + expect(output).toContain('composio execute');
147 + expect(output).toContain('composio link <toolkit>');
148 + })
149 + );
150 + }
151 + );
152 +
153 + layer(TestLive(testLiveOptions))(
154 + '[Given] search --json [Then] JSON output includes full tool-router payload and CTA',
155 it => {
156 it.scoped('prints full search response with CTA for jq', () =>
157 Effect.gen(function* () {
110 - yield* cli(['search', 'send']);
158 + yield* cli(['search', 'send', '--json']);
159 const lines = yield* MockConsole.getLines({ stripAnsi: true });
160 const output = lines.join('\n');
161
162 expect(output).toContain('"results"');
163 expect(output).toContain('"tool_schemas"');
116 - expect(output).toContain('"toolkit_connection_statuses"');
117 - expect(output).toContain('"session"');
118 - expect(output).toContain('"time_info"');
164 + expect(output).toContain('"connected_toolkits"');
165 expect(output).toContain('"CTA"');
166 + expect(output).not.toContain('"session"');
167 + expect(output).not.toContain('"time_info"');
168 + expect(output).not.toContain('"next_steps_guidance"');
169 + expect(output).not.toContain('"success"');
170 + expect(output).not.toContain('"error"');
171 expect(output).toContain('"Execute a tool"');
172 expect(output).toContain('"Connect a user account"');
173 expect(output).toContain('composio execute');
@@ -126,6 +177,72 @@ describe('CLI: composio search', () => {
177 }
178 );
179
180 + layer(TestLive(testLiveOptions))(
181 + '[Given] search results with workbench snippets [Then] snippets are removed from JSON output',
182 + it => {
183 + it.scoped('omits workbench snippets and emits schema/cache references', () =>
184 + Effect.gen(function* () {
185 + const live = TestLive({
186 + ...testLiveOptions,
187 + toolRouter: {
188 + search: async (_sessionId, params) => ({
189 + success: true,
190 + error: null,
191 + results: [
192 + {
193 + index: 1,
194 + use_case: params.queries[0]?.use_case ?? '',
195 + primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
196 + related_tool_slugs: [],
197 + toolkits: ['gmail'],
198 + reference_workbench_snippets: [{ description: 'snippet', code: 'print("hi")' }],
199 + },
200 + ],
201 + tool_schemas: {
202 + GMAIL_SEND_EMAIL: {
203 + tool_slug: 'GMAIL_SEND_EMAIL',
204 + toolkit: 'gmail',
205 + description: 'Sends an email',
206 + hasFullSchema: true,
207 + input_schema: { type: 'object', properties: {} },
208 + output_schema: { type: 'object', properties: {} },
209 + },
210 + },
211 + toolkit_connection_statuses: [
212 + {
213 + toolkit: 'gmail',
214 + description: 'gmail toolkit',
215 + has_active_connection: false,
216 + status_message: 'No active connection',
217 + },
218 + ],
219 + next_steps_guidance: [],
220 + session: {
221 + id: 'trs_test_session',
222 + generate_id: false,
223 + instructions: 'Reuse this session id for follow-up calls.',
224 + },
225 + time_info: {
226 + current_time_utc: '2026-01-01T00:00:00.000Z',
227 + current_time_utc_epoch_seconds: 1767225600,
228 + message: 'UTC time',
229 + },
230 + }),
231 + },
232 + });
233 +
234 + yield* cli(['search', 'send']).pipe(Effect.provide(live));
235 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
236 + const output = lines.join('\n');
237 +
238 + expect(output).not.toContain('reference_workbench_snippets');
239 + expect(output).toContain('~/.composio/tool_definitions/GMAIL_SEND_EMAIL.json');
240 + expect(output).toContain('"related_tools_path_format"');
241 + })
242 + );
243 + }
244 + );
245 +
246 layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
247 '[Given] search with schema properties [Then] CTA has valid payload and lowercase link',
248 it => {
@@ -280,6 +397,79 @@ describe('CLI: composio search', () => {
397 }
398 );
399
400 + layer(TestLive(testLiveOptions))(
401 + '[Given] multiple queries [Then] search passes all queries to the tool-router session',
402 + it => {
403 + it.scoped('passes batched queries without a parallel flag', () =>
404 + Effect.gen(function* () {
405 + let searchParams: SessionSearchParams | undefined;
406 +
407 + const live = TestLive({
408 + baseConfigProvider: testConfigProvider,
409 + toolkitsData,
410 + fixture: 'global-test-user-id',
411 + toolRouter: {
412 + search: async (_sessionId, params) => {
413 + searchParams = params;
414 + return {
415 + success: true,
416 + error: null,
417 + results: params.queries.map((query, index) => ({
418 + index: index + 1,
419 + use_case: query.use_case ?? '',
420 + primary_tool_slugs:
421 + query.use_case === 'create issue'
422 + ? ['GITHUB_CREATE_ISSUE']
423 + : ['GMAIL_SEND_EMAIL'],
424 + related_tool_slugs: [],
425 + toolkits: query.use_case === 'create issue' ? ['github'] : ['gmail'],
426 + })),
427 + tool_schemas: {
428 + GMAIL_SEND_EMAIL: {
429 + tool_slug: 'GMAIL_SEND_EMAIL',
430 + toolkit: 'gmail',
431 + description: 'Sends an email',
432 + hasFullSchema: true,
433 + input_schema: { type: 'object', properties: {} },
434 + output_schema: { type: 'object', properties: {} },
435 + },
436 + GITHUB_CREATE_ISSUE: {
437 + tool_slug: 'GITHUB_CREATE_ISSUE',
438 + toolkit: 'github',
439 + description: 'Creates a GitHub issue',
440 + hasFullSchema: true,
441 + input_schema: { type: 'object', properties: {} },
442 + output_schema: { type: 'object', properties: {} },
443 + },
444 + },
445 + toolkit_connection_statuses: [],
446 + next_steps_guidance: [],
447 + session: {
448 + id: 'trs_test_session',
449 + generate_id: false,
450 + instructions: 'Reuse this session id for follow-up calls.',
451 + },
452 + time_info: {
453 + current_time_utc: '2026-01-01T00:00:00.000Z',
454 + current_time_utc_epoch_seconds: 1767225600,
455 + message: 'UTC time',
456 + },
457 + };
458 + },
459 + },
460 + });
461 +
462 + yield* cli(['search', 'send', 'create issue']).pipe(Effect.provide(live));
463 +
464 + expect(searchParams?.queries.map(query => query.use_case)).toEqual([
465 + 'send',
466 + 'create issue',
467 + ]);
468 + })
469 + );
470 + }
471 + );
472 +
473 layer(TestLive(testLiveOptions))(
474 '[Given] search response with recommended plan [Then] it prints plan and execute hint',
475 it => {
@@ -336,7 +526,7 @@ describe('CLI: composio search', () => {
526 },
527 });
528
339 - yield* cli(['search', 'send email']).pipe(Effect.provide(live));
529 + yield* cli(['search', 'send email', '--human']).pipe(Effect.provide(live));
530 const lines = yield* MockConsole.getLines({ stripAnsi: true });
531 const output = lines.join('\n');
532
@@ -353,7 +543,7 @@ describe('CLI: composio search', () => {
543 layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
544 it.scoped('warns user to login', () =>
545 Effect.gen(function* () {
356 - yield* cli(['search', 'send']);
546 + yield* cli(['search', 'send', '--human']);
547 const lines = yield* MockConsole.getLines({ stripAnsi: true });
548 const output = lines.join('\n');
549
@@ -404,7 +594,8 @@ describe('CLI: composio search', () => {
594 const lines = yield* MockConsole.getLines({ stripAnsi: true });
595 const output = lines.join('\n');
596
407 - expect(output).toContain('Found 2 tools');
597 + expect(output).toContain('"results"');
598 + expect(output).toContain('GMAIL_SEND_EMAIL');
599 expect(output).not.toContain('Using global test user id');
600 })
601 );
@@ -415,7 +606,7 @@ describe('CLI: composio search', () => {
606 it => {
607 it.scoped('search returns matching tools', () =>
608 Effect.gen(function* () {
418 - yield* cli(['search', 'send']);
609 + yield* cli(['search', 'send', '--human']);
610 const lines = yield* MockConsole.getLines({ stripAnsi: true });
611 const output = lines.join('\n');
612