Skip to content

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

Add batched multi-query tool search (#3031)

Rahul Tarak095c71585af9
diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.ts
index 8a703cca7..4fe68f703 100644
--- a/ts/packages/cli/src/commands/root-help.ts
+++ b/ts/packages/cli/src/commands/root-help.ts
@@ -19,18 +19,23 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [
{
name: 'search',
description: 'Find tools by use case across all toolkits/apps.',
- usage: 'search <query> [--toolkits text] [--limit integer]',
+ usage: 'search <query...> [--toolkits text] [--limit integer] [--human]',
options: [
- { name: '<query>', description: 'Semantic use-case query (e.g. "send emails")' },
+ {
+ name: '<query...>',
+ description: 'One or more semantic use-case queries (e.g. "send emails" "github issues")',
+ },
{ name: '--toolkits', description: 'Filter by toolkit slugs, comma-separated' },
{ name: '--limit', description: 'Maximum number of results (1-1000)' },
+ { name: '--human', description: 'Show formatted output instead of default JSON' },
],
},
{
name: 'execute',
description:
'Execute a tool. Validates inputs and connections automatically; use it aggressively.',
- usage: 'execute <slug> [-d, --data text] [--dry-run] [--get-schema]',
+ usage:
+ 'execute <slug> [-d, --data text] [--dry-run] [--get-schema] | execute -p <slug> -d <text> <slug> -d <text> ...',
options: [
{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' },
{
@@ -38,6 +43,10 @@ const CORE_COMMANDS: ReadonlyArray<DetailedCommand> = [
description:
'JSON or JS-style object arguments, e.g. -d \'{ repo: "foo" }\', @file, or - for stdin',
},
+ {
+ name: '-p, --parallel',
+ description: 'Execute repeated <slug> -d <text> pairs concurrently',
+ },
{ name: '--dry-run', description: 'Validate and preview the tool call without executing it' },
{ name: '--get-schema', description: 'Fetch and print the raw tool schema' },
],
@@ -145,23 +154,28 @@ type SubcommandHelp = {
const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
search: {
- usage: 'composio search <query> [--toolkits text] [--limit integer]',
+ usage: 'composio search <query...> [--toolkits text] [--limit integer] [--human]',
description:
- 'Find tools by use case. Returns matching tools with slugs you can pass directly to execute.',
+ 'Find tools by use case. Defaults to JSON output; use --human for formatted output.',
args: [
{
- name: '<query>',
- description: 'Semantic use-case query (e.g. "send an email", "create github issue")',
+ name: '<query...>',
+ description:
+ 'One or more semantic use-case queries (e.g. "send an email", "create github issue")',
},
],
options: [
{ name: '--toolkits <text>', description: 'Filter by toolkit slugs, comma-separated' },
{ name: '--limit <integer>', description: 'Maximum number of results (1-1000)' },
+ { name: '--human', description: 'Show formatted human-readable search output' },
],
examples: [
'# Find tools for a use case',
'composio search "send an email"',
+ 'composio search "send an email" "create github issue"',
+ 'composio search "my emails" "my github issues" --toolkits gmail,github',
'composio search "create issue" --toolkits github',
+ 'composio search "send an email" --human',
'',
'# Cross-app workflow discovery',
'composio search "post a message to a slack channel"',
@@ -180,7 +194,13 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
usage: 'composio execute <slug> [-d, --data text] [--dry-run] [--get-schema] [--parallel]',
description:
'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.',
- args: [{ name: '<slug>', description: 'Tool slug (e.g. "GITHUB_CREATE_ISSUE")' }],
+ args: [
+ {
+ name: '<slug>',
+ description:
+ 'Tool slug for single execute, or repeated <slug> -d <text> pairs when using -p/--parallel',
+ },
+ ],
options: [
{
name: '-d, --data <text>',
@@ -225,7 +245,7 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
'composio execute GITHUB_CREATE_ISSUE -d @issue.json',
'',
'# Execute multiple tools concurrently',
- `composio execute --parallel GMAIL_SEND_EMAIL -d '{ recipient_email: "[email protected]" }' GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,
+ `composio execute -p GMAIL_SEND_EMAIL -d '{ recipient_email: "[email protected]" }' GITHUB_CREATE_AN_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,
],
seeAlso: [
'composio search "<query>" Find tool slugs by use case',
diff --git a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
index a815a1079..dd08cc18d 100644
--- a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+++ b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
@@ -2,6 +2,7 @@ import { Args, Command, Options } from '@effect/cli';
import { Effect, Option } from 'effect';
import { TerminalUI } from 'src/services/terminal-ui';
import { requireAuth } from 'src/effects/require-auth';
+import { setupCacheDir } from 'src/effects/setup-cache-dir';
import { clampLimit } from 'src/ui/clamp-limit';
import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
import { buildMinimalPayloadFromSchema } from 'src/ui/build-minimal-payload';
@@ -14,12 +15,16 @@ import {
formatResolveCommandProjectError,
} from 'src/services/command-project';
import { commandHintExample, commandHintStep } from 'src/services/command-hints';
-import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
+import {
+ primeConsumerConnectedToolkitsCacheInBackground,
+ writeConsumerConnectedToolkitsCache,
+} from 'src/services/consumer-short-term-cache';
import { appendCliSessionHistory } from 'src/services/cli-session-artifacts';
+import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
-const query = Args.text({ name: 'query' }).pipe(
+const query = Args.repeated(Args.text({ name: 'query' })).pipe(
Args.withDescription(
- 'Semantic use-case query (e.g. "onboard a new GitHub repo and notify Slack").'
+ 'One or more semantic use-case queries (e.g. "onboard a new GitHub repo", "notify Slack").'
)
);
@@ -43,12 +48,252 @@ const limit = Options.integer('limit').pipe(
Options.withDescription('Number of results per page (1-1000)')
);
+const json = Options.boolean('json').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Print the full search response as JSON (default behavior)')
+);
+
+const human = Options.boolean('human').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Show formatted human-readable search output')
+);
+
+type SearchToolSchema = {
+ tool_slug: string;
+ toolkit: string;
+ description?: string;
+ input_schema?: Record<string, unknown>;
+ output_schema?: Record<string, unknown>;
+};
+
+type SearchResultRecord = {
+ use_case: string;
+ primary_tool_slugs: string[];
+ related_tool_slugs: string[];
+ recommended_plan_steps?: string[];
+ reference_workbench_snippets?: unknown;
+ plan_id?: string;
+};
+
+type ToolkitConnectionStatusRecord = {
+ toolkit: string;
+ has_active_connection: boolean;
+};
+
+type SearchResponseRecord = {
+ results: SearchResultRecord[];
+ toolkit_connection_statuses: ToolkitConnectionStatusRecord[];
+ tool_schemas: Record<string, SearchToolSchema>;
+ next_steps_guidance: string[];
+ error: string | null;
+};
+
+const stripSearchResultMetadata = <
+ T extends { reference_workbench_snippets?: unknown; plan_id?: unknown },
+>(
+ result: T
+) => {
+ const {
+ reference_workbench_snippets: _referenceWorkbenchSnippets,
+ plan_id: _planId,
+ ...rest
+ } = result;
+ return rest;
+};
+
+const TOOL_SCHEMA_PATH_FORMAT = '~/.composio/tool_definitions/<TOOL_SLUG>.json';
+
+const toHomeRelativePath = (cacheDir: string, absolutePath: string) =>
+ absolutePath.startsWith(cacheDir) ? absolutePath.replace(cacheDir, '~/.composio') : absolutePath;
+
+const collectToolsForResult = (params: {
+ result: {
+ primary_tool_slugs: string[];
+ related_tool_slugs: string[];
+ };
+ toolSchemas: Record<string, SearchToolSchema>;
+ toolkitSet?: Set<string>;
+ limit: number;
+}): Tool[] => {
+ const mergedSlugs: string[] = [];
+ const seen = new Set<string>();
+ for (const slug of [...params.result.primary_tool_slugs, ...params.result.related_tool_slugs]) {
+ if (!seen.has(slug)) {
+ seen.add(slug);
+ mergedSlugs.push(slug);
+ }
+ }
+
+ const toolsList: Tool[] = [];
+ for (const slug of mergedSlugs) {
+ const schema = params.toolSchemas[slug];
+ if (!schema) continue;
+ if (params.toolkitSet && !params.toolkitSet.has(schema.toolkit.toLowerCase())) continue;
+
+ toolsList.push({
+ slug: schema.tool_slug,
+ name: schema.tool_slug,
+ description: schema.description ?? '',
+ tags: [],
+ available_versions: [],
+ input_parameters: (schema.input_schema ?? {}) as Record<string, unknown>,
+ output_parameters: (schema.output_schema ?? {}) as Record<string, unknown>,
+ } as Tool);
+
+ if (toolsList.length >= params.limit) break;
+ }
+
+ return toolsList;
+};
+
+const buildSearchCta = (params: {
+ firstSlug?: string;
+ firstToolkit?: string;
+ firstDataArg: string;
+ rootOnly: boolean;
+}) => {
+ const cta: Array<{ action: string; command: string }> = [];
+ if (params.firstSlug) {
+ cta.push({
+ action: 'Execute a tool',
+ command: params.rootOnly
+ ? commandHintExample('root.execute', { slug: params.firstSlug, data: params.firstDataArg })
+ : commandHintExample('dev.playgroundExecute', {
+ slug: params.firstSlug,
+ userId: '<user-id>',
+ data: params.firstDataArg,
+ }),
+ });
+ }
+ if (params.firstToolkit) {
+ cta.push({
+ action: 'Connect a user account',
+ command: params.rootOnly
+ ? commandHintExample('root.link', { toolkit: String(params.firstToolkit).toLowerCase() })
+ : commandHintExample('dev.connectedAccounts.link', {
+ toolkit: String(params.firstToolkit).toLowerCase(),
+ userId: '<user-id>',
+ }),
+ });
+ }
+ return cta;
+};
+
+const buildSearchJsonPayload = (params: {
+ searchResponse: SearchResponseRecord;
+ cacheScope: { orgId?: string; consumerUserId?: string };
+ projectScope: { orgId: string; projectId: string };
+ cta: Array<{ action: string; command: string }>;
+}) =>
+ Effect.gen(function* () {
+ const cacheDir = yield* setupCacheDir;
+ const primaryToolSlugs = Array.from(
+ new Set(params.searchResponse.results.flatMap(result => result.primary_tool_slugs))
+ );
+ const primaryToolSchemaPaths = Object.fromEntries(
+ yield* Effect.forEach(primaryToolSlugs, slug =>
+ Effect.gen(function* () {
+ const definition = yield* getOrFetchToolInputDefinition(slug, params.projectScope);
+ return [slug, toHomeRelativePath(cacheDir, definition.schemaPath)] as const;
+ })
+ )
+ );
+ const connectedToolkits = Array.from(
+ new Set(
+ params.searchResponse.toolkit_connection_statuses
+ .filter(status => status.has_active_connection)
+ .map(status => status.toolkit.toLowerCase())
+ )
+ );
+
+ if (params.cacheScope.orgId && params.cacheScope.consumerUserId) {
+ yield* writeConsumerConnectedToolkitsCache({
+ orgId: params.cacheScope.orgId,
+ consumerUserId: params.cacheScope.consumerUserId,
+ toolkits: connectedToolkits,
+ }).pipe(Effect.catchAll(() => Effect.void));
+ }
+
+ return {
+ results: params.searchResponse.results.map(stripSearchResultMetadata),
+ tool_schemas: {
+ primary: primaryToolSchemaPaths,
+ related_tools_path_format: TOOL_SCHEMA_PATH_FORMAT,
+ },
+ connected_toolkits: connectedToolkits,
+ ...(params.searchResponse.error ? { error: params.searchResponse.error } : {}),
+ CTA: params.cta,
+ } as const;
+ });
+
+const emitHumanSearchOutput = (params: {
+ ui: TerminalUI;
+ queries: ReadonlyArray<string>;
+ resultsWithTools: Array<{ result: SearchResultRecord; tools: Tool[] }>;
+ nextStepsGuidance: ReadonlyArray<string>;
+ firstSlug?: string;
+ firstDataArg: string;
+ rootOnly: boolean;
+ error: string | null;
+}) =>
+ Effect.gen(function* () {
+ for (const { result, tools } of params.resultsWithTools) {
+ if (params.queries.length > 1) {
+ yield* params.ui.log.info(`Results for "${result.use_case}"`);
+ }
+
+ if (tools.length === 0) {
+ yield* params.ui.log.warn(`No tools found for "${result.use_case}".`);
+ continue;
+ }
+
+ yield* params.ui.log.info(`Found ${tools.length} tools\n\n${formatToolsTable(tools)}`);
+
+ const planSteps = Array.from(new Set(result.recommended_plan_steps ?? []));
+ if (planSteps.length > 0) {
+ yield* params.ui.log.info(
+ `Plan:\n${planSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}`
+ );
+ } else if (params.queries.length === 1 && params.nextStepsGuidance.length > 0) {
+ yield* params.ui.log.info(
+ `Plan:\n${params.nextStepsGuidance.map((step, i) => `${i + 1}. ${step}`).join('\n')}`
+ );
+ }
+ }
+
+ if (params.firstSlug) {
+ const executeHint = params.rootOnly
+ ? commandHintStep('Execute a tool', 'root.execute', {
+ slug: params.firstSlug,
+ data: params.firstDataArg,
+ })
+ : commandHintStep('Test a tool against a playground user', 'dev.playgroundExecute', {
+ slug: params.firstSlug,
+ userId: '<user-id>',
+ data: params.firstDataArg,
+ });
+ const linkHint = params.rootOnly
+ ? commandHintStep('Link an account', 'root.link', { toolkit: '<toolkit>' })
+ : commandHintStep('Link an account', 'dev.connectedAccounts.link', {
+ toolkit: '<toolkit>',
+ userId: '<user-id>',
+ });
+ yield* params.ui.log.step([executeHint, linkHint].join('\n'));
+ }
+
+ if (params.error) {
+ yield* params.ui.log.warn(params.error);
+ }
+ });
+
const runToolsSearch = (params: {
- query: string;
+ query: ReadonlyArray<string>;
toolkits: Option.Option<string>;
userId: Option.Option<string>;
projectName: Option.Option<string>;
limit: number;
+ json: boolean;
+ human: boolean;
rootOnly: boolean;
}) =>
Effect.gen(function* () {
@@ -58,6 +303,12 @@ const runToolsSearch = (params: {
const userContext = yield* ComposioUserContext;
const clampedLimit = clampLimit(params.limit);
+ const emitHuman = params.human;
+ const emitJson = params.json || !emitHuman;
+ const queries = params.query.map(q => q.trim()).filter(Boolean);
+ if (queries.length === 0) {
+ return yield* Effect.fail(new Error('At least one query is required.'));
+ }
const toolkitFilter = Option.getOrUndefined(params.toolkits);
const toolkitList =
toolkitFilter && toolkitFilter.trim().length > 0
@@ -67,115 +318,98 @@ const runToolsSearch = (params: {
.filter(Boolean)
: undefined;
- const searchResult = yield* ui.withSpinner(
- `Searching tools for "${params.query}"...`,
- Effect.gen(function* () {
- const resolvedProject = yield* resolveCommandProject({
- mode: 'consumer',
- projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
- }).pipe(Effect.mapError(formatResolveCommandProjectError));
- const resolvedUserId =
- resolvedProject.projectType === 'CONSUMER'
- ? Option.fromNullable(resolvedProject.consumerUserId)
- : Option.match(params.userId, {
- onSome: value => Option.some(value),
- onNone: () => userContext.data.testUserId,
- });
- if (Option.isNone(resolvedUserId)) {
- return yield* Effect.fail(
- new Error(
- 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
- )
- );
- }
- const clientSingleton = yield* ComposioClientSingleton;
- const client = yield* clientSingleton.getFor({
+ const runSearchRequest = Effect.gen(function* () {
+ const resolvedProject = yield* resolveCommandProject({
+ mode: 'consumer',
+ projectName: params.rootOnly ? undefined : Option.getOrUndefined(params.projectName),
+ }).pipe(Effect.mapError(formatResolveCommandProjectError));
+ const resolvedUserId =
+ resolvedProject.projectType === 'CONSUMER'
+ ? Option.fromNullable(resolvedProject.consumerUserId)
+ : Option.match(params.userId, {
+ onSome: value => Option.some(value),
+ onNone: () => userContext.data.testUserId,
+ });
+ if (Option.isNone(resolvedUserId)) {
+ return yield* Effect.fail(
+ new Error(
+ 'Missing user id. Provide --user-id or run composio login to set global test_user_id.'
+ )
+ );
+ }
+ const clientSingleton = yield* ComposioClientSingleton;
+ const client = yield* clientSingleton.getFor({
+ orgId: resolvedProject.orgId,
+ projectId: resolvedProject.projectId,
+ });
+ if (resolvedProject.projectType === 'CONSUMER') {
+ yield* primeConsumerConnectedToolkitsCacheInBackground({
orgId: resolvedProject.orgId,
- projectId: resolvedProject.projectId,
+ consumerUserId: resolvedUserId.value,
});
- if (resolvedProject.projectType === 'CONSUMER') {
- yield* primeConsumerConnectedToolkitsCacheInBackground({
- orgId: resolvedProject.orgId,
- consumerUserId: resolvedUserId.value,
- });
- }
- const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
- toolkits: toolkitList,
- });
- const searchResponse = yield* Effect.tryPromise(() =>
- client.toolRouter.session.search(sessionId, {
- queries: [{ use_case: params.query }],
- })
- );
- return {
- searchResponse,
- historyScope:
- resolvedProject.projectType === 'CONSUMER'
- ? {
- orgId: resolvedProject.orgId,
- consumerUserId: resolvedUserId.value,
- toolRouterSessionId: sessionId,
- }
- : undefined,
- };
- })
- );
+ }
+ const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
+ toolkits: toolkitList,
+ });
+ const searchResponse = yield* Effect.tryPromise(() =>
+ client.toolRouter.session.search(sessionId, {
+ queries: queries.map(query => ({ use_case: query })),
+ })
+ );
+ return {
+ searchResponse,
+ projectScope: {
+ orgId: resolvedProject.orgId,
+ projectId: resolvedProject.projectId,
+ },
+ historyScope:
+ resolvedProject.projectType === 'CONSUMER'
+ ? {
+ orgId: resolvedProject.orgId,
+ consumerUserId: resolvedUserId.value,
+ toolRouterSessionId: sessionId,
+ }
+ : undefined,
+ };
+ });
+
+ const searchResult = emitHuman
+ ? yield* ui.withSpinner(
+ queries.length === 1
+ ? `Searching tools for "${queries[0]}"...`
+ : `Searching tools for ${queries.length} queries...`,
+ runSearchRequest
+ )
+ : yield* runSearchRequest;
const searchResponse = searchResult.searchResponse;
const toolkitSet = toolkitList && toolkitList.length > 0 ? new Set(toolkitList) : undefined;
- const mergedSlugs: string[] = [];
- const seen = new Set<string>();
- for (const item of searchResponse.results) {
- for (const slug of [...item.primary_tool_slugs, ...item.related_tool_slugs]) {
- if (!seen.has(slug)) {
- seen.add(slug);
- mergedSlugs.push(slug);
- }
- }
- }
-
- const toolsList: Tool[] = [];
- for (const slug of mergedSlugs) {
- const schema = searchResponse.tool_schemas[slug];
- if (!schema) continue;
- if (toolkitSet && !toolkitSet.has(schema.toolkit.toLowerCase())) continue;
-
- toolsList.push({
- slug: schema.tool_slug,
- name: schema.tool_slug,
- description: schema.description ?? '',
- tags: [],
- available_versions: [],
- input_parameters: (schema.input_schema ?? {}) as Record<string, unknown>,
- output_parameters: (schema.output_schema ?? {}) as Record<string, unknown>,
- } as Tool);
-
- if (toolsList.length >= clampedLimit) break;
- }
+ const resultsWithTools = searchResponse.results.map(result => ({
+ result,
+ tools: collectToolsForResult({
+ result,
+ toolSchemas: searchResponse.tool_schemas,
+ toolkitSet,
+ limit: clampedLimit,
+ }),
+ }));
- if (toolsList.length === 0) {
- yield* ui.log.warn(`No tools found matching "${params.query}". Try broadening your search.`);
+ const totalToolCount = resultsWithTools.reduce((sum, item) => sum + item.tools.length, 0);
+ if (totalToolCount === 0) {
+ const description =
+ queries.length === 1 ? `"${queries[0]}"` : `the provided ${queries.length} queries`;
+ if (emitHuman) {
+ yield* ui.log.warn(`No tools found matching ${description}. Try broadening your search.`);
+ } else if (emitJson) {
+ yield* ui.log.message('[]');
+ yield* ui.output('[]');
+ }
return;
}
- const showing = toolsList.length;
- yield* ui.log.info(`Found ${showing} tools\n\n${formatToolsTable(toolsList)}`);
-
- const planSteps = Array.from(
- new Set(searchResponse.results.flatMap(result => result.recommended_plan_steps ?? []))
- );
- if (planSteps.length > 0) {
- yield* ui.log.info(`Plan:\n${planSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}`);
- } else if (searchResponse.next_steps_guidance.length > 0) {
- yield* ui.log.info(
- `Plan:\n${searchResponse.next_steps_guidance
- .map((step, i) => `${i + 1}. ${step}`)
- .join('\n')}`
- );
- }
-
- const firstSlug = toolsList[0]?.slug;
+ const firstToolsList = resultsWithTools.find(item => item.tools.length > 0)?.tools ?? [];
+ const firstSlug = firstToolsList[0]?.slug;
const firstSchema =
firstSlug && searchResponse.tool_schemas[firstSlug]
? searchResponse.tool_schemas[firstSlug]
@@ -188,88 +422,71 @@ const runToolsSearch = (params: {
const firstDataArg =
Object.keys(firstPayload).length === 0 ? '-d "{}"' : `-d '${firstPayloadJson}'`;
- if (firstSlug) {
- const executeHint = params.rootOnly
- ? commandHintStep('Execute a tool', 'root.execute', {
- slug: firstSlug,
- data: firstDataArg,
- })
- : commandHintStep('Test a tool against a playground user', 'dev.playgroundExecute', {
- slug: firstSlug,
- userId: '<user-id>',
- data: firstDataArg,
- });
- const linkHint = params.rootOnly
- ? commandHintStep('Link an account', 'root.link', { toolkit: '<toolkit>' })
- : commandHintStep('Link an account', 'dev.connectedAccounts.link', {
- toolkit: '<toolkit>',
- userId: '<user-id>',
- });
- yield* ui.log.step([executeHint, linkHint].join('\n'));
- }
+ const cta = buildSearchCta({
+ firstSlug,
+ firstToolkit,
+ firstDataArg,
+ rootOnly: params.rootOnly,
+ });
- if (searchResponse.error) {
- yield* ui.log.warn(searchResponse.error);
- }
-
- const cta: Array<{ action: string; command: string }> = [];
- if (firstSlug) {
- cta.push({
- action: 'Execute a tool',
- command: params.rootOnly
- ? commandHintExample('root.execute', { slug: firstSlug, data: firstDataArg })
- : commandHintExample('dev.playgroundExecute', {
- slug: firstSlug,
- userId: '<user-id>',
- data: firstDataArg,
- }),
- });
- }
- if (firstToolkit) {
- cta.push({
- action: 'Connect a user account',
- command: params.rootOnly
- ? commandHintExample('root.link', { toolkit: String(firstToolkit).toLowerCase() })
- : commandHintExample('dev.connectedAccounts.link', {
- toolkit: String(firstToolkit).toLowerCase(),
- userId: '<user-id>',
- }),
- });
- }
+ const outputForJq = yield* buildSearchJsonPayload({
+ searchResponse,
+ cacheScope: {
+ orgId: searchResult.historyScope?.orgId,
+ consumerUserId: searchResult.historyScope?.consumerUserId,
+ },
+ projectScope: searchResult.projectScope,
+ cta,
+ });
- const outputForJq = {
- ...searchResponse,
- CTA: cta,
- };
yield* appendCliSessionHistory({
orgId: searchResult.historyScope?.orgId,
consumerUserId: searchResult.historyScope?.consumerUserId,
entry: {
command: 'search',
- query: params.query,
+ query: queries.join(' | '),
+ queries,
toolkitFilter: toolkitList ?? [],
limit: clampedLimit,
- resultCount: toolsList.length,
+ resultCount: totalToolCount,
toolRouterSessionId: searchResult.historyScope?.toolRouterSessionId,
nextSteps: searchResponse.next_steps_guidance,
},
}).pipe(Effect.catchAll(() => Effect.void));
- yield* ui.output(JSON.stringify(outputForJq, null, 2));
+
+ if (emitHuman) {
+ yield* emitHumanSearchOutput({
+ ui,
+ queries,
+ resultsWithTools,
+ nextStepsGuidance: searchResponse.next_steps_guidance,
+ firstSlug,
+ firstDataArg,
+ rootOnly: params.rootOnly,
+ error: searchResponse.error,
+ });
+ } else if (emitJson) {
+ const outputJson = JSON.stringify(outputForJq, null, 2);
+ yield* ui.log.message(outputJson);
+ yield* ui.output(outputJson);
+ }
});
export const toolsCmd$Search = Command.make(
'search',
- { query, toolkits, userId, projectName, limit },
- ({ query, toolkits, userId, projectName, limit }) =>
- runToolsSearch({ query, toolkits, userId, projectName, limit, rootOnly: false })
+ { query, toolkits, userId, projectName, limit, json, human },
+ ({ query, toolkits, userId, projectName, limit, json, human }) =>
+ runToolsSearch({ query, toolkits, userId, projectName, limit, json, human, rootOnly: false })
).pipe(
Command.withDescription(
[
- 'Find tools by use case. Returns matching tools with slugs you can pass directly to `execute`.',
+ 'Find tools by use case. Defaults to full JSON output; use `--human` for formatted output.',
'',
'Examples:',
' composio search "send an email"',
+ ' composio search "send an email" "create a github issue"',
' composio search "create issue" --toolkits github',
+ ' composio search "send an email" --human',
' composio search "list calendar events" --limit 5',
'',
'Next steps:',
@@ -282,24 +499,28 @@ export const toolsCmd$Search = Command.make(
export const rootToolsCmd$Search = Command.make(
'search',
- { query, toolkits, limit },
- ({ query, toolkits, limit }) =>
+ { query, toolkits, limit, json, human },
+ ({ query, toolkits, limit, json, human }) =>
runToolsSearch({
query,
toolkits,
userId: Option.none(),
projectName: Option.none(),
limit,
+ json,
+ human,
rootOnly: true,
})
).pipe(
Command.withDescription(
[
- 'Find tools by use case. Returns matching tools with slugs you can pass directly to `execute`.',
+ 'Find tools by use case. Defaults to full JSON output; use `--human` for formatted output.',
'',
'Examples:',
' composio search "send an email"',
+ ' composio search "send an email" "create a github issue"',
' composio search "create issue" --toolkits github',
+ ' composio search "send an email" --human',
' composio search "list calendar events" --limit 5',
'',
'Next steps:',
diff --git a/ts/packages/cli/src/services/consumer-short-term-cache.ts b/ts/packages/cli/src/services/consumer-short-term-cache.ts
index e285d4007..b3a58505a 100644
--- a/ts/packages/cli/src/services/consumer-short-term-cache.ts
+++ b/ts/packages/cli/src/services/consumer-short-term-cache.ts
@@ -211,6 +211,31 @@ export const refreshConsumerConnectedToolkitsCache = (params?: {
});
});
+export const writeConsumerConnectedToolkitsCache = (params: {
+ readonly orgId: string;
+ readonly consumerUserId: string;
+ readonly toolkits: ReadonlyArray<string>;
+}) =>
+ Effect.gen(function* () {
+ const state = yield* readCache();
+ const key = cacheKey(params.orgId, params.consumerUserId);
+ const currentEntry = state[key];
+ const proc = yield* NodeProcess;
+ const searchSessionFields = resolveSearchSessionMetadata({
+ currentEntry,
+ cwd: proc.cwd,
+ });
+
+ yield* writeCache({
+ ...state,
+ [key]: {
+ toolkits: [...new Set(params.toolkits.map(toolkit => toolkit.toLowerCase()))],
+ expiresAt: new Date(Date.now() + CACHE_TTL_MS).toISOString(),
+ ...searchSessionFields,
+ },
+ });
+ });
+
export const primeConsumerConnectedToolkitsCacheInBackground = (params?: {
readonly orgId?: string;
readonly consumerUserId?: string;
diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.ts
index 8dd52cb29..8d6254c9d 100644
--- a/ts/packages/cli/test/__utils__/services/test-layer.ts
+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts
@@ -857,18 +857,31 @@ export const TestLayer = (input?: TestLiveInput) =>
_sessionId: string,
params: SessionSearchParams
): Promise<SessionSearchResponse> => {
- const queryUseCase = params.queries[0]?.use_case ?? '';
- const normalizedQuery = queryUseCase.toLowerCase();
- const matchedTools = toolkitsData.tools.filter(
- tool =>
- tool.name.toLowerCase().includes(normalizedQuery) ||
- tool.slug.toLowerCase().includes(normalizedQuery) ||
- tool.description.toLowerCase().includes(normalizedQuery)
- );
+ const results = params.queries.map((query, index) => {
+ const queryUseCase = query.use_case ?? '';
+ const normalizedQuery = queryUseCase.toLowerCase();
+ const matchedTools = toolkitsData.tools.filter(
+ tool =>
+ tool.name.toLowerCase().includes(normalizedQuery) ||
+ tool.slug.toLowerCase().includes(normalizedQuery) ||
+ tool.description.toLowerCase().includes(normalizedQuery)
+ );
+
+ return {
+ index: index + 1,
+ use_case: queryUseCase,
+ primary_tool_slugs: matchedTools.map(tool => tool.slug),
+ related_tool_slugs: [],
+ toolkits: Array.from(
+ new Set(matchedTools.map(tool => tool.slug.split('_')[0]?.toLowerCase() ?? '').filter(Boolean))
+ ),
+ matchedTools,
+ };
+ });
- const primaryToolSlugs = matchedTools.map(tool => tool.slug);
+ const allMatchedTools = results.flatMap(result => result.matchedTools);
const toolSchemas = Object.fromEntries(
- matchedTools.map(tool => [
+ allMatchedTools.map(tool => [
tool.slug,
{
tool_slug: tool.slug,
@@ -882,7 +895,7 @@ export const TestLayer = (input?: TestLiveInput) =>
);
const toolkitConnectionStatuses = Array.from(
new Set(
- matchedTools.map(tool => tool.slug.split('_')[0]?.toLowerCase() ?? '').filter(Boolean)
+ allMatchedTools.map(tool => tool.slug.split('_')[0]?.toLowerCase() ?? '').filter(Boolean)
)
).map(toolkitSlug => ({
toolkit: toolkitSlug,
@@ -894,15 +907,7 @@ export const TestLayer = (input?: TestLiveInput) =>
return {
success: true,
error: null,
- results: [
- {
- index: 1,
- use_case: queryUseCase,
- primary_tool_slugs: primaryToolSlugs,
- related_tool_slugs: [],
- toolkits: toolkitConnectionStatuses.map(t => t.toolkit),
- },
- ],
+ results: results.map(({ matchedTools: _matchedTools, ...result }) => result),
tool_schemas: toolSchemas,
toolkit_connection_statuses: toolkitConnectionStatuses,
next_steps_guidance: [],
diff --git a/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
index a9f88e6fd..ffa67fb43 100644
--- a/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
@@ -54,42 +54,71 @@ const testLiveOptions = {
};
describe('CLI: composio search', () => {
- layer(TestLive(testLiveOptions))('[Given] query "send" [Then] returns matching tools', it => {
- it.scoped('returns matching tools', () =>
+ layer(TestLive(testLiveOptions))('[Given] query "send" [Then] returns JSON by default', it => {
+ it.scoped('returns JSON payload by default', () =>
Effect.gen(function* () {
yield* cli(['search', 'send']);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
+ expect(output).toContain('"results"');
+ expect(output).toContain('"tool_schemas"');
+ expect(output).toContain('"primary"');
+ expect(output).toContain('"related_tools_path_format"');
+ expect(output).toContain('"connected_toolkits"');
+ expect(output).toContain('"CTA"');
+ expect(output).not.toContain('"session"');
+ expect(output).not.toContain('"time_info"');
+ expect(output).not.toContain('"next_steps_guidance"');
+ expect(output).not.toContain('"success"');
+ expect(output).not.toContain('"error"');
expect(output).toContain('GMAIL_SEND_EMAIL');
expect(output).toContain('SLACK_SEND_MESSAGE');
- expect(output).not.toContain('GITHUB_CREATE_ISSUE');
- expect(output).toContain('Found 2 tools');
+ expect(output).toContain('~/.composio/tool_definitions/GMAIL_SEND_EMAIL.json');
})
);
});
+ layer(TestLive(testLiveOptions))(
+ '[Given] multiple queries [Then] the CLI returns a batched JSON response',
+ it => {
+ it.scoped('returns batched results in JSON', () =>
+ Effect.gen(function* () {
+ yield* cli(['search', 'send', 'create issue']);
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const output = lines.join('\n');
+
+ expect(output).toContain('"use_case": "send"');
+ expect(output).toContain('"use_case": "create issue"');
+ expect(output).toContain('GMAIL_SEND_EMAIL');
+ expect(output).toContain('SLACK_SEND_MESSAGE');
+ expect(output).toContain('GITHUB_CREATE_ISSUE');
+ })
+ );
+ }
+ );
+
layer(TestLive(testLiveOptions))(
'[Given] query with no results [Then] shows not found message',
it => {
- it.scoped('shows not found message', () =>
+ it.scoped('shows empty json output', () =>
Effect.gen(function* () {
yield* cli(['search', 'nonexistent_query']);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
- expect(output).toContain('No tools found');
+ expect(output).toContain('[]');
})
);
}
);
layer(TestLive(testLiveOptions))(
- '[Given] query "send" --toolkits "gmail" [Then] scopes to toolkit',
+ '[Given] query "send" --toolkits "gmail" --human [Then] scopes to toolkit',
it => {
it.scoped('scopes search to toolkit', () =>
Effect.gen(function* () {
- yield* cli(['search', 'send', '--toolkits', 'gmail']);
+ yield* cli(['search', 'send', '--toolkits', 'gmail', '--human']);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
const humanOutput = output.split('\n{')[0] ?? output;
@@ -103,20 +132,42 @@ describe('CLI: composio search', () => {
);
layer(TestLive(testLiveOptions))(
- '[Given] tools search [Then] JSON output includes full tool-router payload and CTA',
+ '[Given] search --human [Then] it stays human-readable and omits raw JSON',
+ it => {
+ it.scoped('does not print raw JSON in human mode', () =>
+ Effect.gen(function* () {
+ yield* cli(['search', 'send', '--human']);
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const output = lines.join('\n');
+
+ expect(output).not.toContain('"results"');
+ expect(output).not.toContain('"tool_schemas"');
+ expect(output).toContain('Found 2 tools');
+ expect(output).toContain('composio execute');
+ expect(output).toContain('composio link <toolkit>');
+ })
+ );
+ }
+ );
+
+ layer(TestLive(testLiveOptions))(
+ '[Given] search --json [Then] JSON output includes full tool-router payload and CTA',
it => {
it.scoped('prints full search response with CTA for jq', () =>
Effect.gen(function* () {
- yield* cli(['search', 'send']);
+ yield* cli(['search', 'send', '--json']);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
expect(output).toContain('"results"');
expect(output).toContain('"tool_schemas"');
- expect(output).toContain('"toolkit_connection_statuses"');
- expect(output).toContain('"session"');
- expect(output).toContain('"time_info"');
+ expect(output).toContain('"connected_toolkits"');
expect(output).toContain('"CTA"');
+ expect(output).not.toContain('"session"');
+ expect(output).not.toContain('"time_info"');
+ expect(output).not.toContain('"next_steps_guidance"');
+ expect(output).not.toContain('"success"');
+ expect(output).not.toContain('"error"');
expect(output).toContain('"Execute a tool"');
expect(output).toContain('"Connect a user account"');
expect(output).toContain('composio execute');
@@ -126,6 +177,72 @@ describe('CLI: composio search', () => {
}
);
+ layer(TestLive(testLiveOptions))(
+ '[Given] search results with workbench snippets [Then] snippets are removed from JSON output',
+ it => {
+ it.scoped('omits workbench snippets and emits schema/cache references', () =>
+ Effect.gen(function* () {
+ const live = TestLive({
+ ...testLiveOptions,
+ toolRouter: {
+ search: async (_sessionId, params) => ({
+ success: true,
+ error: null,
+ results: [
+ {
+ index: 1,
+ use_case: params.queries[0]?.use_case ?? '',
+ primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
+ related_tool_slugs: [],
+ toolkits: ['gmail'],
+ reference_workbench_snippets: [{ description: 'snippet', code: 'print("hi")' }],
+ },
+ ],
+ tool_schemas: {
+ GMAIL_SEND_EMAIL: {
+ tool_slug: 'GMAIL_SEND_EMAIL',
+ toolkit: 'gmail',
+ description: 'Sends an email',
+ hasFullSchema: true,
+ input_schema: { type: 'object', properties: {} },
+ output_schema: { type: 'object', properties: {} },
+ },
+ },
+ toolkit_connection_statuses: [
+ {
+ toolkit: 'gmail',
+ description: 'gmail toolkit',
+ has_active_connection: false,
+ status_message: 'No active connection',
+ },
+ ],
+ next_steps_guidance: [],
+ session: {
+ id: 'trs_test_session',
+ generate_id: false,
+ instructions: 'Reuse this session id for follow-up calls.',
+ },
+ time_info: {
+ current_time_utc: '2026-01-01T00:00:00.000Z',
+ current_time_utc_epoch_seconds: 1767225600,
+ message: 'UTC time',
+ },
+ }),
+ },
+ });
+
+ yield* cli(['search', 'send']).pipe(Effect.provide(live));
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const output = lines.join('\n');
+
+ expect(output).not.toContain('reference_workbench_snippets');
+ expect(output).toContain('~/.composio/tool_definitions/GMAIL_SEND_EMAIL.json');
+ expect(output).toContain('"related_tools_path_format"');
+ })
+ );
+ }
+ );
+
layer(TestLive({ baseConfigProvider: testConfigProvider, fixture: 'global-test-user-id' }))(
'[Given] search with schema properties [Then] CTA has valid payload and lowercase link',
it => {
@@ -280,6 +397,79 @@ describe('CLI: composio search', () => {
}
);
+ layer(TestLive(testLiveOptions))(
+ '[Given] multiple queries [Then] search passes all queries to the tool-router session',
+ it => {
+ it.scoped('passes batched queries without a parallel flag', () =>
+ Effect.gen(function* () {
+ let searchParams: SessionSearchParams | undefined;
+
+ const live = TestLive({
+ baseConfigProvider: testConfigProvider,
+ toolkitsData,
+ fixture: 'global-test-user-id',
+ toolRouter: {
+ search: async (_sessionId, params) => {
+ searchParams = params;
+ return {
+ success: true,
+ error: null,
+ results: params.queries.map((query, index) => ({
+ index: index + 1,
+ use_case: query.use_case ?? '',
+ primary_tool_slugs:
+ query.use_case === 'create issue'
+ ? ['GITHUB_CREATE_ISSUE']
+ : ['GMAIL_SEND_EMAIL'],
+ related_tool_slugs: [],
+ toolkits: query.use_case === 'create issue' ? ['github'] : ['gmail'],
+ })),
+ tool_schemas: {
+ GMAIL_SEND_EMAIL: {
+ tool_slug: 'GMAIL_SEND_EMAIL',
+ toolkit: 'gmail',
+ description: 'Sends an email',
+ hasFullSchema: true,
+ input_schema: { type: 'object', properties: {} },
+ output_schema: { type: 'object', properties: {} },
+ },
+ GITHUB_CREATE_ISSUE: {
+ tool_slug: 'GITHUB_CREATE_ISSUE',
+ toolkit: 'github',
+ description: 'Creates a GitHub issue',
+ hasFullSchema: true,
+ input_schema: { type: 'object', properties: {} },
+ output_schema: { type: 'object', properties: {} },
+ },
+ },
+ toolkit_connection_statuses: [],
+ next_steps_guidance: [],
+ session: {
+ id: 'trs_test_session',
+ generate_id: false,
+ instructions: 'Reuse this session id for follow-up calls.',
+ },
+ time_info: {
+ current_time_utc: '2026-01-01T00:00:00.000Z',
+ current_time_utc_epoch_seconds: 1767225600,
+ message: 'UTC time',
+ },
+ };
+ },
+ },
+ });
+
+ yield* cli(['search', 'send', 'create issue']).pipe(Effect.provide(live));
+
+ expect(searchParams?.queries.map(query => query.use_case)).toEqual([
+ 'send',
+ 'create issue',
+ ]);
+ })
+ );
+ }
+ );
+
layer(TestLive(testLiveOptions))(
'[Given] search response with recommended plan [Then] it prints plan and execute hint',
it => {
@@ -336,7 +526,7 @@ describe('CLI: composio search', () => {
},
});
- yield* cli(['search', 'send email']).pipe(Effect.provide(live));
+ yield* cli(['search', 'send email', '--human']).pipe(Effect.provide(live));
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
@@ -353,7 +543,7 @@ describe('CLI: composio search', () => {
layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
it.scoped('warns user to login', () =>
Effect.gen(function* () {
- yield* cli(['search', 'send']);
+ yield* cli(['search', 'send', '--human']);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
@@ -404,7 +594,8 @@ describe('CLI: composio search', () => {
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');
- expect(output).toContain('Found 2 tools');
+ expect(output).toContain('"results"');
+ expect(output).toContain('GMAIL_SEND_EMAIL');
expect(output).not.toContain('Using global test user id');
})
);
@@ -415,7 +606,7 @@ describe('CLI: composio search', () => {
it => {
it.scoped('search returns matching tools', () =>
Effect.gen(function* () {
- yield* cli(['search', 'send']);
+ yield* cli(['search', 'send', '--human']);
const lines = yield* MockConsole.getLines({ stripAnsi: true });
const output = lines.join('\n');