Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat(cli): enhance init and tool-router based tool discovery (#2767)
Musthaq Ahamad2bd2db476cf7
diff --git a/.changeset/few-beers-join.md b/.changeset/few-beers-join.mdnew file mode 100644index 000000000..e4fe4d784--- /dev/null+++ b/.changeset/few-beers-join.md@@ -0,0 +1,5 @@+---+'@composio/cli': patch+---++Update tool search and API key inferencediff --git a/ts/e2e-tests/cli/toolkits/list/e2e.test.ts b/ts/e2e-tests/cli/toolkits/list/e2e.test.tsindex 9d49ae31a..2e1959e38 100644--- a/ts/e2e-tests/cli/toolkits/list/e2e.test.ts+++ b/ts/e2e-tests/cli/toolkits/list/e2e.test.ts@@ -58,9 +58,10 @@ e2e(import.meta.url, {expect(item).toHaveProperty('name');expect(item).toHaveProperty('slug');expect(item).toHaveProperty('description');- expect(item).toHaveProperty('is_no_auth');- expect(item).toHaveProperty('enabled');- expect(item).toHaveProperty('composio_managed_auth_schemes');+ // `toolkits list` without user-id uses legacy listing output.+ expect(item).toHaveProperty('latest_version');+ expect(item).toHaveProperty('tools_count');+ expect(item).toHaveProperty('triggers_count');});});diff --git a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.tsindex 3879a9419..4a7b01dfc 100644--- a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts+++ b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts@@ -7,6 +7,7 @@ import { requireAuth } from 'src/effects/require-auth';import { handleHttpServerError } from 'src/effects/handle-http-error';import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';import { extractMessage } from 'src/utils/api-error-extraction';+import { ProjectContext } from 'src/services/project-context';const toolkit = Args.text({ name: 'toolkit' }).pipe(Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),@@ -19,8 +20,8 @@ const authConfig = Options.text('auth-config').pipe();const userId = Options.text('user-id').pipe(- Options.withDescription('User ID for the connection'),- Options.withDefault('default')+ Options.withDescription('User ID for the connection (falls back to project test_user_id)'),+ Options.optional);const noBrowser = Options.boolean('no-browser').pipe(@@ -125,6 +126,21 @@ export const connectedAccountsCmd$Link = Command.make(const ui = yield* TerminalUI;const repo = yield* ComposioToolkitsRepository;+ const projectContext = yield* ProjectContext;+ const resolvedProjectContext = yield* projectContext.resolve;+ const testUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);+ const resolvedUserId = Option.match(userId, {+ onSome: value => Option.some(value),+ onNone: () => testUserId,+ });+ if (Option.isNone(resolvedUserId)) {+ return yield* Effect.fail(+ new Error('Missing user id. Provide --user-id or run composio init to set test_user_id.')+ );+ }+ if (Option.isNone(userId) && Option.isSome(testUserId)) {+ yield* ui.log.warn(`Using test user id "${testUserId.value}"`);+ }// Validate: exactly one of <toolkit> or --auth-config must be providedif (Option.isSome(toolkit) && Option.isSome(authConfig)) {@@ -152,7 +168,7 @@ export const connectedAccountsCmd$Link = Command.make('Creating link session...',repo.createConnectedAccountLink({auth_config_id: authConfig.value,- user_id: userId,+ user_id: resolvedUserId.value,})).pipe(@@ -186,7 +202,7 @@ export const connectedAccountsCmd$Link = Command.make(.withSpinner(`Linking ${toolkitSlug}...`,Effect.gen(function* () {- const { client, sessionId } = yield* resolveToolRouterSession(userId, {+ const { client, sessionId } = yield* resolveToolRouterSession(resolvedUserId.value, {manageConnections: true,});return yield* Effect.tryPromise(() =>diff --git a/ts/packages/cli/src/commands/init.cmd.ts b/ts/packages/cli/src/commands/init.cmd.tsindex cabe4922a..9528f7c28 100644--- a/ts/packages/cli/src/commands/init.cmd.ts+++ b/ts/packages/cli/src/commands/init.cmd.ts@@ -1,25 +1,21 @@import path from 'node:path';import { Command as CliCommand, Options } from '@effect/cli';-import { Command as PlatformCommand } from '@effect/platform';import { Effect, Option } from 'effect';import { FileSystem } from '@effect/platform';import { ComposioUserContext } from 'src/services/user-context';import { NodeProcess } from 'src/services/node-process';import { projectKeysToJSON, type ProjectKeys } from 'src/models/project-keys';-import { listOrgProjects, type OrgProject } from 'src/services/composio-clients';+import { userDataFromJSON } from 'src/models/user-data';+import {+ createProjectApiKey,+ getSessionInfo,+ listOrgProjects,+ type OrgProject,+} from 'src/services/composio-clients';import * as constants from 'src/constants';import { TerminalUI } from 'src/services/terminal-ui';import { browserLogin, noBrowser as noBrowserOpt } from 'src/commands/login.cmd';-import {- ProjectEnvironmentDetector,- type ProjectEnvironment,-} from 'src/services/project-environment-detector';-import { CommandRunner } from 'src/services/command-runner';-import {- detectCoreDependencyPlan,- resolveCoreDependencyState,- type CoreDependencyPlan,-} from 'src/effects/core-dependency';+import { setupCacheDir } from 'src/effects/setup-cache-dir';/*** `composio init` — Initialize a Composio project in the current directory.@@ -27,18 +23,11 @@ import {* ## Behavior** 1. **Project selection** — fetches projects from the API or accepts `--org-id`/`--project-id`.- * 2. **Usage mode** — asks "Native tools" vs "Composio MCP".- * 3. **Framework** — if native, asks which agent framework.- * 4. **Coding-agent skills** — asks whether to install Composio skills.- * 5. **Environment detection** — detects language (TS/Python) and package manager.- * 6. **Dependency installation** — installs `@composio/core` or `composio` via detected PM.- * 7. **Writes config** — saves `<cwd>/.composio/project.json` and `<cwd>/.composio/config.json`.+ * 2. **Writes config** — saves `<cwd>/.composio/project.json`.** ## Flags*- * - `--dry-run` — print install command without executing- * - `--force` — reinstall even if dependency is already present- * - `--yes` / `-y` — skip confirmation prompts+ * - `--yes` / `-y` — auto-select the first project from the list*/const orgIdOpt = Options.text('org-id').pipe(@@ -51,287 +40,17 @@ const projectIdOpt = Options.text('project-id').pipe(Options.withDescription('Project ID (skip interactive picker)'));-const dryRunOpt = Options.boolean('dry-run').pipe(- Options.withDefault(false),- Options.withDescription('Print install command without executing it')-);--const forceOpt = Options.boolean('force').pipe(- Options.withDefault(false),- Options.withDescription('Reinstall even if dependency appears installed')-);-const yesOpt = Options.boolean('yes').pipe(Options.withAlias('y'),Options.withDefault(false),- Options.withDescription('Skip confirmation prompts')+ Options.withDescription('Auto-select default org/project, else first project'));-const noSkillsOpt = Options.boolean('no-skills').pipe(- Options.withDefault(false),- Options.withDescription('Skip Composio skills installation')-);--// ----------------------------------------------------------------------------// Init config types and options-// -----------------------------------------------------------------------------type UsageMode = 'native' | 'mcp';-type NativeFramework = 'skip' | 'ai-sdk' | 'mastra' | 'openai-agents' | 'claude-agent-sdk';--const USAGE_MODE_OPTIONS: ReadonlyArray<{- value: UsageMode;- label: string;- hint: string;-}> = [- {- value: 'native',- label: 'Native tools',- hint: 'Use with Agent frameworks: AI SDK, Mastra, etc.',- },- {- value: 'mcp',- label: 'Composio MCP',- hint: 'Use Composio tools via MCP',- },-];--const NATIVE_FRAMEWORK_OPTIONS: ReadonlyArray<{- value: NativeFramework;- label: string;-}> = [- { value: 'skip', label: 'Skip' },- { value: 'ai-sdk', label: 'AI SDK' },- { value: 'mastra', label: 'Mastra' },- { value: 'openai-agents', label: 'OpenAI Agents' },- { value: 'claude-agent-sdk', label: 'Claude Agent SDK' },-];--// ----------------------------------------------------------------------------// InitConfig — type-safe builder for the init wizard answers-// -----------------------------------------------------------------------------/**- * Immutable config object built step-by-step through the init wizard.- * Each `.with*` method returns a new instance with the added field,- * narrowing the type so downstream code can rely on what has been set.- *- * The builder enforces that `build()` can only be called once ALL wizard- * steps have been completed — calling it too early is a compile-time error.- *- * Future wizard steps (e.g., detected environment, dependency list) can be- * added by introducing new `with*` methods and extending the `build()`- * constraint.- */-class InitConfigBuilder<T extends Record<string, unknown> = Record<string, never>> {- private constructor(private readonly data: T) {}-- static create(): InitConfigBuilder {- return new InitConfigBuilder({});- }-- withUsageMode(mode: UsageMode): InitConfigBuilder<T & { usageMode: UsageMode }> {- return new InitConfigBuilder({ ...this.data, usageMode: mode });- }-- withFramework(- fw: NativeFramework | undefined- ): InitConfigBuilder<T & { framework: NativeFramework | undefined }> {- return new InitConfigBuilder({ ...this.data, framework: fw });- }-- withInstallSkills(install: boolean): InitConfigBuilder<T & { installSkills: boolean }> {- return new InitConfigBuilder({ ...this.data, installSkills: install });- }-- withDetectedEnv(- env: ProjectEnvironment | undefined- ): InitConfigBuilder<T & { detectedEnv: ProjectEnvironment | undefined }> {- return new InitConfigBuilder({ ...this.data, detectedEnv: env });- }-- withInstallPlan(- plan: CoreDependencyPlan | undefined- ): InitConfigBuilder<T & { installPlan: CoreDependencyPlan | undefined }> {- return new InitConfigBuilder({ ...this.data, installPlan: plan });- }-- /** Extract the final config. Only callable when all required fields are present. */- build(- this: InitConfigBuilder<{- usageMode: UsageMode;- framework: NativeFramework | undefined;- installSkills: boolean;- detectedEnv: ProjectEnvironment | undefined;- installPlan: CoreDependencyPlan | undefined;- }>- ): InitConfig {- return {- usageMode: this.data.usageMode,- framework: this.data.framework,- installSkills: this.data.installSkills,- detectedEnv: this.data.detectedEnv,- installPlan: this.data.installPlan,- };- }-- /** Read accumulated data (for intermediate access). */- get value(): T {- return this.data;- }-}--interface InitConfig {- readonly usageMode: UsageMode;- readonly framework: NativeFramework | undefined;- readonly installSkills: boolean;- readonly detectedEnv: ProjectEnvironment | undefined;- readonly installPlan: CoreDependencyPlan | undefined;-}--// ----------------------------------------------------------------------------// Init wizard — collects all answers via the builder-// -----------------------------------------------------------------------------/**- * Detect the project environment. Returns `undefined` if detection fails- * (logs a warning but does not abort the wizard).- */-const detectEnvironment = (cwd: string) =>- Effect.gen(function* () {- const ui = yield* TerminalUI;- const envDetector = yield* ProjectEnvironmentDetector;-- return yield* envDetector.detectProjectEnvironment(cwd).pipe(- Effect.tap(env => ui.log.step(`Detected: ${env.language} (${env.packageManager})`)),- Effect.catchTag('services/ProjectEnvironmentDetectorError', e =>- Effect.gen(function* () {- yield* ui.log.warn(e.message);- if (e.details) yield* ui.log.info(e.details);- yield* ui.log.info('Skipping dependency installation.');- return undefined;- })- )- );- });--/**- * Resolve the install plan for the detected environment.- * Only determines WHAT to install (no version checking or shell commands).- * Version checking is deferred to `runInstallStep`.- */-const resolveInstallPlan = (cwd: string) =>- detectCoreDependencyPlan(cwd).pipe(Effect.catchAll(() => Effect.succeed(null)));--/**- * After detecting the project environment and resolving an install plan,- * ask the user to confirm the detected package manager or skip installation.- * Returns the plan if confirmed, `undefined` if skipped.- */-const confirmInstallPlan = (plan: CoreDependencyPlan) =>- Effect.gen(function* () {- const ui = yield* TerminalUI;-- type PmChoice = 'confirm' | 'skip';- const choice = yield* ui.select<PmChoice>(- `Install ${plan.dependency} using ${plan.packageManager}?`,- [- { value: 'confirm' as PmChoice, label: plan.packageManager, hint: plan.installCommand },- { value: 'skip' as PmChoice, label: 'Skip' },- ]- );-- return choice === 'confirm' ? plan : undefined;- });--/**- * Runs the interactive init wizard.- *- * Steps:- * 1. Usage mode — "Native tools" or "Composio MCP"- * 2. Framework — which agent framework (only if native)- * 3. Install skills — whether to install Composio coding-agent skills- * 4. Detect project environment (only if native)- * 5. Resolve + confirm install plan (only if native and environment detected)- *- * All inputs are collected through the builder before any side effects run.- * Returns a fully-built `InitConfig`.- */-const runInitWizard = (cwd: string, params: { noSkills: boolean }) =>- Effect.gen(function* () {- const ui = yield* TerminalUI;-- // Step 1: Usage mode- const usageMode = yield* ui.select<UsageMode>(- 'How would you like to use Composio?',- USAGE_MODE_OPTIONS- );-- // Step 2: Framework (only for native tools)- const framework: NativeFramework | undefined =- usageMode === 'native'- ? yield* ui- .select<NativeFramework>('Which framework do you use?', NATIVE_FRAMEWORK_OPTIONS)- .pipe(Effect.map(fw => (fw === 'skip' ? undefined : fw)))- : undefined;-- // Step 3: Install Composio skills (skip prompt when --no-skills)- const installSkills = params.noSkills- ? false- : yield* ui.confirm('Install Composio skills for your Coding Agent?', {- defaultValue: true,- });-- // Steps 4+5: Detect environment + confirm install plan (only for native tools)- let detectedEnv: ProjectEnvironment | undefined;- let installPlan: CoreDependencyPlan | undefined;-- if (usageMode === 'native') {- // Step 4: Detect project environment- detectedEnv = yield* detectEnvironment(cwd);-- // Step 5: Resolve install plan and confirm package manager- if (detectedEnv) {- const plan = yield* resolveInstallPlan(cwd);- if (plan) {- installPlan = yield* confirmInstallPlan(plan);- }- }- }-- return InitConfigBuilder.create()- .withUsageMode(usageMode)- .withFramework(framework)- .withInstallSkills(installSkills)- .withDetectedEnv(detectedEnv)- .withInstallPlan(installPlan)- .build();- });-// ---------------------------------------------------------------------------// File I/O helpers// -----------------------------------------------------------------------------/**- * Serializes an `InitConfig` to the JSON payload written to `.composio/config.json`.- */-const initConfigToJSON = (config: InitConfig): string => {- const payload: Record<string, unknown> = {- usage_mode: config.usageMode,- };- if (config.framework) {- payload.framework = config.framework;- }- payload.install_skills = config.installSkills;- if (config.detectedEnv) {- payload.detected_language = config.detectedEnv.language;- payload.package_manager = config.detectedEnv.packageManager;- }- return JSON.stringify(payload, null, 2);-};--/** Writes project keys + init config to `<cwd>/.composio/` and creates a `.gitignore`. */-const writeProjectConfig = (composioDir: string, selected: ProjectKeys, config: InitConfig) =>+/** Writes project keys to `<cwd>/.composio/` and creates a `.gitignore`. */+const writeProjectConfig = (composioDir: string, selected: ProjectKeys) =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;@@ -345,8 +64,6 @@ const writeProjectConfig = (composioDir: string, selected: ProjectKeys, config:projectJson);- yield* fs.writeFileString(path.join(composioDir, 'config.json'), initConfigToJSON(config));-// Create .composio/.gitignore to prevent accidental commitsconst gitignorePath = path.join(composioDir, '.gitignore');const gitignoreExists = yield* fs.exists(gitignorePath);@@ -356,169 +73,145 @@ const writeProjectConfig = (composioDir: string, selected: ProjectKeys, config:});// ----------------------------------------------------------------------------// Install step — runs after wizard, before outro+// Structured output helper// ----------------------------------------------------------------------------/**- * Runs the dependency installation step based on the init config.- * Handles --dry-run, --force, --yes flags and already-installed detection.- */-const runInstallStep = (params: {- config: InitConfig;- cwd: string;- dryRun: boolean;- force: boolean;- yes: boolean;-}) =>+const makeOutputJson = (selected: ProjectKeys, composioDir: string) =>+ JSON.stringify({+ org_id: selected.orgId,+ project_id: selected.projectId,+ path: composioDir,+ });++const getGlobalUserApiKey = () =>Effect.gen(function* () {- const { config, cwd, dryRun, force, yes } = params;- if (!config.installPlan) return;+ const fs = yield* FileSystem.FileSystem;+ const cacheDir = yield* setupCacheDir;+ const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);+ const exists = yield* fs.exists(userConfigPath);+ if (!exists) return undefined;- const ui = yield* TerminalUI;- const runner = yield* CommandRunner;- const plan = config.installPlan;+ const userDataRaw = yield* fs.readFileString(userConfigPath, 'utf8');+ const parsed = yield* userDataFromJSON(userDataRaw).pipe(Effect.option);+ if (Option.isNone(parsed)) return undefined;- // Check if already installed (only for JS — Python version check requires shell)- if (plan.kind === 'js') {- const depState = yield* resolveCoreDependencyState(cwd).pipe(- Effect.catchAll(() => Effect.succeed({ plan, installedVersion: null }))- );+ return Option.getOrUndefined(parsed.value.apiKey);+ });- if (depState.installedVersion && !force) {- const detail =- depState.installedVersion.source === 'package.json'- ? `declared in package.json (${depState.installedVersion.version})`- : `${depState.installedVersion.version} (${depState.installedVersion.source})`;- yield* ui.log.info(`Found ${plan.dependency}: ${detail}`);- yield* ui.log.success('Dependency already installed.');- return;- }+const upsertEnvVar = (content: string, key: string, value: string): string => {+ const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const line = `${key}=${value}`;+ const pattern = new RegExp(`^${escapedKey}=.*$`, 'm');+ if (pattern.test(content)) {+ return content.replace(pattern, line);+ }+ return content.trim().length ? `${content.trimEnd()}\n${line}\n` : `${line}\n`;+};- if (depState.installedVersion && force) {- yield* ui.log.warn('Reinstalling due to --force.');- }- }+const ensureProjectApiKeyInEnv = (params: { cwd: string; selected: ProjectKeys }) =>+ Effect.gen(function* () {+ const { cwd, selected } = params;+ const ui = yield* TerminalUI;+ const fs = yield* FileSystem.FileSystem;+ const ctx = yield* ComposioUserContext;- if (dryRun) {- yield* ui.note(plan.installCommand, 'Install Command');- yield* ui.log.info('Dry run complete.');- return;- }+ const envPath = path.join(cwd, '.env.local');+ const envExists = yield* fs.exists(envPath);+ const existingEnvContent = envExists ? yield* fs.readFileString(envPath, 'utf8') : '';+ const hasProjectApiKey = /^COMPOSIO_API_KEY=.*/m.test(existingEnvContent);+ const hasTestUserId = /^COMPOSIO_TEST_USER_ID=.*/m.test(existingEnvContent);- const shouldInstall =- yes || (yield* ui.confirm(`Run: ${plan.installCommand}?`, { defaultValue: true }));- if (!shouldInstall) {- yield* ui.log.warn('Installation cancelled.');+ const uakApiKey = yield* getGlobalUserApiKey();+ if (!uakApiKey) {+ yield* ui.log.warn('No global API key found; skipping .env.local creation.');return;}- const [cmd, ...args] = plan.installCommand.split(' ');- const command = PlatformCommand.make(cmd!, ...args).pipe(- PlatformCommand.workingDirectory(plan.rootDir)- );-- const install = Effect.gen(function* () {- const exitCode = yield* runner.run(command);- if (exitCode !== 0) {- yield* Effect.fail(new Error(`Install command failed with exit code ${exitCode}`));- }+ const sessionInfo = yield* getSessionInfo({+ baseURL: ctx.data.baseURL,+ apiKey: uakApiKey,+ orgId: selected.orgId,+ projectId: selected.projectId,});- yield* ui- .withSpinner(`Installing ${plan.dependency}...`, install, {- successMessage: `Installed ${plan.dependency}.`,- errorMessage: `Failed to install ${plan.dependency}.`,- })- .pipe(- Effect.catchAll(e =>- Effect.gen(function* () {- yield* ui.log.error(`Install failed: ${e instanceof Error ? e.message : String(e)}`);- yield* ui.log.info(`You can install manually: ${plan.installCommand}`);- })- )- );- });--// ----------------------------------------------------------------------------// Skills install step — runs `npx skills add composiohq/skills`-// -----------------------------------------------------------------------------const SKILLS_INSTALL_COMMAND = 'npx skills add composiohq/skills';--/**- * Runs the Composio skills installation step.- * Uses `npx skills add composiohq/skills` to install coding-agent skills.- */-const runSkillsInstallStep = (params: {- config: InitConfig;- cwd: string;- dryRun: boolean;- yes: boolean;-}) =>- Effect.gen(function* () {- const { config, cwd, dryRun, yes } = params;- if (!config.installSkills) return;+ let projectApiKey = sessionInfo.api_key?.api_key ?? sessionInfo.api_key?.key ?? null;+ if (!projectApiKey && !hasProjectApiKey) {+ const dateSuffix = new Date().toISOString().slice(0, 10);+ projectApiKey = yield* createProjectApiKey({+ baseURL: ctx.data.baseURL,+ apiKey: uakApiKey,+ orgId: selected.orgId,+ projectId: selected.projectId,+ name: `composio-cli-${dateSuffix}`,+ });+ }- const ui = yield* TerminalUI;- const runner = yield* CommandRunner;+ const sessionUserId = sessionInfo.org_member.user_id ?? sessionInfo.org_member.id;+ const composioTestUserId = `pg-test-${sessionUserId}`;+ const composioDir = path.join(cwd, constants.PROJECT_COMPOSIO_DIR);- if (dryRun) {- yield* ui.note(SKILLS_INSTALL_COMMAND, 'Skills Install Command');- return;+ let nextEnvContent = existingEnvContent;+ if (!hasProjectApiKey && projectApiKey) {+ nextEnvContent = upsertEnvVar(nextEnvContent, 'COMPOSIO_API_KEY', projectApiKey);}-- const shouldInstall =- yes || (yield* ui.confirm(`Run: ${SKILLS_INSTALL_COMMAND}?`, { defaultValue: true }));- if (!shouldInstall) {- yield* ui.log.warn('Skills installation cancelled.');- return;+ if (!hasTestUserId) {+ nextEnvContent = upsertEnvVar(nextEnvContent, 'COMPOSIO_TEST_USER_ID', composioTestUserId);}- const [cmd, ...args] = SKILLS_INSTALL_COMMAND.split(' ');- const command = PlatformCommand.make(cmd!, ...args).pipe(- PlatformCommand.workingDirectory(cwd)- );+ if (nextEnvContent !== existingEnvContent) {+ yield* fs.writeFileString(envPath, nextEnvContent);+ }+ yield* writeProjectConfig(composioDir, {+ ...selected,+ testUserId: Option.some(composioTestUserId),+ });+ if (nextEnvContent !== existingEnvContent) {+ yield* ui.log.step(+ envExists+ ? 'Updated .env.local with Composio credentials'+ : 'Created .env.local with Composio credentials'+ );+ }+ });- const install = Effect.gen(function* () {- const exitCode = yield* runner.run(command);- if (exitCode !== 0) {- yield* Effect.fail(new Error(`Skills install command failed with exit code ${exitCode}`));+const logEnvCreationHttpError =+ (ui: TerminalUI) =>+ (e: { status?: number; details?: { message: string; suggestedFix: string }; cause?: unknown }) =>+ Effect.gen(function* () {+ yield* ui.log.warn('Could not create .env.local from session info.');+ if (e.status) {+ yield* ui.log.error(`HTTP ${e.status}`);+ }+ if (e.details) {+ yield* ui.log.error(e.details.message);+ yield* ui.log.step(e.details.suggestedFix);+ } else if (e.cause) {+ yield* ui.log.error(String(e.cause));}});- yield* ui- .withSpinner('Installing Composio skills...', install, {- successMessage: 'Installed Composio skills.',- errorMessage: 'Failed to install Composio skills.',- })- .pipe(- Effect.catchAll(e =>- Effect.gen(function* () {- yield* ui.log.error(- `Skills install failed: ${e instanceof Error ? e.message : String(e)}`- );- yield* ui.log.info(`You can install manually: ${SKILLS_INSTALL_COMMAND}`);- })- )- );+const logEnvCreationDecodingError = (ui: TerminalUI) => (e: { cause?: unknown }) =>+ Effect.gen(function* () {+ yield* ui.log.warn('Could not decode API key response; skipping .env.local creation.');+ if (e.cause) {+ yield* ui.log.error(String(e.cause));+ }});-// ----------------------------------------------------------------------------// Structured output helper-// ---------------------------------------------------------------------------+const selectDefaultProject = (params: {+ projects: ReadonlyArray<OrgProject>;+ defaultOrgId: string;+ defaultProjectId: string;+}): OrgProject | undefined => {+ const { projects, defaultOrgId, defaultProjectId } = params;+ const exactMatch = projects.find(p => p.org_id === defaultOrgId && p.id === defaultProjectId);+ if (exactMatch) return exactMatch;-const makeOutputJson = (selected: ProjectKeys, config: InitConfig, composioDir: string) =>- JSON.stringify({- org_id: selected.orgId,- project_id: selected.projectId,- usage_mode: config.usageMode,- framework: config.framework ?? null,- install_skills: config.installSkills,- detected_language: config.detectedEnv?.language ?? null,- package_manager: config.detectedEnv?.packageManager ?? null,- install_command: config.installPlan?.installCommand ?? null,- path: composioDir,- });+ const sameOrgFirst = projects.find(p => p.org_id === defaultOrgId);+ if (sameOrgFirst) return sameOrgFirst;++ return projects[0];+};// ---------------------------------------------------------------------------// Command@@ -527,8 +220,7 @@ const makeOutputJson = (selected: ProjectKeys, config: InitConfig, composioDir:/*** CLI command to initialize a Composio project in the current directory.*- * Creates `<cwd>/.composio/project.json` with org_id and project_id,- * plus `<cwd>/.composio/config.json` with usage mode, framework, and skill preferences.+ * Creates `<cwd>/.composio/project.json` with org_id and project_id.** Supports two modes:* 1. Interactive: Fetches projects from the API and prompts for selection@@ -546,15 +238,11 @@ export const initCmd = CliCommand.make(orgId: orgIdOpt,projectId: projectIdOpt,noBrowser: noBrowserOpt,- dryRun: dryRunOpt,- force: forceOpt,yes: yesOpt,- noSkills: noSkillsOpt,},- ({ orgId, projectId, noBrowser, dryRun, force, yes, noSkills }) =>+ ({ orgId, projectId, noBrowser, yes }) =>Effect.gen(function* () {const ui = yield* TerminalUI;- const ctx = yield* ComposioUserContext;const proc = yield* NodeProcess;yield* ui.intro('composio init');@@ -569,20 +257,32 @@ export const initCmd = CliCommand.make(projectName: Option.none(),orgName: Option.none(),email: Option.none(),+ testUserId: Option.none(),};- const config = yield* runInitWizard(proc.cwd, { noSkills });- yield* writeProjectConfig(composioDir, selected, config);- yield* runInstallStep({ config, cwd: proc.cwd, dryRun, force, yes });- yield* runSkillsInstallStep({ config, cwd: proc.cwd, dryRun, yes });+ yield* writeProjectConfig(composioDir, selected);+ yield* ensureProjectApiKeyInEnv({ cwd: proc.cwd, selected }).pipe(+ Effect.catchTag('services/HttpServerError', e =>+ Effect.gen(function* () {+ yield* Effect.logDebug('Failed to resolve project API key from session/info:', e);+ yield* logEnvCreationHttpError(ui)(e);+ })+ ),+ Effect.catchTag('services/HttpDecodingError', e =>+ Effect.gen(function* () {+ yield* Effect.logDebug('Failed to decode API key response:', e);+ yield* logEnvCreationDecodingError(ui)(e);+ })+ )+ );yield* ui.log.success(`Project initialized in ${composioDir}/`);- yield* ui.output(makeOutputJson(selected, config, composioDir));+ yield* ui.output(makeOutputJson(selected, composioDir));yield* ui.outro('');return;}- yield* initInteractiveFlow({ composioDir, noBrowser, dryRun, force, yes, noSkills });+ yield* initInteractiveFlow({ composioDir, noBrowser, yes });})).pipe(CliCommand.withDescription('Initialize a Composio project in the current directory.'));@@ -590,33 +290,27 @@ export const initCmd = CliCommand.make(* Interactive init flow — handles login, project selection, wizard, install.* Extracted to keep the main command handler under the line limit.*/-const initInteractiveFlow = (params: {- composioDir: string;- noBrowser: boolean;- dryRun: boolean;- force: boolean;- yes: boolean;- noSkills: boolean;-}) =>+const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean; yes: boolean }) =>Effect.gen(function* () {- const { composioDir, noBrowser, dryRun, force, yes, noSkills } = params;+ const { composioDir, noBrowser, yes } = params;const ui = yield* TerminalUI;const ctx = yield* ComposioUserContext;const proc = yield* NodeProcess;- // 1. Ensure user is logged in- if (!ctx.isLoggedIn()) {+ // 1. Ensure global user API key exists (ignore local/project keys).+ let globalApiKey = yield* getGlobalUserApiKey();+ if (!globalApiKey) {yield* ui.log.step('No credentials found. Logging in...');yield* browserLogin({ scope: 'project', noBrowser });+ globalApiKey = yield* getGlobalUserApiKey();}// 2. Fetch projects- const apiKey = Option.getOrUndefined(ctx.data.apiKey);const orgIdValue = Option.getOrUndefined(ctx.data.orgId);const projectIdValue = Option.getOrUndefined(ctx.data.projectId);- if (!apiKey || !orgIdValue || !projectIdValue) {+ if (!globalApiKey || !orgIdValue || !projectIdValue) {yield* ui.log.warn(- 'No API key, org ID, or project ID found. Please try `composio login` first.'+ 'No global API key, org ID, or project ID found. Please try `composio login` first.');yield* ui.outro('');return;@@ -624,7 +318,7 @@ const initInteractiveFlow = (params: {const orgProjects = yield* listOrgProjects({baseURL: ctx.data.baseURL,- apiKey,+ apiKey: globalApiKey,orgId: orgIdValue,projectId: projectIdValue,}).pipe(@@ -668,11 +362,16 @@ const initInteractiveFlow = (params: {projectName: Option.some(p.name),orgName: Option.none(),email: Option.some(p.email),+ testUserId: Option.none(),});const selectedProject: OrgProject =- orgProjects.data.length === 1- ? orgProjects.data[0]+ yes || orgProjects.data.length === 1+ ? (selectDefaultProject({+ projects: orgProjects.data,+ defaultOrgId: orgIdValue,+ defaultProjectId: projectIdValue,+ }) ?? orgProjects.data[0]): yield* ui.select<OrgProject>('Select a project:',orgProjects.data.map(p => ({ value: p, label: p.name, hint: p.id }))@@ -681,13 +380,24 @@ const initInteractiveFlow = (params: {const selected = orgProjectToKeys(selectedProject);yield* ui.log.step(`Using project "${selectedProject.name}"`);- // 4. Run wizard + write config + install- const config = yield* runInitWizard(proc.cwd, { noSkills });- yield* writeProjectConfig(composioDir, selected, config);- yield* runInstallStep({ config, cwd: proc.cwd, dryRun, force, yes });- yield* runSkillsInstallStep({ config, cwd: proc.cwd, dryRun, yes });+ // 4. Write project config+ yield* writeProjectConfig(composioDir, selected);+ yield* ensureProjectApiKeyInEnv({ cwd: proc.cwd, selected }).pipe(+ Effect.catchTag('services/HttpServerError', e =>+ Effect.gen(function* () {+ yield* Effect.logDebug('Failed to resolve project API key from session/info:', e);+ yield* logEnvCreationHttpError(ui)(e);+ })+ ),+ Effect.catchTag('services/HttpDecodingError', e =>+ Effect.gen(function* () {+ yield* Effect.logDebug('Failed to decode API key response:', e);+ yield* logEnvCreationDecodingError(ui)(e);+ })+ )+ );yield* ui.log.success(`Project initialized in ${composioDir}/`);- yield* ui.output(makeOutputJson(selected, config, composioDir));+ yield* ui.output(makeOutputJson(selected, composioDir));yield* ui.outro('');});diff --git a/ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts b/ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.tsindex 755ddc4f1..c465a9e0b 100644--- a/ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts+++ b/ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts@@ -17,6 +17,12 @@ const userId = Options.text('user-id').pipe(Options.withDescription('User ID for connection status (default: "default")'));+const allDetails = Options.boolean('all').pipe(+ Options.withAlias('a'),+ Options.withDefault(false),+ Options.withDescription('Show all available toolkit details, including auth config fields')+);+/*** View details of a specific toolkit including connection status.*@@ -26,85 +32,98 @@ const userId = Options.text('user-id').pipe(* composio toolkits info "github" --user-id "alice"* ```*/-export const toolkitsCmd$Info = Command.make('info', { slug, userId }, ({ slug, userId }) =>- Effect.gen(function* () {- if (!(yield* requireAuth)) return;-- const ui = yield* TerminalUI;-- // Missing slug guard- if (Option.isNone(slug)) {- yield* ui.log.warn('Missing required argument: <slug>');- yield* ui.log.step('Try specifying a toolkit slug, e.g.:\n> composio toolkits info "gmail"');- return;- }-- const slugValue = slug.value;-- const resultOpt = yield* ui- .withSpinner(- `Fetching toolkit "${slugValue}"...`,- Effect.gen(function* () {- const { client, sessionId } = yield* resolveToolRouterSession(userId);- return yield* Effect.tryPromise(() =>- client.toolRouter.session.toolkits(sessionId, {- toolkits: [slugValue],- })- );- })- )- .pipe(- Effect.asSome,- Effect.catchAll(error =>+export const toolkitsCmd$Info = Command.make(+ 'info',+ { slug, userId, allDetails },+ ({ slug, userId, allDetails }) =>+ Effect.gen(function* () {+ if (!(yield* requireAuth)) return;++ const ui = yield* TerminalUI;++ // Missing slug guard+ if (Option.isNone(slug)) {+ yield* ui.log.warn('Missing required argument: <slug>');+ yield* ui.log.step(+ 'Try specifying a toolkit slug, e.g.:\n> composio toolkits info "gmail"'+ );+ return;+ }++ const slugValue = slug.value;+ const repo = yield* ComposioToolkitsRepository;++ const resultOpt = yield* ui+ .withSpinner(+ `Fetching toolkit "${slugValue}"...`,Effect.gen(function* () {- const message = extractMessage(error) ?? `Failed to fetch toolkit "${slugValue}".`;- yield* ui.log.error(message);- yield* Effect.logDebug('Toolkit info error:', error);- yield* ui.log.step('Browse available toolkits:\n> composio toolkits list');- return Option.none();+ const [{ client, sessionId }, detailedToolkitOpt] = yield* Effect.all(+ [+ resolveToolRouterSession(userId),+ repo.getToolkitDetailed(slugValue).pipe(Effect.option),+ ],+ { concurrency: 'unbounded' }+ );+ const sessionToolkits = yield* Effect.tryPromise(() =>+ client.toolRouter.session.toolkits(sessionId, { toolkits: [slugValue] })+ );+ return { sessionToolkits, detailedToolkitOpt };}))- );+ .pipe(+ Effect.asSome,+ Effect.catchAll(error =>+ Effect.gen(function* () {+ const message = extractMessage(error) ?? `Failed to fetch toolkit "${slugValue}".`;+ yield* ui.log.error(message);+ yield* Effect.logDebug('Toolkit info error:', error);+ yield* ui.log.step('Browse available toolkits:\n> composio toolkits list');+ return Option.none();+ })+ )+ );- if (Option.isNone(resultOpt)) {- return;- }+ if (Option.isNone(resultOpt)) {+ return;+ }- const result = resultOpt.value;- const toolkit = result.items[0];+ const result = resultOpt.value;+ const toolkit = result.sessionToolkits.items[0];+ const detailedToolkit = Option.getOrUndefined(result.detailedToolkitOpt);- if (!toolkit) {- yield* ui.log.warn(`Toolkit "${slugValue}" not found.`);+ if (!toolkit) {+ yield* ui.log.warn(`Toolkit "${slugValue}" not found.`);- // "Did you mean?" suggestions via legacy search- const repo = yield* ComposioToolkitsRepository;- const suggestions = yield* repo.searchToolkits({ search: slugValue, limit: 3 }).pipe(- Effect.map(r =>- r.items.map(s => ({- label: `${s.slug} — ${s.meta.description}`,- command: `> composio toolkits info "${s.slug}"`,- }))- ),- Effect.catchAll(() => Effect.succeed([] as { label: string; command: string }[]))- );+ // "Did you mean?" suggestions via legacy search+ const suggestions = yield* repo.searchToolkits({ search: slugValue, limit: 3 }).pipe(+ Effect.map(r =>+ r.items.map(s => ({+ label: `${s.slug} — ${s.meta.description}`,+ command: `> composio toolkits info "${s.slug}"`,+ }))+ ),+ Effect.catchAll(() => Effect.succeed([] as { label: string; command: string }[]))+ );- const [first] = suggestions;- if (first) {- const lines = suggestions.map(s => ` ${s.label}`).join('\n');- yield* ui.log.step(`Did you mean?\n${lines}\n\n${first.command}`);- } else {- yield* ui.log.step('Browse available toolkits:\n> composio toolkits list');+ const [first] = suggestions;+ if (first) {+ const lines = suggestions.map(s => ` ${s.label}`).join('\n');+ yield* ui.log.step(`Did you mean?\n${lines}\n\n${first.command}`);+ } else {+ yield* ui.log.step('Browse available toolkits:\n> composio toolkits list');+ }+ return;}- return;- }- yield* ui.note(formatToolkitInfo(toolkit), `Toolkit: ${toolkit.name}`);+ yield* ui.log.message(+ `Toolkit: ${toolkit.name}\n\n${formatToolkitInfo(toolkit, detailedToolkit, allDetails)}`+ );- // Next step hint- yield* ui.log.step(- `To list tools in this toolkit:\n> composio tools list --toolkits "${toolkit.slug}"`- );+ // Next step hint+ yield* ui.log.step(+ `To list tools in this toolkit:\n> composio tools list --toolkits "${toolkit.slug}"`+ );- yield* ui.output(formatToolkitInfoJson(toolkit));- })+ yield* ui.output(formatToolkitInfoJson(toolkit, detailedToolkit, allDetails));+ })).pipe(Command.withDescription('View details of a specific toolkit.'));diff --git a/ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts b/ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.tsindex 6b82382f2..99742dd4e 100644--- a/ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts+++ b/ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts@@ -3,8 +3,15 @@ import { Effect, Option } from 'effect';import { TerminalUI } from 'src/services/terminal-ui';import { requireAuth } from 'src/effects/require-auth';import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';+import { ComposioToolkitsRepository } from 'src/services/composio-clients';+import { ProjectContext } from 'src/services/project-context';import { clampLimit } from 'src/ui/clamp-limit';-import { formatToolkitsTable, formatToolkitsJson } from '../format';+import {+ formatLegacyToolkitsJson,+ formatLegacyToolkitsTable,+ formatToolkitsJson,+ formatToolkitsTable,+} from '../format';const query = Options.text('query').pipe(Options.withDescription('Text search by name, slug, or description'),@@ -22,8 +29,8 @@ const connected = Options.boolean('connected').pipe();const userId = Options.text('user-id').pipe(- Options.withDefault('default'),- Options.withDescription('User ID for connection status (default: "default")')+ Options.optional,+ Options.withDescription('User ID for connection status (defaults to project test_user_id)'));/**@@ -45,36 +52,81 @@ export const toolkitsCmd$List = Command.make(if (!(yield* requireAuth)) return;const ui = yield* TerminalUI;+ const repo = yield* ComposioToolkitsRepository;+ const projectContext = yield* ProjectContext;const clampedLimit = clampLimit(limit);+ const resolvedProjectContext = yield* projectContext.resolve;+ const testUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);+ const resolvedUserId = Option.orElse(userId, () => testUserId);+ const usingDefaultTestUserId = Option.isNone(userId) && Option.isSome(testUserId);++ if (usingDefaultTestUserId && Option.isSome(testUserId)) {+ yield* ui.log.info(`Showing connection status for user id "${testUserId.value}"`);+ yield* ui.log.message('To show status for a specific user, use `--user-id`.');+ }++ if (Option.isSome(resolvedUserId)) {+ const result = yield* ui.withSpinner(+ 'Fetching toolkits...',+ Effect.gen(function* () {+ const { client, sessionId } = yield* resolveToolRouterSession(resolvedUserId.value);+ return yield* Effect.tryPromise(() =>+ client.toolRouter.session.toolkits(sessionId, {+ search: Option.getOrUndefined(query),+ limit: clampedLimit,+ is_connected: Option.getOrUndefined(connected),+ })+ );+ })+ );++ const { items } = result;+ if (items.length === 0) {+ yield* ui.log.warn('No toolkits found. Try broadening your search.');+ yield* ui.output('[]');+ return;+ }++ const showing = items.length;+ const total = result.total_items;+ yield* ui.log.info(+ `Listing ${showing} of ${total} toolkits\n\n${formatToolkitsTable(items)}`+ );++ const firstSlug = items[0]?.slug;+ if (firstSlug) {+ yield* ui.log.step(+ `To view details of a toolkit:\n> composio toolkits info "${firstSlug}"`+ );+ }+ yield* ui.output(formatToolkitsJson(items));+ return;+ }++ if (Option.isSome(connected)) {+ yield* ui.log.warn(+ '`--connected` requires a user id. Use `--user-id` or run `composio init`.'+ );+ }const result = yield* ui.withSpinner('Fetching toolkits...',- Effect.gen(function* () {- const { client, sessionId } = yield* resolveToolRouterSession(userId);- return yield* Effect.tryPromise(() =>- client.toolRouter.session.toolkits(sessionId, {- search: Option.getOrUndefined(query),- limit: clampedLimit,- is_connected: Option.getOrUndefined(connected),- })- );+ repo.searchToolkits({+ search: Option.getOrUndefined(query),+ limit: clampedLimit,}));-- const { items } = result;-+ const items = result.items;if (items.length === 0) {yield* ui.log.warn('No toolkits found. Try broadening your search.');yield* ui.output('[]');return;}-const showing = items.length;const total = result.total_items;-yield* ui.log.info(- `Listing ${showing} of ${total} toolkits\n\n${formatToolkitsTable(items)}`+ `Listing ${showing} of ${total} toolkits\n\n${formatLegacyToolkitsTable(items)}`);// Next step hint@@ -85,6 +137,6 @@ export const toolkitsCmd$List = Command.make();}- yield* ui.output(formatToolkitsJson(items));+ yield* ui.output(formatLegacyToolkitsJson(items));})).pipe(Command.withDescription('List available toolkits with connection status.'));diff --git a/ts/packages/cli/src/commands/toolkits/format.ts b/ts/packages/cli/src/commands/toolkits/format.tsindex 14ce807f5..5e8751800 100644--- a/ts/packages/cli/src/commands/toolkits/format.ts+++ b/ts/packages/cli/src/commands/toolkits/format.ts@@ -1,10 +1,26 @@-import type { Toolkit } from 'src/models/toolkits';+import type { Toolkit, ToolkitDetailed } from 'src/models/toolkits';import type { SessionToolkitsResponse } from '@composio/client/resources/tool-router';import { bold, gray, green, dim } from 'src/ui/colors';import { truncate } from 'src/ui/truncate';type SessionToolkitItem = SessionToolkitsResponse.Item;+const formatAuthConfigField = (field: {+ name: string;+ displayName: string;+ description: string;+ type: string;+ required: boolean;+ default: string | null;+}): string =>+ [+ ` - ${field.name} (${field.type})`,+ ` display: ${field.displayName}`,+ ` required: ${field.required ? 'yes' : 'no'}`,+ ` default: ${field.default ?? '-'}`,+ ` description: ${field.description || '-'}`,+ ].join('\n');+// ---------- Tool Router format functions ----------/**@@ -69,12 +85,79 @@ export function formatToolkitsJson(toolkits: ReadonlyArray<SessionToolkitItem>):/*** Format a single session toolkit for detailed interactive display.*/-export function formatToolkitInfo(toolkit: SessionToolkitItem): string {+export function formatToolkitInfo(+ toolkit: SessionToolkitItem,+ detailed?: ToolkitDetailed,+ showAllDetails = false+): string {const lines: string[] = [];+ const detailedMeta = detailed?.meta;+ const availableVersions = detailedMeta?.available_versions ?? [];+ const latestVersion = availableVersions.at(-1);+ const authModes = detailed?.auth_config_details.map(detail => detail.mode) ?? [];lines.push(`${bold('Name:')} ${toolkit.name}`);lines.push(`${bold('Slug:')} ${toolkit.slug}`);- lines.push(`${bold('Description:')} ${toolkit.meta.description || '(none)'}`);+ lines.push(+ `${bold('Description:')} ${detailedMeta?.description || toolkit.meta.description || '(none)'}`+ );+ lines.push(`${bold('Latest Version:')} ${latestVersion ?? '-'}`);+ lines.push(`${bold('Tools Count:')} ${detailedMeta?.tools_count ?? '-'}`);+ lines.push(`${bold('Triggers Count:')} ${detailedMeta?.triggers_count ?? '-'}`);+ if (authModes.length > 0) {+ lines.push(`${bold('Auth Modes:')} ${authModes.join(', ')}`);+ }+ if (showAllDetails && detailed) {+ lines.push(`${bold('No Auth:')} ${detailed.no_auth ? 'Yes' : 'No'}`);+ lines.push(`${bold('Is Local Toolkit:')} ${detailed.is_local_toolkit ? 'Yes' : 'No'}`);+ lines.push(`${bold('Created At:')} ${String(detailed.meta.created_at)}`);+ lines.push(`${bold('Updated At:')} ${String(detailed.meta.updated_at)}`);+ lines.push(+ `${bold('Composio Managed Auth Schemes:')} ${+ detailed.composio_managed_auth_schemes.length > 0+ ? detailed.composio_managed_auth_schemes.join(', ')+ : '-'+ }`+ );+ lines.push('');+ lines.push(bold('Auth Config Details:'));+ if (detailed.auth_config_details.length === 0) {+ lines.push(' - none');+ } else {+ for (const detail of detailed.auth_config_details) {+ lines.push(` - ${detail.mode} (${detail.name})`);+ const creationRequired = detail.fields.auth_config_creation.required;+ const creationOptional = detail.fields.auth_config_creation.optional;+ const initiationRequired = detail.fields.connected_account_initiation.required;+ const initiationOptional = detail.fields.connected_account_initiation.optional;++ lines.push(' auth_config_creation.required:');+ lines.push(+ creationRequired.length > 0+ ? creationRequired.map(formatAuthConfigField).join('\n')+ : ' - none'+ );+ lines.push(' auth_config_creation.optional:');+ lines.push(+ creationOptional.length > 0+ ? creationOptional.map(formatAuthConfigField).join('\n')+ : ' - none'+ );+ lines.push(' connected_account_initiation.required:');+ lines.push(+ initiationRequired.length > 0+ ? initiationRequired.map(formatAuthConfigField).join('\n')+ : ' - none'+ );+ lines.push(' connected_account_initiation.optional:');+ lines.push(+ initiationOptional.length > 0+ ? initiationOptional.map(formatAuthConfigField).join('\n')+ : ' - none'+ );+ }+ }+ }if (toolkit.is_no_auth) {lines.push(`${bold('Auth:')} No authentication required`);@@ -109,14 +192,23 @@ export function formatToolkitInfo(toolkit: SessionToolkitItem): string {* Format a single session toolkit as JSON for piped output.* Produces a stable, curated schema — does not leak the raw API response.*/-export function formatToolkitInfoJson(toolkit: SessionToolkitItem): string {+export function formatToolkitInfoJson(+ toolkit: SessionToolkitItem,+ detailed?: ToolkitDetailed,+ showAllDetails = false+): string {+ const availableVersions = detailed?.meta.available_versions ?? [];+ const latestVersion = availableVersions.at(-1) ?? null;return JSON.stringify({name: toolkit.name,slug: toolkit.slug,meta: {- description: toolkit.meta.description,+ description: detailed?.meta.description ?? toolkit.meta.description,logo: toolkit.meta.logo,+ latest_version: latestVersion,+ tools_count: detailed?.meta.tools_count ?? null,+ triggers_count: detailed?.meta.triggers_count ?? null,},is_no_auth: toolkit.is_no_auth,enabled: toolkit.enabled,@@ -129,6 +221,18 @@ export function formatToolkitInfoJson(toolkit: SessionToolkitItem): string {}: null,composio_managed_auth_schemes: toolkit.composio_managed_auth_schemes,+ auth_modes: detailed?.auth_config_details.map(detail => detail.mode) ?? [],+ ...(showAllDetails && detailed+ ? {+ detailed: {+ is_local_toolkit: detailed.is_local_toolkit,+ no_auth: detailed.no_auth,+ created_at: String(detailed.meta.created_at),+ updated_at: String(detailed.meta.updated_at),+ auth_config_details: detailed.auth_config_details,+ },+ }+ : {}),},null,2diff --git a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.tsindex ebcd238b1..371b7f5f6 100644--- a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts+++ b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts@@ -12,6 +12,7 @@ import {ToolsExecutor,} from 'src/services/tools-executor';import type { ToolExecuteParams } from 'src/services/tools-executor';+import { ProjectContext } from 'src/services/project-context';import {extractApiErrorDetails,extractMessage,@@ -30,8 +31,8 @@ const data = Options.text('data').pipe();const userId = Options.text('user-id').pipe(- Options.withDefault('default'),- Options.withDescription('User ID to execute the tool for (default: "default")')+ Options.optional,+ Options.withDescription('User ID to execute the tool for (falls back to project test_user_id)'));const resolveInput = (input: Option.Option<string>) =>@@ -243,12 +244,27 @@ export const toolsCmd$Execute = Command.make(const ui = yield* TerminalUI;const executor = yield* ToolsExecutor;+ const projectContext = yield* ProjectContext;+ const resolvedProjectContext = yield* projectContext.resolve;+ const testUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);+ const resolvedUserId = Option.match(userId, {+ onSome: value => Option.some(value),+ onNone: () => testUserId,+ });+ if (Option.isNone(resolvedUserId)) {+ return yield* Effect.fail(+ new Error('Missing user id. Provide --user-id or run composio init to set test_user_id.')+ );+ }+ if (Option.isNone(userId) && Option.isSome(testUserId)) {+ yield* ui.log.warn(`Using test user id "${testUserId.value}"`);+ }const input = yield* resolveInput(data);const args = yield* parseArguments(input);const params: ToolExecuteParams = {- userId,+ userId: resolvedUserId.value,arguments: args,};@@ -261,7 +277,7 @@ export const toolsCmd$Execute = Command.make(yield* spinner.error();const summary = yield* handleExecutionError(ui, resultEither.left, {toolSlug: slug,- userId,+ userId: resolvedUserId.value,});yield* ui.output(JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)@@ -280,7 +296,7 @@ export const toolsCmd$Execute = Command.make(const summary = yield* handleExecutionError(ui, result.error ?? result, {toolSlug: slug,- userId,+ userId: resolvedUserId.value,});yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));return yield* Effect.fail(new ToolExecutionError(summary.error));@@ -291,6 +307,7 @@ export const toolsCmd$Execute = Command.make(? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`: '';yield* spinner.stop(`Execution successful${logId}`);+ yield* ui.log.message(`Response\n${JSON.stringify(result, ciRedactReplacer, 2)}`);yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));}));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.tsindex 0c1f5a602..8fac9396c 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@@ -1,10 +1,11 @@import { Args, Command, Options } from '@effect/cli';import { Effect, Option } from 'effect';-import { ComposioToolkitsRepository } from 'src/services/composio-clients';import { TerminalUI } from 'src/services/terminal-ui';import { requireAuth } from 'src/effects/require-auth';import { clampLimit } from 'src/ui/clamp-limit';-import { formatToolsTable, formatToolsJson } from '../format';+import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';+import { formatToolsTable } from '../format';+import type { Tool } from 'src/models/tools';const query = Args.text({ name: 'query' }).pipe(Args.withDescription('Search query (e.g. "send emails")')@@ -38,38 +39,100 @@ export const toolsCmd$Search = Command.make(if (!(yield* requireAuth)) return;const ui = yield* TerminalUI;- const repo = yield* ComposioToolkitsRepository;-const clampedLimit = clampLimit(limit);+ const toolkitFilter = Option.getOrUndefined(toolkits);+ const toolkitList =+ toolkitFilter && toolkitFilter.trim().length > 0+ ? toolkitFilter+ .split(',')+ .map(s => s.trim().toLowerCase())+ .filter(Boolean)+ : undefined;- const result = yield* ui.withSpinner(+ const searchResponse = yield* ui.withSpinner(`Searching tools for "${query}"...`,- repo.searchTools({- search: query,- toolkit_slug: Option.getOrUndefined(toolkits),- limit: clampedLimit,+ Effect.gen(function* () {+ const { client, sessionId } = yield* resolveToolRouterSession('default-cli', {+ toolkits: toolkitList,+ });+ return yield* Effect.tryPromise(() =>+ client.toolRouter.session.search(sessionId, {+ queries: [{ use_case: query }],+ })+ );}));- if (result.items.length === 0) {+ 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;+ }++ if (toolsList.length === 0) {yield* ui.log.warn(`No tools found matching "${query}". Try broadening your search.`);return;}- const showing = result.items.length;- const totalPages = result.total_pages;- yield* ui.log.info(- totalPages > 1- ? `Found ${showing} tools (page 1 of ${totalPages})\n\n${formatToolsTable(result.items)}`- : `Found ${showing} tools\n\n${formatToolsTable(result.items)}`+ 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')}`+ );+ }// Next step hint- const firstSlug = result.items[0]?.slug;+ const firstSlug = toolsList[0]?.slug;if (firstSlug) {- yield* ui.log.step(`To view details:\n> composio tools info "${firstSlug}"`);+ yield* ui.log.step(+ [+ 'Hints:',+ `> composio tools info "${firstSlug}"`,+ `> composio tools execute "${firstSlug}" --user-id "<user-id>" --arguments '{}'`,+ ].join('\n')+ );+ }++ if (searchResponse.error) {+ yield* ui.log.warn(searchResponse.error);}- yield* ui.output(formatToolsJson(result.items));+ // For machine-readable output (e.g. piping to jq), expose the full API payload.+ yield* ui.output(JSON.stringify(searchResponse, null, 2));})).pipe(Command.withDescription('Search tools by use case.'));diff --git a/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts b/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.tsindex 965532a32..65e0ae9e0 100644--- a/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts+++ b/ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts@@ -298,7 +298,7 @@ export const triggersCmd$Listen = Command.make('webhook-id': webhookId,'webhook-timestamp': webhookTimestamp,'webhook-signature': webhookSignature,- 'x-composio-webhook-version': webhookVersion,+ 'webhook-version': webhookVersion,},body: payloadForForwarding,});diff --git a/ts/packages/cli/src/effects/create-tool-router-session.ts b/ts/packages/cli/src/effects/create-tool-router-session.tsindex 7b8baf2c2..b3eeaa440 100644--- a/ts/packages/cli/src/effects/create-tool-router-session.ts+++ b/ts/packages/cli/src/effects/create-tool-router-session.ts@@ -5,6 +5,8 @@ import { ComposioClientSingleton } from 'src/services/composio-clients';export interface CreateToolRouterSessionOptions {/** Enable auto connection management. Default: false. */readonly manageConnections?: boolean;+ /** Restrict session to these toolkit slugs. */+ readonly toolkits?: ReadonlyArray<string>;}/**@@ -24,6 +26,10 @@ export const createToolRouterSession = (client.toolRouter.session.create({user_id: userId,manage_connections: { enable: options?.manageConnections ?? false },+ toolkits:+ options?.toolkits && options.toolkits.length > 0+ ? { enable: [...options.toolkits] }+ : undefined,})).pipe(Effect.map(session => session.session_id));diff --git a/ts/packages/cli/src/models/project-keys.ts b/ts/packages/cli/src/models/project-keys.tsindex 3ee5baeb1..74e0340e4 100644--- a/ts/packages/cli/src/models/project-keys.ts+++ b/ts/packages/cli/src/models/project-keys.ts@@ -38,6 +38,13 @@ export const ProjectKeys = Schema.Struct({email: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(Schema.fromKey('email')),++ /**+ * Optional test user identifier used by CLI/e2e flows.+ */+ testUserId: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(+ Schema.fromKey('test_user_id')+ ),}).annotations({identifier: 'ProjectKeys',description: 'Organization and project identifiers for a CLI project profile',diff --git a/ts/packages/cli/src/services/composio-clients.ts b/ts/packages/cli/src/services/composio-clients.tsindex 37434b65e..5e42f6704 100644--- a/ts/packages/cli/src/services/composio-clients.ts+++ b/ts/packages/cli/src/services/composio-clients.ts@@ -27,6 +27,7 @@ import {import { Session, RetrievedSession } from 'src/models/session';import { TriggerType, TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigger-types';import { ComposioUserContext, ComposioUserContextLive } from './user-context';+import { ProjectContext } from './project-context';import type { NoSuchElementException } from 'effect/Cause';import { renderPrettyError } from './utils/pretty-error';@@ -358,19 +359,28 @@ export const SessionInfoResponse = Schema.Struct({}),org_member: Schema.Struct({id: Schema.String,+ user_id: Schema.optional(Schema.String),email: Schema.String,name: Schema.String,role: Schema.String,}),- api_key: Schema.Struct({- name: Schema.String,- project_id: Schema.String,- id: Schema.String,- org_member_id: Schema.String,- }),+ api_key: Schema.NullOr(+ Schema.Struct({+ name: Schema.String,+ project_id: Schema.String,+ id: Schema.String,+ org_member_id: Schema.String,+ api_key: Schema.optional(Schema.String),+ key: Schema.optional(Schema.String),+ })+ ),}).annotations({ identifier: 'SessionInfoResponse' });export type SessionInfoResponse = Schema.Schema.Type<typeof SessionInfoResponse>;+const authHeaderForApiKey = (apiKey: string): Record<string, string> => ({+ 'x-user-api-key': apiKey,+});+export interface TriggerInstancesListActiveParams {user_ids?: string[];connected_account_ids?: string[];@@ -708,8 +718,8 @@ export type OrgProjectListResponse = Schema.Schema.Type<typeof OrgProjectListRes** @param params.baseURL - API base URL* @param params.apiKey - UAK (sent as `x-user-api-key`)- * @param params.orgId - Organization ID (sent as `x-composio-org-id`)- * @param params.projectId - Project ID (sent as `x-composio-project-id`)+ * @param params.orgId - Organization ID (sent as `x-org-id`)+ * @param params.projectId - Project ID (sent as `x-project-id`)* @param params.limit - Max projects to return (default 100)*/export const listOrgProjects = (params: {@@ -730,8 +740,8 @@ export const listOrgProjects = (params: {redirect: 'error',headers: {'x-user-api-key': params.apiKey,- 'x-composio-org-id': params.orgId,- 'x-composio-project-id': params.projectId,+ 'x-org-id': params.orgId,+ 'x-project-id': params.projectId,'User-Agent': '@composio/cli',Accept: 'application/json','Content-Type': 'application/json',@@ -777,7 +787,7 @@ export const getSessionInfo = (params: {method: 'GET',redirect: 'error',headers: {- 'x-api-key': params.apiKey,+ ...authHeaderForApiKey(params.apiKey),'x-org-id': params.orgId,'x-project-id': params.projectId,'User-Agent': '@composio/cli',@@ -849,6 +859,82 @@ export const getSessionInfoByUserApiKey = (params: {);});+const getApiKeyFromPayload = (payload: unknown): string | undefined => {+ const candidates = new Set<string>(['api_key', 'apiKey', 'key', 'token']);+ const keyPrefixes = ['uak_', 'ak_'];+ const queue: unknown[] = [payload];++ while (queue.length > 0) {+ const current = queue.shift();+ if (!current || typeof current !== 'object') continue;++ if (Array.isArray(current)) {+ queue.push(...current);+ continue;+ }++ const entries = Object.entries(current as Record<string, unknown>);+ for (const [key, value] of entries) {+ if (+ typeof value === 'string' &&+ candidates.has(key) &&+ keyPrefixes.some(prefix => value.startsWith(prefix))+ ) {+ return value;+ }+ if (value && typeof value === 'object') {+ queue.push(value);+ }+ }+ }++ return undefined;+};++export const createProjectApiKey = (params: {+ baseURL: string;+ apiKey: string;+ orgId: string;+ projectId: string;+ name: string;+}): Effect.Effect<string, HttpServerError | HttpDecodingError> =>+ Effect.gen(function* () {+ const response = yield* Effect.tryPromise({+ try: () =>+ fetch(`${params.baseURL}/api/v3/org/project/${params.projectId}/api_keys/create`, {+ method: 'POST',+ redirect: 'error',+ headers: {+ ...authHeaderForApiKey(params.apiKey),+ 'x-org-id': params.orgId,+ 'x-project-id': params.projectId,+ 'User-Agent': '@composio/cli',+ Accept: '*/*',+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ name: params.name }),+ }),+ catch: error => new HttpServerError({ cause: error }),+ });++ if (!response.ok) {+ return yield* handleHttpErrorResponse(response);+ }++ const { json } = yield* streamResponseWithByteCount(response);+ const createdApiKey = getApiKeyFromPayload(json);++ if (!createdApiKey) {+ return yield* Effect.fail(+ new HttpDecodingError({+ cause: 'Create API key response did not contain an API key',+ })+ );+ }++ return createdApiKey;+ });+// Utility function for calling the Composio API and decoding its response.// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst callClient = <T, S extends Schema.Schema<any, any>>(@@ -1006,6 +1092,7 @@ export class ComposioClientSingleton extends Effect.Service<ComposioClientSingleaccessors: true,effect: Effect.gen(function* () {const ctx = yield* ComposioUserContext;+ const projectContextOpt = yield* Effect.serviceOption(ProjectContext);let ref = Option.none<_RawComposioClient>();return {@@ -1017,9 +1104,26 @@ export class ComposioClientSingleton extends Effect.Service<ComposioClientSingle// Note: `api_key` is not required in every API request.const apiKey = ctx.data.apiKey.pipe(Option.getOrUndefined);const baseURL = ctx.data.baseURL;+ const resolvedProjectContext = yield* Option.match(projectContextOpt, {+ onNone: () => Effect.succeed(Option.none()),+ onSome: projectContext =>+ projectContext.resolve.pipe(Effect.catchAll(() => Effect.succeed(Option.none()))),+ });+ const defaultHeaders = Option.match(resolvedProjectContext, {+ onNone: () => undefined,+ onSome: keys =>+ ({+ 'x-org-id': keys.orgId,+ 'x-project-id': keys.projectId,+ }) satisfies Record<string, string>,+ });yield* Effect.logDebug('Creating raw Composio client...');- const client = new _RawComposioClient({ apiKey, baseURL });+ const client = new _RawComposioClient({+ apiKey,+ baseURL,+ defaultHeaders,+ });ref = Option.some(client);return client;diff --git a/ts/packages/cli/src/services/project-context.ts b/ts/packages/cli/src/services/project-context.tsindex 8ac6353d1..0956f15c9 100644--- a/ts/packages/cli/src/services/project-context.ts+++ b/ts/packages/cli/src/services/project-context.ts@@ -75,6 +75,7 @@ export class ProjectContext extends Effect.Service<ProjectContext>()('services/PprojectName: Option.none(),orgName: Option.none(),email: Option.none(),+ testUserId: Option.none(),});}@@ -105,6 +106,7 @@ export class ProjectContext extends Effect.Service<ProjectContext>()('services/PprojectName: Option.none(),orgName: Option.none(),email: Option.none(),+ testUserId: Option.none(),});}}diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.tsindex 85981ba8f..f178fc608 100644--- a/ts/packages/cli/test/__utils__/services/test-layer.ts+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts@@ -49,11 +49,13 @@ import type {SessionExecuteResponse,SessionExecuteMetaResponse,SessionLinkResponse,+ SessionSearchResponse,SessionToolkitsResponse,SessionCreateParams,SessionExecuteParams,SessionExecuteMetaParams,SessionLinkParams,+ SessionSearchParams,SessionToolkitsParams,} from '@composio/client/resources/tool-router';import { Stdin } from 'src/services/stdin';@@ -163,6 +165,8 @@ export interface TestLiveInput {) => Promise<SessionExecuteMetaResponse>;/** Override `session.link`. Receives sessionId and params. */link?: (sessionId: string, params: SessionLinkParams) => Promise<SessionLinkResponse>;+ /** Override `session.search`. Receives sessionId and params. */+ search?: (sessionId: string, params: SessionSearchParams) => Promise<SessionSearchResponse>;/** Override `session.toolkits`. Receives sessionId and optional params. */toolkits?: (sessionId: string,@@ -795,6 +799,72 @@ export const TestLayer = (input?: TestLiveInput) =>};};+ const defaultSearchHandler = async (+ _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 primaryToolSlugs = matchedTools.map(tool => tool.slug);+ const toolSchemas = Object.fromEntries(+ matchedTools.map(tool => [+ tool.slug,+ {+ tool_slug: tool.slug,+ toolkit: tool.slug.split('_')[0]?.toLowerCase() ?? '',+ description: tool.description,+ hasFullSchema: true,+ input_schema: tool.input_parameters,+ output_schema: tool.output_parameters,+ },+ ])+ );+ const toolkitConnectionStatuses = Array.from(+ new Set(+ matchedTools.map(tool => tool.slug.split('_')[0]?.toLowerCase() ?? '').filter(Boolean)+ )+ ).map(toolkitSlug => ({+ toolkit: toolkitSlug,+ description: `${toolkitSlug} toolkit`,+ has_active_connection: false,+ status_message: 'No active connection',+ }));++ return {+ success: true,+ error: null,+ results: [+ {+ index: 1,+ use_case: queryUseCase,+ primary_tool_slugs: primaryToolSlugs,+ related_tool_slugs: [],+ toolkits: toolkitConnectionStatuses.map(t => t.toolkit),+ },+ ],+ tool_schemas: toolSchemas,+ toolkit_connection_statuses: toolkitConnectionStatuses,+ 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',+ },+ };+ };+const mockComposioClient = {toolRouter: {session: {@@ -827,6 +897,7 @@ export const TestLayer = (input?: TestLiveInput) =>link_token: 'lt_test_token',redirect_url: 'https://app.composio.dev/link?token=lt_test_token',})),+ search: toolRouterOverrides?.search ?? defaultSearchHandler,toolkits: toolRouterOverrides?.toolkits ?? defaultToolkitsHandler,tools: async () => ({items: [],diff --git a/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap b/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snapindex 12dbf3275..00acbf65e 100644--- a/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap+++ b/ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap@@ -35,7 +35,7 @@ Composio CLI - A tool for managing Python and TypeScript composio.dev projects.- logout Log out from the Composio SDK.- - init [--org-id text] [--project-id text] [--no-browser] [--dry-run] [--force] [(-y, --yes)] [--no-skills] Initialize a Composio project in the current directory.+ - init [--org-id text] [--project-id text] [--no-browser] [(-y, --yes)] Initialize a Composio project in the current directory.- generate [(-o, --output-dir directory)] [--type-tools] --toolkits text... Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)@@ -59,7 +59,7 @@ Environment Variables:- toolkits list [--query text] [--limit integer] [--connected] [--user-id text] List available toolkits with connection status.- - toolkits info [--user-id text] [<slug>] View details of a specific toolkit.+ - toolkits info [--user-id text] [(-a, --all)] [<slug>] View details of a specific toolkit.- toolkits search [--limit integer] <query> Search toolkits by use case.diff --git a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.tsindex 283487a11..bc7e4627c 100644--- a/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts@@ -59,15 +59,17 @@ describe('CLI: composio connected-accounts link', () => {);layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(- '[Given] valid --auth-config with default user-id [Then] creates link',+ '[Given] valid --auth-config with explicit --user-id [Then] creates link',it => {- it.scoped('uses default user-id', () =>+ it.scoped('uses explicit user-id', () =>Effect.gen(function* () {yield* cli(['connected-accounts','link','--auth-config','ac_gmail_oauth',+ '--user-id',+ 'default','--no-browser',]);const lines = yield* MockConsole.getLines({ stripAnsi: true });diff --git a/ts/packages/cli/test/src/commands/init.cmd.test.ts b/ts/packages/cli/test/src/commands/init.cmd.test.tsindex 0b7860e59..a315d4224 100644--- a/ts/packages/cli/test/src/commands/init.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/init.cmd.test.ts@@ -1,512 +1,52 @@import path from 'node:path';import { describe, expect, layer } from '@effect/vitest';-import { vi, afterEach, beforeAll, afterAll } from 'vitest';-import { Console, Effect, Exit } from 'effect';-import { CommandExecutor, FileSystem } from '@effect/platform';+import { Effect } from 'effect';+import { FileSystem } from '@effect/platform';import { NodeProcess } from 'src/services/node-process';-import { CommandRunner } from 'src/services/command-runner';-import { TerminalUI } from 'src/services/terminal-ui';import { cli, TestLive, MockConsole } from 'test/__utils__';-// ── Helpers ──────────────────────────────────────────────────────────────────--const makeSessionInfoBody = () => ({- project: {- name: 'test-project',- id: 'proj_test_123',- org_id: 'org_test_456',- nano_id: 'pr_nano_789',- email: '[email protected]',- created_at: '2026-01-01T00:00:00.000Z',- updated_at: '2026-01-01T00:00:00.000Z',- org: { name: 'Test Org', id: 'org_test_456', plan: 'free' },- },- org_member: {- id: 'org_test_456',- email: '[email protected]',- name: 'Test User',- role: 'admin',- },- api_key: {- name: 'default',- project_id: 'proj_test_123',- id: 'ak_test',- org_member_id: 'org_test_456',- },-});--function mockFetchResponse(body: unknown, status = 200): Response {- return new Response(JSON.stringify(body), {- status,- headers: { 'Content-Type': 'application/json' },- });-}--const makeCommandRunnerSuccess = () =>- new CommandRunner({- run: () => Effect.succeed(CommandExecutor.ExitCode(0)),- });--const makeCommandRunnerFail = (exitCode = 1) =>- new CommandRunner({- run: () => Effect.succeed(CommandExecutor.ExitCode(exitCode)),- });--/**- * Creates a TerminalUI where specific `select()` calls return custom values.- * `selectOverrides` maps call index (0-based) to the option index to pick.- * Calls without overrides default to picking the first option (index 0).- */-const makeTerminalUIWithSelectOverrides = (selectOverrides: Record<number, number>): TerminalUI => {- let selectCallIndex = 0;-- return TerminalUI.of({- output: data => Console.log(data),- intro: title => Console.log(`-- ${title} --`),- outro: message => Console.log(`-- ${message} --`),- log: {- info: message => Console.log(message),- success: message => Console.log(message),- warn: message => Console.warn(message),- error: message => Console.error(message),- step: message => Console.log(message),- message: message => Console.log(message),- },- note: (message, title) => Console.log(title ? `[${title}] ${message}` : message),- select: (_message, options) => {- const idx = selectCallIndex++;- const optionIdx = selectOverrides[idx] ?? 0;- return Effect.succeed(options[optionIdx].value);- },- confirm: (_message, options) => Effect.succeed(options?.defaultValue ?? true),- withSpinner: (message, effect, options) =>- Effect.gen(function* () {- const result = yield* effect;- const successMsg =- typeof options?.successMessage === 'function'- ? options.successMessage(result)- : (options?.successMessage ?? message);- yield* Console.log(successMsg);- return result;- }),- useMakeSpinner: (message, use) =>- Effect.gen(function* () {- let stopped = false;- const handle = {- message: (_msg: string) => Effect.void,- stop: (msg?: string) =>- Effect.gen(function* () {- stopped = true;- if (msg) yield* Console.log(msg);- }),- error: (msg?: string) =>- Effect.gen(function* () {- stopped = true;- if (msg) yield* Console.error(msg);- }),- };- const exit = yield* Effect.exit(use(handle));- if (Exit.isFailure(exit) && !stopped) {- yield* Console.error(message);- }- return yield* exit;- }),- });-};--// ── Tests ────────────────────────────────────────────────────────────────────-describe('CLI: composio init', () => {- let savedUserAgent: string | undefined;-- beforeAll(() => {- savedUserAgent = process.env.npm_config_user_agent;- delete process.env.npm_config_user_agent;- });-- afterAll(() => {- if (savedUserAgent !== undefined) {- process.env.npm_config_user_agent = savedUserAgent;- } else {- delete process.env.npm_config_user_agent;- }- });-- afterEach(() => {- vi.restoreAllMocks();- });-- describe('[Given] --org-id + --project-id flags with TS project', () => {- layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(- it => {- it.scoped('[Then] detects TS project and installs dependency', () =>- Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(- mockFetchResponse(makeSessionInfoBody())- );-- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];- yield* cli(args);-- const lines = yield* MockConsole.getLines();- const output = lines.join('\n');-- expect(output).toContain('typescript');- expect(output).toContain('Installed @composio/core');- })- );- }- );- });-- describe('[Given] --org-id + --project-id flags with Python project', () => {- layer(TestLive({ fixture: 'python-project', commandRunner: makeCommandRunnerSuccess() }))(- it => {- it.scoped('[Then] detects Python project and shows correct install command', () =>- Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(- mockFetchResponse(makeSessionInfoBody())- );-- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];- yield* cli(args);-- const lines = yield* MockConsole.getLines();- const output = lines.join('\n');-- expect(output).toContain('python');- expect(output).toContain('pip install composio');- expect(output).toContain('Dry run complete.');- })- );- }- );- });-- describe('[Given] --dry-run flag with TS project', () => {+ describe('[Given] --org-id + --project-id flags', () => {layer(TestLive({ fixture: 'typescript-project' }))(it => {- it.scoped('[Then] prints install command without executing', () =>+ it.scoped('[Then] it initializes project config and prints machine output', () =>Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));-- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];- yield* cli(args);-- const lines = yield* MockConsole.getLines();- const output = lines.join('\n');-- expect(output).toContain('npm install -S @composio/core');- expect(output).toContain('Dry run complete.');- expect(output).not.toContain('Installed @composio/core');- })- );- });- });-- describe('[Given] @composio/core already in node_modules', () => {- layer(- TestLive({- fixture: 'typescript-project-with-composio-core',- commandRunner: makeCommandRunnerSuccess(),- })- )(it => {- it.scoped('[Then] skips install', () =>- Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));-- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1'];- yield* cli(args);-- const lines = yield* MockConsole.getLines();- const output = lines.join('\n');-- expect(output).toContain('Dependency already installed');- expect(output).not.toContain('Installed @composio/core');- })- );- });- });-- describe('[Given] --force flag with dependency installed', () => {- layer(- TestLive({- fixture: 'typescript-project-with-composio-core',- commandRunner: makeCommandRunnerSuccess(),- })- )(it => {- it.scoped('[Then] reinstalls', () =>- Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));-- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--force', '--yes'];- yield* cli(args);-- const lines = yield* MockConsole.getLines();- const output = lines.join('\n');-- expect(output).toContain('Reinstalling due to --force');- expect(output).toContain('Installed @composio/core');- })- );- });- });-- describe('[Given] install command fails', () => {- layer(- TestLive({- fixture: 'typescript-project',- commandRunner: makeCommandRunnerFail(1),- })- )(it => {- it.scoped('[Then] shows error and suggests manual install', () =>- Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));+ const fs = yield* FileSystem.FileSystem;+ const proc = yield* NodeProcess;- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];- yield* cli(args);+ yield* cli(['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes']);- const lines = yield* MockConsole.getLines();+ const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');- expect(output).toContain('Install failed');- expect(output).toContain('install manually');- })- );- });- });-- describe('[Given] pnpm monorepo fixture', () => {- layer(- TestLive({- fixture: 'typescript-pnpm-monorepo',- commandRunner: makeCommandRunnerSuccess(),- })- )(it => {- it.scoped('[Then] detects pnpm and uses pnpm add', () =>- Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));-- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];- yield* cli(args);+ expect(output).toContain('-- composio init --');+ expect(output).toContain('Project initialized in');+ expect(output).toContain('"org_id":"org1"');+ expect(output).toContain('"project_id":"proj1"');- const lines = yield* MockConsole.getLines();- const output = lines.join('\n');+ const projectConfigPath = path.join(proc.cwd, '.composio', 'project.json');+ const exists = yield* fs.exists(projectConfigPath);+ expect(exists).toBe(true);- expect(output).toContain('pnpm');- expect(output).toContain('pnpm add @composio/core');+ const projectConfigRaw = yield* fs.readFileString(projectConfigPath, 'utf8');+ const projectConfig = JSON.parse(projectConfigRaw) as Record<string, unknown>;+ expect(projectConfig.org_id).toBe('org1');+ expect(projectConfig.project_id).toBe('proj1');}));});});- // ── Skills installation tests ──────────────────────────────────────────────-- describe('[Given] skills install with --yes flag', () => {- layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(- it => {- it.scoped('[Then] installs Composio skills', () =>- Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(- mockFetchResponse(makeSessionInfoBody())- );-- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];- yield* cli(args);-- const lines = yield* MockConsole.getLines();- const output = lines.join('\n');-- expect(output).toContain('Installed Composio skills');- })- );- }- );- });-- describe('[Given] --dry-run flag shows skills command', () => {+ describe('[Given] explicit project ids but no global credentials', () => {layer(TestLive({ fixture: 'typescript-project' }))(it => {- it.scoped('[Then] prints skills install command without executing', () =>- Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));-- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];- yield* cli(args);-- const lines = yield* MockConsole.getLines();- const output = lines.join('\n');-- expect(output).toContain('npx skills add composiohq/skills');- expect(output).not.toContain('Installed Composio skills');- })- );- });- });-- describe('[Given] skills install command fails', () => {- layer(- TestLive({- fixture: 'typescript-project',- commandRunner: makeCommandRunnerFail(1),- })- )(it => {- it.scoped('[Then] shows error and suggests manual skills install', () =>+ it.scoped('[Then] it warns and skips .env.local creation', () =>Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));-- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];- yield* cli(args);+ yield* cli(['init', '--org-id', 'org1', '--project-id', 'proj1']);- const lines = yield* MockConsole.getLines();+ const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');-- expect(output).toContain('Skills install failed');- expect(output).toContain('npx skills add composiohq/skills');+ expect(output).toContain('No global API key found; skipping .env.local creation.');}));});});-- // ── --no-skills flag tests ─────────────────────────────────────────────────-- describe('[Given] --no-skills flag', () => {- layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(- it => {- it.scoped('[Then] skips skills prompt and does not install skills', () =>- Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(- mockFetchResponse(makeSessionInfoBody())- );-- const proc = yield* NodeProcess;- const fs = yield* FileSystem.FileSystem;- const args = [- 'init',- '--org-id',- 'org1',- '--project-id',- 'proj1',- '--yes',- '--no-skills',- ];- yield* cli(args);-- const lines = yield* MockConsole.getLines();- const output = lines.join('\n');-- // Should NOT install skills- expect(output).not.toContain('Installed Composio skills');- // Should still install the core dependency- expect(output).toContain('Installed @composio/core');-- // config.json should have install_skills: false- const configPath = path.join(proc.cwd, '.composio', 'config.json');- const configContent = yield* fs.readFileString(configPath);- const config = JSON.parse(configContent);- expect(config.install_skills).toBe(false);- })- );- }- );- });-- // ── MCP mode and PM-skip tests ─────────────────────────────────────────────-- describe('[Given] MCP usage mode selected', () => {- // Select overrides: 0th select (usage mode) → index 1 ("Composio MCP")- const mcpUI = makeTerminalUIWithSelectOverrides({ 0: 1 });-- layer(- TestLive({- fixture: 'typescript-project',- commandRunner: makeCommandRunnerSuccess(),- terminalUI: mcpUI,- })- )(it => {- it.scoped('[Then] skips env detection and dependency install', () =>- Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));-- const proc = yield* NodeProcess;- const fs = yield* FileSystem.FileSystem;- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];- yield* cli(args);-- const lines = yield* MockConsole.getLines();- const output = lines.join('\n');-- // Should NOT detect environment or install dependency in MCP mode- expect(output).not.toContain('Detected:');- expect(output).not.toContain('Installed @composio/core');- expect(output).toContain('Project initialized');-- // config.json should not have detected_language or package_manager- const configPath = path.join(proc.cwd, '.composio', 'config.json');- const configContent = yield* fs.readFileString(configPath);- const config = JSON.parse(configContent);- expect(config.usage_mode).toBe('mcp');- expect(config.detected_language).toBeUndefined();- expect(config.package_manager).toBeUndefined();- })- );- });- });-- describe('[Given] native mode but user skips PM confirmation', () => {- // Select overrides:- // 0th select (usage mode) → index 0 ("Native tools")- // 1st select (framework) → index 0 ("Skip")- // 2nd select (PM confirm) → index 1 ("Skip")- const skipPmUI = makeTerminalUIWithSelectOverrides({ 2: 1 });-- layer(- TestLive({- fixture: 'typescript-project',- commandRunner: makeCommandRunnerSuccess(),- terminalUI: skipPmUI,- })- )(it => {- it.scoped('[Then] detects env but skips dependency install', () =>- Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));-- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];- yield* cli(args);-- const lines = yield* MockConsole.getLines();- const output = lines.join('\n');-- // Should detect environment but NOT install dependency- expect(output).toContain('Detected:');- expect(output).not.toContain('Installed @composio/core');- expect(output).toContain('Project initialized');- })- );- });- });-- describe('[Given] config files are written', () => {- layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(- it => {- it.scoped('[Then] config.json includes detection info', () =>- Effect.gen(function* () {- vi.spyOn(globalThis, 'fetch').mockResolvedValue(- mockFetchResponse(makeSessionInfoBody())- );-- const proc = yield* NodeProcess;- const fs = yield* FileSystem.FileSystem;- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];- yield* cli(args);-- const configPath = path.join(proc.cwd, '.composio', 'config.json');- const configContent = yield* fs.readFileString(configPath);- const config = JSON.parse(configContent);-- expect(config.detected_language).toBeDefined();- expect(config.package_manager).toBeDefined();- })- );- }- );- });});diff --git a/ts/packages/cli/test/src/commands/login.cmd.test.ts b/ts/packages/cli/test/src/commands/login.cmd.test.tsindex bca8b7610..38d34f3c4 100644--- a/ts/packages/cli/test/src/commands/login.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/login.cmd.test.ts@@ -101,7 +101,7 @@ describe('CLI: composio login', () => {const [url, init] = fetchSpy.mock.calls[0]!;expect(url).toContain('/api/v3/auth/session/info');expect((init as RequestInit).headers).toMatchObject({- 'x-api-key': 'uak_test_key',+ 'x-user-api-key': 'uak_test_key','x-org-id': 'org_initial','x-project-id': 'proj_initial',});diff --git a/ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.ts b/ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.tsindex 12b949105..2c8f65cd8 100644--- a/ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.ts@@ -142,6 +142,11 @@ describe('CLI: composio toolkits info', () => {expect(output).toContain('Gmail');expect(output).toContain('gmail');expect(output).toContain('Email service to send and receive emails');+ expect(output).toContain('Latest Version:');+ expect(output).toContain('20250909');+ expect(output).toContain('Tools Count: 36');+ expect(output).toContain('Triggers Count: 2');+ expect(output).toContain('Auth Modes: OAUTH2, BEARER_TOKEN');// Connection statusexpect(output).toContain('Not connected');})@@ -159,12 +164,33 @@ describe('CLI: composio toolkits info', () => {const output = lines.join('\n');expect(output).toContain('Code Interpreter');+ expect(output).toContain('Execute code snippets');+ expect(output).toContain('Tools Count: 5');expect(output).toContain('No authentication required');}));});+ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(+ '[Given] --all flag',+ it => {+ it.scoped('shows full auth config setup fields', () =>+ Effect.gen(function* () {+ yield* cli(['toolkits', 'info', 'gmail', '--all']);+ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = lines.join('\n');++ expect(output).toContain('Auth Config Details:');+ expect(output).toContain('auth_config_creation.required');+ expect(output).toContain('connected_account_initiation.required');+ expect(output).toContain('apiKey');+ expect(output).toContain('API Key');+ })+ );+ }+ );+layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))('[Given] invalid slug',it => {diff --git a/ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts b/ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.tsindex 84e363008..20a821745 100644--- a/ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts@@ -69,9 +69,9 @@ const testConfigProvider = ConfigProvider.fromMap(describe('CLI: composio toolkits list', () => {layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(- '[Given] no flags [Then] lists all toolkits',+ '[Given] no flags [Then] lists all toolkits without connected status',it => {- it.scoped('lists all toolkits', () =>+ it.scoped('lists all toolkits without connected column', () =>Effect.gen(function* () {yield* cli(['toolkits', 'list']);const lines = yield* MockConsole.getLines({ stripAnsi: true });@@ -81,7 +81,24 @@ describe('CLI: composio toolkits list', () => {expect(output).toContain('gmail');expect(output).toContain('Slack');expect(output).toContain('GitHub');- // Connection status column+ // Legacy table fallback removes connection status when no user id is available.+ expect(output).not.toContain('Connected');+ expect(output).toContain('Version');+ expect(output).toContain('Listing 3 of 3 toolkits');+ })+ );+ }+ );++ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(+ '[Given] explicit --user-id [Then] shows connected status column',+ it => {+ it.scoped('shows connected column with explicit user id', () =>+ Effect.gen(function* () {+ yield* cli(['toolkits', 'list', '--user-id', 'default']);+ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = lines.join('\n');+expect(output).toContain('Connected');expect(output).toContain('Listing 3 of 3 toolkits');})diff --git a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.tsindex a9eb7b8a7..0a364f77c 100644--- a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts@@ -48,7 +48,15 @@ describe('CLI: composio tools execute', () => {)('[Given] -d inline JSON [Then] executes via Tool Router with defaults', it => {it.scoped('executes via Tool Router with defaults', () =>Effect.gen(function* () {- yield* cli(['tools', 'execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);+ yield* cli([+ 'tools',+ 'execute',+ 'GMAIL_SEND_EMAIL',+ '--user-id',+ 'default',+ '-d',+ '{"recipient":"a"}',+ ]);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = parseLastJson(lines);@@ -69,7 +77,7 @@ describe('CLI: composio tools execute', () => {)('[Given] stdin is piped [Then] reads input from stdin', it => {it.scoped('reads stdin input', () =>Effect.gen(function* () {- yield* cli(['tools', 'execute', 'GITHUB_GET_REPOS']);+ yield* cli(['tools', 'execute', 'GITHUB_GET_REPOS', '--user-id', 'default']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = parseLastJson(lines);@@ -98,6 +106,8 @@ describe('CLI: composio tools execute', () => {'tools','execute','GMAIL_CREATE_EMAIL_DRAFT',+ '--user-id',+ 'default','-d','{\"recipient\":\"[email protected]\"}',]).pipe(Effect.catchAll(() => Effect.void));@@ -138,6 +148,8 @@ describe('CLI: composio tools execute', () => {'tools','execute','GMAIL_CREATE_EMAIL_DRAFT',+ '--user-id',+ 'default','-d','{"recipient":"[email protected]"}',]).pipe(Effect.catchAll(() => Effect.void));@@ -170,6 +182,8 @@ describe('CLI: composio tools execute', () => {'tools','execute','GITHUB_STAR_REPO',+ '--user-id',+ 'default','-d','{"owner":"composio","repo":"composio"}',]);@@ -203,6 +217,8 @@ describe('CLI: composio tools execute', () => {'tools','execute','GMAIL_CREATE_EMAIL_DRAFT',+ '--user-id',+ 'default','-d','{\"recipient\":\"[email protected]\"}',]).pipe(Effect.catchAll(() => Effect.void));@@ -229,6 +245,8 @@ describe('CLI: composio tools execute', () => {'tools','execute','GMAIL_CREATE_EMAIL_DRAFT',+ '--user-id',+ 'default','-d','{\"recipient\":\"[email protected]\"}',]).pipe(Effect.catchAll(() => Effect.void));@@ -264,6 +282,8 @@ describe('CLI: composio tools execute', () => {'tools','execute','GMAIL_CREATE_EMAIL_DRAFT',+ '--user-id',+ 'default','-d','{\"recipient\":\"[email protected]\"}',]).pipe(Effect.catchAll(() => Effect.void));@@ -300,6 +320,8 @@ describe('CLI: composio tools execute', () => {'tools','execute','GMAIL_CREATE_EMAIL_DRAFT',+ '--user-id',+ 'default','-d','{\"recipient\":\"[email protected]\"}',]).pipe(Effect.catchAll(() => Effect.void));@@ -332,9 +354,15 @@ describe('CLI: composio tools execute', () => {)('[Given] meta tool NoActiveConnection error [Then] does not suggest "link composio"', it => {it.scoped('omits connection tips for meta tool slugs', () =>Effect.gen(function* () {- yield* cli(['tools', 'execute', 'COMPOSIO_SEARCH_TOOLS', '-d', '{"query":"email"}']).pipe(- Effect.catchAll(() => Effect.void)- );+ yield* cli([+ 'tools',+ 'execute',+ 'COMPOSIO_SEARCH_TOOLS',+ '--user-id',+ 'default',+ '-d',+ '{"query":"email"}',+ ]).pipe(Effect.catchAll(() => Effect.void));const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');@@ -359,6 +387,8 @@ describe('CLI: composio tools execute', () => {'tools','execute','GMAIL_SEND_EMAIL',+ '--user-id',+ 'default','-d','not-valid-json',]).pipe(Effect.catchAll(e => Effect.succeed(e)));@@ -379,9 +409,15 @@ describe('CLI: composio tools execute', () => {)('[Given] -d with JSON array [Then] fails with expected-object error', it => {it.scoped('fails with expected object error', () =>Effect.gen(function* () {- const result = yield* cli(['tools', 'execute', 'GMAIL_SEND_EMAIL', '-d', '[1,2,3]']).pipe(- Effect.catchAll(e => Effect.succeed(e))- );+ const result = yield* cli([+ 'tools',+ 'execute',+ 'GMAIL_SEND_EMAIL',+ '--user-id',+ 'default',+ '-d',+ '[1,2,3]',+ ]).pipe(Effect.catchAll(e => Effect.succeed(e)));expect(result).toBeDefined();expect(result instanceof Error ? result.message : String(result)).toContain(@@ -403,6 +439,8 @@ describe('CLI: composio tools execute', () => {'tools','execute','GMAIL_SEND_EMAIL',+ '--user-id',+ 'default','-d','"just a string"',]).pipe(Effect.catchAll(e => Effect.succeed(e)));@@ -423,9 +461,13 @@ describe('CLI: composio tools execute', () => {)('[Given] no -d and TTY stdin [Then] fails with missing input error', it => {it.scoped('fails with missing input error', () =>Effect.gen(function* () {- const result = yield* cli(['tools', 'execute', 'GMAIL_SEND_EMAIL']).pipe(- Effect.catchAll(e => Effect.succeed(e))- );+ const result = yield* cli([+ 'tools',+ 'execute',+ 'GMAIL_SEND_EMAIL',+ '--user-id',+ 'default',+ ]).pipe(Effect.catchAll(e => Effect.succeed(e)));expect(result).toBeDefined();expect(result instanceof Error ? result.message : String(result)).toContain(@@ -443,9 +485,13 @@ describe('CLI: composio tools execute', () => {)('[Given] empty piped stdin [Then] fails with parse error', it => {it.scoped('fails with error for empty stdin', () =>Effect.gen(function* () {- const result = yield* cli(['tools', 'execute', 'GMAIL_SEND_EMAIL']).pipe(- Effect.catchAll(e => Effect.succeed(e))- );+ const result = yield* cli([+ 'tools',+ 'execute',+ 'GMAIL_SEND_EMAIL',+ '--user-id',+ 'default',+ ]).pipe(Effect.catchAll(e => Effect.succeed(e)));expect(result).toBeDefined();expect(result instanceof Error ? result.message : String(result)).toContain(@@ -489,6 +535,8 @@ describe('CLI: composio tools execute', () => {'tools','execute','GMAIL_SEND_EMAIL',+ '--user-id',+ 'default','-d','{"recipient_email":"[email protected]"}',]);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.tsindex 82f3bc44e..9720f0530 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@@ -1,5 +1,9 @@import { describe, expect, layer } from '@effect/vitest';import { ConfigProvider, Effect } from 'effect';+import type {+ SessionCreateParams,+ SessionSearchParams,+} from '@composio/client/resources/tool-router';import { extendConfigProvider } from 'src/services/config';import { cli, TestLive, MockConsole } from 'test/__utils__';import type { TestLiveInput } from 'test/__utils__/services/test-layer';@@ -85,10 +89,181 @@ describe('CLI: composio tools search', () => {yield* cli(['tools', 'search', 'send', '--toolkits', 'gmail']);const lines = yield* MockConsole.getLines({ stripAnsi: true });const output = lines.join('\n');+ const humanOutput = output.split('\n{')[0] ?? output;- expect(output).toContain('GMAIL_SEND_EMAIL');- expect(output).not.toContain('SLACK_SEND_MESSAGE');- expect(output).toContain('Found 1 tools');+ expect(humanOutput).toContain('GMAIL_SEND_EMAIL');+ expect(humanOutput).not.toContain('SLACK_SEND_MESSAGE');+ expect(humanOutput).toContain('Found 1 tools');+ })+ );+ }+ );++ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(+ '[Given] tools search [Then] JSON output includes full tool-router payload',+ it => {+ it.scoped('prints full search response for jq', () =>+ Effect.gen(function* () {+ yield* cli(['tools', '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('"toolkit_connection_statuses"');+ expect(output).toContain('"session"');+ expect(output).toContain('"time_info"');+ })+ );+ }+ );++ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(+ '[Given] --toolkits filter [Then] it is passed to session create as enabled toolkits',+ it => {+ it.scoped('passes toolkit filter into tool router session', () =>+ Effect.gen(function* () {+ let createParams: SessionCreateParams | undefined;+ let searchParams: SessionSearchParams | undefined;++ const live = TestLive({+ baseConfigProvider: testConfigProvider,+ toolkitsData,+ toolRouter: {+ create: async params => {+ createParams = params;+ return {+ session_id: 'trs_test_session',+ config: { user_id: params.user_id },+ mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },+ tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],+ };+ },+ search: async (_sessionId, params) => {+ searchParams = params;+ return {+ 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'],+ },+ ],+ 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(['tools', 'search', 'send', '--toolkits', 'gmail,outlook']).pipe(+ Effect.provide(live)+ );++ expect(createParams?.toolkits).toEqual({ enable: ['gmail', 'outlook'] });+ expect(searchParams?.queries[0]?.use_case).toBe('send');+ })+ );+ }+ );++ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(+ '[Given] search response with recommended plan [Then] it prints plan and execute hint',+ it => {+ it.scoped('prints plan and command hints', () =>+ Effect.gen(function* () {+ const live = TestLive({+ baseConfigProvider: testConfigProvider,+ toolkitsData,+ 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'],+ recommended_plan_steps: ['Collect recipient details', 'Execute send action'],+ },+ ],+ 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: ['Fallback 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(['tools', 'search', 'send email']).pipe(Effect.provide(live));+ const lines = yield* MockConsole.getLines({ stripAnsi: true });+ const output = lines.join('\n');++ expect(output).toContain('Plan:');+ expect(output).toContain('1. Collect recipient details');+ expect(output).toContain('Hints:');+ expect(output).toContain('composio tools info "GMAIL_SEND_EMAIL"');+ expect(output).toContain(+ `composio tools execute "GMAIL_SEND_EMAIL" --user-id "<user-id>" --arguments '{}'`+ );}));}diff --git a/ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts b/ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.tsindex 350035eb9..c6b982812 100644--- a/ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts@@ -71,7 +71,7 @@ const startWebhookServer = async (): Promise<{webhookId: (req.headers['webhook-id'] as string | undefined) ?? '',webhookTimestamp: (req.headers['webhook-timestamp'] as string | undefined) ?? '',webhookSignature: (req.headers['webhook-signature'] as string | undefined) ?? '',- webhookVersion: (req.headers['x-composio-webhook-version'] as string | undefined) ?? '',+ webhookVersion: (req.headers['webhook-version'] as string | undefined) ?? '',},});res.statusCode = 200;diff --git a/ts/packages/cli/test/src/models/project-keys.test.ts b/ts/packages/cli/test/src/models/project-keys.test.tsindex d7798187f..65cff6563 100644--- a/ts/packages/cli/test/src/models/project-keys.test.ts+++ b/ts/packages/cli/test/src/models/project-keys.test.ts@@ -14,6 +14,7 @@ describe('ProjectKeys', () => {expect(Option.isNone(result.projectName)).toBe(true);expect(Option.isNone(result.orgName)).toBe(true);expect(Option.isNone(result.email)).toBe(true);+ expect(Option.isNone(result.testUserId)).toBe(true);});it('decodes valid JSON with all fields', () => {@@ -23,6 +24,7 @@ describe('ProjectKeys', () => {project_name: 'My Project',org_name: 'My Org',email: '[email protected]',+ test_user_id: 'pg-test-user-123',});const result = Effect.runSync(projectKeysFromJSON(json));@@ -32,6 +34,7 @@ describe('ProjectKeys', () => {expect(Option.getOrUndefined(result.projectName)).toBe('My Project');expect(Option.getOrUndefined(result.orgName)).toBe('My Org');expect(Option.getOrUndefined(result.email)).toBe('[email protected]');+ expect(Option.getOrUndefined(result.testUserId)).toBe('pg-test-user-123');});it('decodes null optional fields as Option.none()', () => {@@ -41,6 +44,7 @@ describe('ProjectKeys', () => {project_name: null,org_name: null,email: null,+ test_user_id: null,});const result = Effect.runSync(projectKeysFromJSON(json));@@ -50,6 +54,7 @@ describe('ProjectKeys', () => {expect(Option.isNone(result.projectName)).toBe(true);expect(Option.isNone(result.orgName)).toBe(true);expect(Option.isNone(result.email)).toBe(true);+ expect(Option.isNone(result.testUserId)).toBe(true);});it('ignores extra keys in decoded JSON', () => {@@ -105,6 +110,7 @@ describe('ProjectKeys', () => {projectName: Option.some('My Project'),orgName: Option.some('My Org'),email: Option.some('[email protected]'),+ testUserId: Option.some('pg-test-user-123'),};const json = Effect.runSync(projectKeysToJSON(keys));@@ -115,6 +121,7 @@ describe('ProjectKeys', () => {expect(parsed.project_name).toBe('My Project');expect(parsed.org_name).toBe('My Org');expect(parsed.email).toBe('[email protected]');+ expect(parsed.test_user_id).toBe('pg-test-user-123');});it('encodes None optional fields as null', () => {@@ -124,6 +131,7 @@ describe('ProjectKeys', () => {projectName: Option.none(),orgName: Option.none(),email: Option.none(),+ testUserId: Option.none(),};const json = Effect.runSync(projectKeysToJSON(keys));@@ -134,6 +142,7 @@ describe('ProjectKeys', () => {expect(parsed.project_name).toBeNull();expect(parsed.org_name).toBeNull();expect(parsed.email).toBeNull();+ expect(parsed.test_user_id).toBeNull();});});@@ -145,6 +154,7 @@ describe('ProjectKeys', () => {projectName: Option.some('Test Project'),orgName: Option.some('Test Org'),email: Option.some('[email protected]'),+ testUserId: Option.some('pg-test-user-123'),};const json = Effect.runSync(projectKeysToJSON(original));@@ -157,6 +167,9 @@ describe('ProjectKeys', () => {);expect(Option.getOrUndefined(decoded.orgName)).toBe(Option.getOrUndefined(original.orgName));expect(Option.getOrUndefined(decoded.email)).toBe(Option.getOrUndefined(original.email));+ expect(Option.getOrUndefined(decoded.testUserId)).toBe(+ Option.getOrUndefined(original.testUserId)+ );});it('encode then decode preserves None values', () => {@@ -166,6 +179,7 @@ describe('ProjectKeys', () => {projectName: Option.none(),orgName: Option.none(),email: Option.none(),+ testUserId: Option.none(),};const json = Effect.runSync(projectKeysToJSON(original));@@ -176,6 +190,7 @@ describe('ProjectKeys', () => {expect(Option.isNone(decoded.projectName)).toBe(true);expect(Option.isNone(decoded.orgName)).toBe(true);expect(Option.isNone(decoded.email)).toBe(true);+ expect(Option.isNone(decoded.testUserId)).toBe(true);});});});