Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
feat(cli): enhance init and tool-router based tool discovery (#2767)
Musthaq Ahamad committed
Feb 25, 2026 at 20:36 UTC
2bd2db476cf715fe5f09caf2c3d8799505e7ef51
25 files changed
+1116
-1116
.changeset/few-beers-join.md
new
+5
@@ -0,0 +1,5 @@
1
+---
2
+'@composio/cli': patch
3
+---
4
+
5
+Update tool search and API key inference
ts/e2e-tests/cli/toolkits/list/e2e.test.ts
+4
-3
@@ -58,9 +58,10 @@ e2e(import.meta.url, {
58
expect(item).toHaveProperty('name');
59
expect(item).toHaveProperty('slug');
60
expect(item).toHaveProperty('description');
61
- expect(item).toHaveProperty('is_no_auth');
62
- expect(item).toHaveProperty('enabled');
63
- expect(item).toHaveProperty('composio_managed_auth_schemes');
61
+ // `toolkits list` without user-id uses legacy listing output.
62
+ expect(item).toHaveProperty('latest_version');
63
+ expect(item).toHaveProperty('tools_count');
64
+ expect(item).toHaveProperty('triggers_count');
65
});
66
});
67
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+20
-4
@@ -7,6 +7,7 @@ import { requireAuth } from 'src/effects/require-auth';
7
import { handleHttpServerError } from 'src/effects/handle-http-error';
8
import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
9
import { extractMessage } from 'src/utils/api-error-extraction';
10
+import { ProjectContext } from 'src/services/project-context';
11
12
const toolkit = Args.text({ name: 'toolkit' }).pipe(
13
Args.withDescription('Toolkit slug to link (e.g. "github", "gmail")'),
@@ -19,8 +20,8 @@ const authConfig = Options.text('auth-config').pipe(
20
);
21
22
const userId = Options.text('user-id').pipe(
22
- Options.withDescription('User ID for the connection'),
23
- Options.withDefault('default')
23
+ Options.withDescription('User ID for the connection (falls back to project test_user_id)'),
24
+ Options.optional
25
);
26
27
const noBrowser = Options.boolean('no-browser').pipe(
@@ -125,6 +126,21 @@ export const connectedAccountsCmd$Link = Command.make(
126
127
const ui = yield* TerminalUI;
128
const repo = yield* ComposioToolkitsRepository;
129
+ const projectContext = yield* ProjectContext;
130
+ const resolvedProjectContext = yield* projectContext.resolve;
131
+ const testUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
132
+ const resolvedUserId = Option.match(userId, {
133
+ onSome: value => Option.some(value),
134
+ onNone: () => testUserId,
135
+ });
136
+ if (Option.isNone(resolvedUserId)) {
137
+ return yield* Effect.fail(
138
+ new Error('Missing user id. Provide --user-id or run composio init to set test_user_id.')
139
+ );
140
+ }
141
+ if (Option.isNone(userId) && Option.isSome(testUserId)) {
142
+ yield* ui.log.warn(`Using test user id "${testUserId.value}"`);
143
+ }
144
145
// Validate: exactly one of <toolkit> or --auth-config must be provided
146
if (Option.isSome(toolkit) && Option.isSome(authConfig)) {
@@ -152,7 +168,7 @@ export const connectedAccountsCmd$Link = Command.make(
168
'Creating link session...',
169
repo.createConnectedAccountLink({
170
auth_config_id: authConfig.value,
155
- user_id: userId,
171
+ user_id: resolvedUserId.value,
172
})
173
)
174
.pipe(
@@ -186,7 +202,7 @@ export const connectedAccountsCmd$Link = Command.make(
202
.withSpinner(
203
`Linking ${toolkitSlug}...`,
204
Effect.gen(function* () {
189
- const { client, sessionId } = yield* resolveToolRouterSession(userId, {
205
+ const { client, sessionId } = yield* resolveToolRouterSession(resolvedUserId.value, {
206
manageConnections: true,
207
});
208
return yield* Effect.tryPromise(() =>
ts/packages/cli/src/commands/init.cmd.ts
+179
-469
@@ -1,25 +1,21 @@
1
import path from 'node:path';
2
import { Command as CliCommand, Options } from '@effect/cli';
3
-import { Command as PlatformCommand } from '@effect/platform';
3
import { Effect, Option } from 'effect';
4
import { FileSystem } from '@effect/platform';
5
import { ComposioUserContext } from 'src/services/user-context';
6
import { NodeProcess } from 'src/services/node-process';
7
import { projectKeysToJSON, type ProjectKeys } from 'src/models/project-keys';
9
-import { listOrgProjects, type OrgProject } from 'src/services/composio-clients';
8
+import { userDataFromJSON } from 'src/models/user-data';
9
+import {
10
+ createProjectApiKey,
11
+ getSessionInfo,
12
+ listOrgProjects,
13
+ type OrgProject,
14
+} from 'src/services/composio-clients';
15
import * as constants from 'src/constants';
16
import { TerminalUI } from 'src/services/terminal-ui';
17
import { browserLogin, noBrowser as noBrowserOpt } from 'src/commands/login.cmd';
13
-import {
14
- ProjectEnvironmentDetector,
15
- type ProjectEnvironment,
16
-} from 'src/services/project-environment-detector';
17
-import { CommandRunner } from 'src/services/command-runner';
18
-import {
19
- detectCoreDependencyPlan,
20
- resolveCoreDependencyState,
21
- type CoreDependencyPlan,
22
-} from 'src/effects/core-dependency';
18
+import { setupCacheDir } from 'src/effects/setup-cache-dir';
19
20
/**
21
* `composio init` — Initialize a Composio project in the current directory.
@@ -27,18 +23,11 @@ import {
23
* ## Behavior
24
*
25
* 1. **Project selection** — fetches projects from the API or accepts `--org-id`/`--project-id`.
30
- * 2. **Usage mode** — asks "Native tools" vs "Composio MCP".
31
- * 3. **Framework** — if native, asks which agent framework.
32
- * 4. **Coding-agent skills** — asks whether to install Composio skills.
33
- * 5. **Environment detection** — detects language (TS/Python) and package manager.
34
- * 6. **Dependency installation** — installs `@composio/core` or `composio` via detected PM.
35
- * 7. **Writes config** — saves `<cwd>/.composio/project.json` and `<cwd>/.composio/config.json`.
26
+ * 2. **Writes config** — saves `<cwd>/.composio/project.json`.
27
*
28
* ## Flags
29
*
39
- * - `--dry-run` — print install command without executing
40
- * - `--force` — reinstall even if dependency is already present
41
- * - `--yes` / `-y` — skip confirmation prompts
30
+ * - `--yes` / `-y` — auto-select the first project from the list
31
*/
32
33
const orgIdOpt = Options.text('org-id').pipe(
@@ -51,287 +40,17 @@ const projectIdOpt = Options.text('project-id').pipe(
40
Options.withDescription('Project ID (skip interactive picker)')
41
);
42
54
-const dryRunOpt = Options.boolean('dry-run').pipe(
55
- Options.withDefault(false),
56
- Options.withDescription('Print install command without executing it')
57
-);
58
-
59
-const forceOpt = Options.boolean('force').pipe(
60
- Options.withDefault(false),
61
- Options.withDescription('Reinstall even if dependency appears installed')
62
-);
63
-
43
const yesOpt = Options.boolean('yes').pipe(
44
Options.withAlias('y'),
45
Options.withDefault(false),
67
- Options.withDescription('Skip confirmation prompts')
46
+ Options.withDescription('Auto-select default org/project, else first project')
47
);
48
70
-const noSkillsOpt = Options.boolean('no-skills').pipe(
71
- Options.withDefault(false),
72
- Options.withDescription('Skip Composio skills installation')
73
-);
74
-
75
-// ---------------------------------------------------------------------------
76
-// Init config types and options
77
-// ---------------------------------------------------------------------------
78
-
79
-type UsageMode = 'native' | 'mcp';
80
-type NativeFramework = 'skip' | 'ai-sdk' | 'mastra' | 'openai-agents' | 'claude-agent-sdk';
81
-
82
-const USAGE_MODE_OPTIONS: ReadonlyArray<{
83
- value: UsageMode;
84
- label: string;
85
- hint: string;
86
-}> = [
87
- {
88
- value: 'native',
89
- label: 'Native tools',
90
- hint: 'Use with Agent frameworks: AI SDK, Mastra, etc.',
91
- },
92
- {
93
- value: 'mcp',
94
- label: 'Composio MCP',
95
- hint: 'Use Composio tools via MCP',
96
- },
97
-];
98
-
99
-const NATIVE_FRAMEWORK_OPTIONS: ReadonlyArray<{
100
- value: NativeFramework;
101
- label: string;
102
-}> = [
103
- { value: 'skip', label: 'Skip' },
104
- { value: 'ai-sdk', label: 'AI SDK' },
105
- { value: 'mastra', label: 'Mastra' },
106
- { value: 'openai-agents', label: 'OpenAI Agents' },
107
- { value: 'claude-agent-sdk', label: 'Claude Agent SDK' },
108
-];
109
-
110
-// ---------------------------------------------------------------------------
111
-// InitConfig — type-safe builder for the init wizard answers
112
-// ---------------------------------------------------------------------------
113
-
114
-/**
115
- * Immutable config object built step-by-step through the init wizard.
116
- * Each `.with*` method returns a new instance with the added field,
117
- * narrowing the type so downstream code can rely on what has been set.
118
- *
119
- * The builder enforces that `build()` can only be called once ALL wizard
120
- * steps have been completed — calling it too early is a compile-time error.
121
- *
122
- * Future wizard steps (e.g., detected environment, dependency list) can be
123
- * added by introducing new `with*` methods and extending the `build()`
124
- * constraint.
125
- */
126
-class InitConfigBuilder<T extends Record<string, unknown> = Record<string, never>> {
127
- private constructor(private readonly data: T) {}
128
-
129
- static create(): InitConfigBuilder {
130
- return new InitConfigBuilder({});
131
- }
132
-
133
- withUsageMode(mode: UsageMode): InitConfigBuilder<T & { usageMode: UsageMode }> {
134
- return new InitConfigBuilder({ ...this.data, usageMode: mode });
135
- }
136
-
137
- withFramework(
138
- fw: NativeFramework | undefined
139
- ): InitConfigBuilder<T & { framework: NativeFramework | undefined }> {
140
- return new InitConfigBuilder({ ...this.data, framework: fw });
141
- }
142
-
143
- withInstallSkills(install: boolean): InitConfigBuilder<T & { installSkills: boolean }> {
144
- return new InitConfigBuilder({ ...this.data, installSkills: install });
145
- }
146
-
147
- withDetectedEnv(
148
- env: ProjectEnvironment | undefined
149
- ): InitConfigBuilder<T & { detectedEnv: ProjectEnvironment | undefined }> {
150
- return new InitConfigBuilder({ ...this.data, detectedEnv: env });
151
- }
152
-
153
- withInstallPlan(
154
- plan: CoreDependencyPlan | undefined
155
- ): InitConfigBuilder<T & { installPlan: CoreDependencyPlan | undefined }> {
156
- return new InitConfigBuilder({ ...this.data, installPlan: plan });
157
- }
158
-
159
- /** Extract the final config. Only callable when all required fields are present. */
160
- build(
161
- this: InitConfigBuilder<{
162
- usageMode: UsageMode;
163
- framework: NativeFramework | undefined;
164
- installSkills: boolean;
165
- detectedEnv: ProjectEnvironment | undefined;
166
- installPlan: CoreDependencyPlan | undefined;
167
- }>
168
- ): InitConfig {
169
- return {
170
- usageMode: this.data.usageMode,
171
- framework: this.data.framework,
172
- installSkills: this.data.installSkills,
173
- detectedEnv: this.data.detectedEnv,
174
- installPlan: this.data.installPlan,
175
- };
176
- }
177
-
178
- /** Read accumulated data (for intermediate access). */
179
- get value(): T {
180
- return this.data;
181
- }
182
-}
183
-
184
-interface InitConfig {
185
- readonly usageMode: UsageMode;
186
- readonly framework: NativeFramework | undefined;
187
- readonly installSkills: boolean;
188
- readonly detectedEnv: ProjectEnvironment | undefined;
189
- readonly installPlan: CoreDependencyPlan | undefined;
190
-}
191
-
192
-// ---------------------------------------------------------------------------
193
-// Init wizard — collects all answers via the builder
194
-// ---------------------------------------------------------------------------
195
-
196
-/**
197
- * Detect the project environment. Returns `undefined` if detection fails
198
- * (logs a warning but does not abort the wizard).
199
- */
200
-const detectEnvironment = (cwd: string) =>
201
- Effect.gen(function* () {
202
- const ui = yield* TerminalUI;
203
- const envDetector = yield* ProjectEnvironmentDetector;
204
-
205
- return yield* envDetector.detectProjectEnvironment(cwd).pipe(
206
- Effect.tap(env => ui.log.step(`Detected: ${env.language} (${env.packageManager})`)),
207
- Effect.catchTag('services/ProjectEnvironmentDetectorError', e =>
208
- Effect.gen(function* () {
209
- yield* ui.log.warn(e.message);
210
- if (e.details) yield* ui.log.info(e.details);
211
- yield* ui.log.info('Skipping dependency installation.');
212
- return undefined;
213
- })
214
- )
215
- );
216
- });
217
-
218
-/**
219
- * Resolve the install plan for the detected environment.
220
- * Only determines WHAT to install (no version checking or shell commands).
221
- * Version checking is deferred to `runInstallStep`.
222
- */
223
-const resolveInstallPlan = (cwd: string) =>
224
- detectCoreDependencyPlan(cwd).pipe(Effect.catchAll(() => Effect.succeed(null)));
225
-
226
-/**
227
- * After detecting the project environment and resolving an install plan,
228
- * ask the user to confirm the detected package manager or skip installation.
229
- * Returns the plan if confirmed, `undefined` if skipped.
230
- */
231
-const confirmInstallPlan = (plan: CoreDependencyPlan) =>
232
- Effect.gen(function* () {
233
- const ui = yield* TerminalUI;
234
-
235
- type PmChoice = 'confirm' | 'skip';
236
- const choice = yield* ui.select<PmChoice>(
237
- `Install ${plan.dependency} using ${plan.packageManager}?`,
238
- [
239
- { value: 'confirm' as PmChoice, label: plan.packageManager, hint: plan.installCommand },
240
- { value: 'skip' as PmChoice, label: 'Skip' },
241
- ]
242
- );
243
-
244
- return choice === 'confirm' ? plan : undefined;
245
- });
246
-
247
-/**
248
- * Runs the interactive init wizard.
249
- *
250
- * Steps:
251
- * 1. Usage mode — "Native tools" or "Composio MCP"
252
- * 2. Framework — which agent framework (only if native)
253
- * 3. Install skills — whether to install Composio coding-agent skills
254
- * 4. Detect project environment (only if native)
255
- * 5. Resolve + confirm install plan (only if native and environment detected)
256
- *
257
- * All inputs are collected through the builder before any side effects run.
258
- * Returns a fully-built `InitConfig`.
259
- */
260
-const runInitWizard = (cwd: string, params: { noSkills: boolean }) =>
261
- Effect.gen(function* () {
262
- const ui = yield* TerminalUI;
263
-
264
- // Step 1: Usage mode
265
- const usageMode = yield* ui.select<UsageMode>(
266
- 'How would you like to use Composio?',
267
- USAGE_MODE_OPTIONS
268
- );
269
-
270
- // Step 2: Framework (only for native tools)
271
- const framework: NativeFramework | undefined =
272
- usageMode === 'native'
273
- ? yield* ui
274
- .select<NativeFramework>('Which framework do you use?', NATIVE_FRAMEWORK_OPTIONS)
275
- .pipe(Effect.map(fw => (fw === 'skip' ? undefined : fw)))
276
- : undefined;
277
-
278
- // Step 3: Install Composio skills (skip prompt when --no-skills)
279
- const installSkills = params.noSkills
280
- ? false
281
- : yield* ui.confirm('Install Composio skills for your Coding Agent?', {
282
- defaultValue: true,
283
- });
284
-
285
- // Steps 4+5: Detect environment + confirm install plan (only for native tools)
286
- let detectedEnv: ProjectEnvironment | undefined;
287
- let installPlan: CoreDependencyPlan | undefined;
288
-
289
- if (usageMode === 'native') {
290
- // Step 4: Detect project environment
291
- detectedEnv = yield* detectEnvironment(cwd);
292
-
293
- // Step 5: Resolve install plan and confirm package manager
294
- if (detectedEnv) {
295
- const plan = yield* resolveInstallPlan(cwd);
296
- if (plan) {
297
- installPlan = yield* confirmInstallPlan(plan);
298
- }
299
- }
300
- }
301
-
302
- return InitConfigBuilder.create()
303
- .withUsageMode(usageMode)
304
- .withFramework(framework)
305
- .withInstallSkills(installSkills)
306
- .withDetectedEnv(detectedEnv)
307
- .withInstallPlan(installPlan)
308
- .build();
309
- });
310
-
49
// ---------------------------------------------------------------------------
50
// File I/O helpers
51
// ---------------------------------------------------------------------------
314
-
315
-/**
316
- * Serializes an `InitConfig` to the JSON payload written to `.composio/config.json`.
317
- */
318
-const initConfigToJSON = (config: InitConfig): string => {
319
- const payload: Record<string, unknown> = {
320
- usage_mode: config.usageMode,
321
- };
322
- if (config.framework) {
323
- payload.framework = config.framework;
324
- }
325
- payload.install_skills = config.installSkills;
326
- if (config.detectedEnv) {
327
- payload.detected_language = config.detectedEnv.language;
328
- payload.package_manager = config.detectedEnv.packageManager;
329
- }
330
- return JSON.stringify(payload, null, 2);
331
-};
332
-
333
-/** Writes project keys + init config to `<cwd>/.composio/` and creates a `.gitignore`. */
334
-const writeProjectConfig = (composioDir: string, selected: ProjectKeys, config: InitConfig) =>
52
+/** Writes project keys to `<cwd>/.composio/` and creates a `.gitignore`. */
53
+const writeProjectConfig = (composioDir: string, selected: ProjectKeys) =>
54
Effect.gen(function* () {
55
const fs = yield* FileSystem.FileSystem;
56
@@ -345,8 +64,6 @@ const writeProjectConfig = (composioDir: string, selected: ProjectKeys, config:
64
projectJson
65
);
66
348
- yield* fs.writeFileString(path.join(composioDir, 'config.json'), initConfigToJSON(config));
349
-
67
// Create .composio/.gitignore to prevent accidental commits
68
const gitignorePath = path.join(composioDir, '.gitignore');
69
const gitignoreExists = yield* fs.exists(gitignorePath);
@@ -356,169 +73,145 @@ const writeProjectConfig = (composioDir: string, selected: ProjectKeys, config:
73
});
74
75
// ---------------------------------------------------------------------------
359
-// Install step — runs after wizard, before outro
76
+// Structured output helper
77
// ---------------------------------------------------------------------------
78
362
-/**
363
- * Runs the dependency installation step based on the init config.
364
- * Handles --dry-run, --force, --yes flags and already-installed detection.
365
- */
366
-const runInstallStep = (params: {
367
- config: InitConfig;
368
- cwd: string;
369
- dryRun: boolean;
370
- force: boolean;
371
- yes: boolean;
372
-}) =>
79
+const makeOutputJson = (selected: ProjectKeys, composioDir: string) =>
80
+ JSON.stringify({
81
+ org_id: selected.orgId,
82
+ project_id: selected.projectId,
83
+ path: composioDir,
84
+ });
85
+
86
+const getGlobalUserApiKey = () =>
87
Effect.gen(function* () {
374
- const { config, cwd, dryRun, force, yes } = params;
375
- if (!config.installPlan) return;
88
+ const fs = yield* FileSystem.FileSystem;
89
+ const cacheDir = yield* setupCacheDir;
90
+ const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
91
+ const exists = yield* fs.exists(userConfigPath);
92
+ if (!exists) return undefined;
93
377
- const ui = yield* TerminalUI;
378
- const runner = yield* CommandRunner;
379
- const plan = config.installPlan;
94
+ const userDataRaw = yield* fs.readFileString(userConfigPath, 'utf8');
95
+ const parsed = yield* userDataFromJSON(userDataRaw).pipe(Effect.option);
96
+ if (Option.isNone(parsed)) return undefined;
97
381
- // Check if already installed (only for JS — Python version check requires shell)
382
- if (plan.kind === 'js') {
383
- const depState = yield* resolveCoreDependencyState(cwd).pipe(
384
- Effect.catchAll(() => Effect.succeed({ plan, installedVersion: null }))
385
- );
98
+ return Option.getOrUndefined(parsed.value.apiKey);
99
+ });
100
387
- if (depState.installedVersion && !force) {
388
- const detail =
389
- depState.installedVersion.source === 'package.json'
390
- ? `declared in package.json (${depState.installedVersion.version})`
391
- : `${depState.installedVersion.version} (${depState.installedVersion.source})`;
392
- yield* ui.log.info(`Found ${plan.dependency}: ${detail}`);
393
- yield* ui.log.success('Dependency already installed.');
394
- return;
395
- }
101
+const upsertEnvVar = (content: string, key: string, value: string): string => {
102
+ const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
103
+ const line = `${key}=${value}`;
104
+ const pattern = new RegExp(`^${escapedKey}=.*$`, 'm');
105
+ if (pattern.test(content)) {
106
+ return content.replace(pattern, line);
107
+ }
108
+ return content.trim().length ? `${content.trimEnd()}\n${line}\n` : `${line}\n`;
109
+};
110
397
- if (depState.installedVersion && force) {
398
- yield* ui.log.warn('Reinstalling due to --force.');
399
- }
400
- }
111
+const ensureProjectApiKeyInEnv = (params: { cwd: string; selected: ProjectKeys }) =>
112
+ Effect.gen(function* () {
113
+ const { cwd, selected } = params;
114
+ const ui = yield* TerminalUI;
115
+ const fs = yield* FileSystem.FileSystem;
116
+ const ctx = yield* ComposioUserContext;
117
402
- if (dryRun) {
403
- yield* ui.note(plan.installCommand, 'Install Command');
404
- yield* ui.log.info('Dry run complete.');
405
- return;
406
- }
118
+ const envPath = path.join(cwd, '.env.local');
119
+ const envExists = yield* fs.exists(envPath);
120
+ const existingEnvContent = envExists ? yield* fs.readFileString(envPath, 'utf8') : '';
121
+ const hasProjectApiKey = /^COMPOSIO_API_KEY=.*/m.test(existingEnvContent);
122
+ const hasTestUserId = /^COMPOSIO_TEST_USER_ID=.*/m.test(existingEnvContent);
123
408
- const shouldInstall =
409
- yes || (yield* ui.confirm(`Run: ${plan.installCommand}?`, { defaultValue: true }));
410
- if (!shouldInstall) {
411
- yield* ui.log.warn('Installation cancelled.');
124
+ const uakApiKey = yield* getGlobalUserApiKey();
125
+ if (!uakApiKey) {
126
+ yield* ui.log.warn('No global API key found; skipping .env.local creation.');
127
return;
128
}
129
415
- const [cmd, ...args] = plan.installCommand.split(' ');
416
- const command = PlatformCommand.make(cmd!, ...args).pipe(
417
- PlatformCommand.workingDirectory(plan.rootDir)
418
- );
419
-
420
- const install = Effect.gen(function* () {
421
- const exitCode = yield* runner.run(command);
422
- if (exitCode !== 0) {
423
- yield* Effect.fail(new Error(`Install command failed with exit code ${exitCode}`));
424
- }
130
+ const sessionInfo = yield* getSessionInfo({
131
+ baseURL: ctx.data.baseURL,
132
+ apiKey: uakApiKey,
133
+ orgId: selected.orgId,
134
+ projectId: selected.projectId,
135
});
136
427
- yield* ui
428
- .withSpinner(`Installing ${plan.dependency}...`, install, {
429
- successMessage: `Installed ${plan.dependency}.`,
430
- errorMessage: `Failed to install ${plan.dependency}.`,
431
- })
432
- .pipe(
433
- Effect.catchAll(e =>
434
- Effect.gen(function* () {
435
- yield* ui.log.error(`Install failed: ${e instanceof Error ? e.message : String(e)}`);
436
- yield* ui.log.info(`You can install manually: ${plan.installCommand}`);
437
- })
438
- )
439
- );
440
- });
441
-
442
-// ---------------------------------------------------------------------------
443
-// Skills install step — runs `npx skills add composiohq/skills`
444
-// ---------------------------------------------------------------------------
445
-
446
-const SKILLS_INSTALL_COMMAND = 'npx skills add composiohq/skills';
447
-
448
-/**
449
- * Runs the Composio skills installation step.
450
- * Uses `npx skills add composiohq/skills` to install coding-agent skills.
451
- */
452
-const runSkillsInstallStep = (params: {
453
- config: InitConfig;
454
- cwd: string;
455
- dryRun: boolean;
456
- yes: boolean;
457
-}) =>
458
- Effect.gen(function* () {
459
- const { config, cwd, dryRun, yes } = params;
460
- if (!config.installSkills) return;
137
+ let projectApiKey = sessionInfo.api_key?.api_key ?? sessionInfo.api_key?.key ?? null;
138
+ if (!projectApiKey && !hasProjectApiKey) {
139
+ const dateSuffix = new Date().toISOString().slice(0, 10);
140
+ projectApiKey = yield* createProjectApiKey({
141
+ baseURL: ctx.data.baseURL,
142
+ apiKey: uakApiKey,
143
+ orgId: selected.orgId,
144
+ projectId: selected.projectId,
145
+ name: `composio-cli-${dateSuffix}`,
146
+ });
147
+ }
148
462
- const ui = yield* TerminalUI;
463
- const runner = yield* CommandRunner;
149
+ const sessionUserId = sessionInfo.org_member.user_id ?? sessionInfo.org_member.id;
150
+ const composioTestUserId = `pg-test-${sessionUserId}`;
151
+ const composioDir = path.join(cwd, constants.PROJECT_COMPOSIO_DIR);
152
465
- if (dryRun) {
466
- yield* ui.note(SKILLS_INSTALL_COMMAND, 'Skills Install Command');
467
- return;
153
+ let nextEnvContent = existingEnvContent;
154
+ if (!hasProjectApiKey && projectApiKey) {
155
+ nextEnvContent = upsertEnvVar(nextEnvContent, 'COMPOSIO_API_KEY', projectApiKey);
156
}
469
-
470
- const shouldInstall =
471
- yes || (yield* ui.confirm(`Run: ${SKILLS_INSTALL_COMMAND}?`, { defaultValue: true }));
472
- if (!shouldInstall) {
473
- yield* ui.log.warn('Skills installation cancelled.');
474
- return;
157
+ if (!hasTestUserId) {
158
+ nextEnvContent = upsertEnvVar(nextEnvContent, 'COMPOSIO_TEST_USER_ID', composioTestUserId);
159
}
160
477
- const [cmd, ...args] = SKILLS_INSTALL_COMMAND.split(' ');
478
- const command = PlatformCommand.make(cmd!, ...args).pipe(
479
- PlatformCommand.workingDirectory(cwd)
480
- );
161
+ if (nextEnvContent !== existingEnvContent) {
162
+ yield* fs.writeFileString(envPath, nextEnvContent);
163
+ }
164
+ yield* writeProjectConfig(composioDir, {
165
+ ...selected,
166
+ testUserId: Option.some(composioTestUserId),
167
+ });
168
+ if (nextEnvContent !== existingEnvContent) {
169
+ yield* ui.log.step(
170
+ envExists
171
+ ? 'Updated .env.local with Composio credentials'
172
+ : 'Created .env.local with Composio credentials'
173
+ );
174
+ }
175
+ });
176
482
- const install = Effect.gen(function* () {
483
- const exitCode = yield* runner.run(command);
484
- if (exitCode !== 0) {
485
- yield* Effect.fail(new Error(`Skills install command failed with exit code ${exitCode}`));
177
+const logEnvCreationHttpError =
178
+ (ui: TerminalUI) =>
179
+ (e: { status?: number; details?: { message: string; suggestedFix: string }; cause?: unknown }) =>
180
+ Effect.gen(function* () {
181
+ yield* ui.log.warn('Could not create .env.local from session info.');
182
+ if (e.status) {
183
+ yield* ui.log.error(`HTTP ${e.status}`);
184
+ }
185
+ if (e.details) {
186
+ yield* ui.log.error(e.details.message);
187
+ yield* ui.log.step(e.details.suggestedFix);
188
+ } else if (e.cause) {
189
+ yield* ui.log.error(String(e.cause));
190
}
191
});
192
489
- yield* ui
490
- .withSpinner('Installing Composio skills...', install, {
491
- successMessage: 'Installed Composio skills.',
492
- errorMessage: 'Failed to install Composio skills.',
493
- })
494
- .pipe(
495
- Effect.catchAll(e =>
496
- Effect.gen(function* () {
497
- yield* ui.log.error(
498
- `Skills install failed: ${e instanceof Error ? e.message : String(e)}`
499
- );
500
- yield* ui.log.info(`You can install manually: ${SKILLS_INSTALL_COMMAND}`);
501
- })
502
- )
503
- );
193
+const logEnvCreationDecodingError = (ui: TerminalUI) => (e: { cause?: unknown }) =>
194
+ Effect.gen(function* () {
195
+ yield* ui.log.warn('Could not decode API key response; skipping .env.local creation.');
196
+ if (e.cause) {
197
+ yield* ui.log.error(String(e.cause));
198
+ }
199
});
200
506
-// ---------------------------------------------------------------------------
507
-// Structured output helper
508
-// ---------------------------------------------------------------------------
201
+const selectDefaultProject = (params: {
202
+ projects: ReadonlyArray<OrgProject>;
203
+ defaultOrgId: string;
204
+ defaultProjectId: string;
205
+}): OrgProject | undefined => {
206
+ const { projects, defaultOrgId, defaultProjectId } = params;
207
+ const exactMatch = projects.find(p => p.org_id === defaultOrgId && p.id === defaultProjectId);
208
+ if (exactMatch) return exactMatch;
209
510
-const makeOutputJson = (selected: ProjectKeys, config: InitConfig, composioDir: string) =>
511
- JSON.stringify({
512
- org_id: selected.orgId,
513
- project_id: selected.projectId,
514
- usage_mode: config.usageMode,
515
- framework: config.framework ?? null,
516
- install_skills: config.installSkills,
517
- detected_language: config.detectedEnv?.language ?? null,
518
- package_manager: config.detectedEnv?.packageManager ?? null,
519
- install_command: config.installPlan?.installCommand ?? null,
520
- path: composioDir,
521
- });
210
+ const sameOrgFirst = projects.find(p => p.org_id === defaultOrgId);
211
+ if (sameOrgFirst) return sameOrgFirst;
212
+
213
+ return projects[0];
214
+};
215
216
// ---------------------------------------------------------------------------
217
// Command
@@ -527,8 +220,7 @@ const makeOutputJson = (selected: ProjectKeys, config: InitConfig, composioDir:
220
/**
221
* CLI command to initialize a Composio project in the current directory.
222
*
530
- * Creates `<cwd>/.composio/project.json` with org_id and project_id,
531
- * plus `<cwd>/.composio/config.json` with usage mode, framework, and skill preferences.
223
+ * Creates `<cwd>/.composio/project.json` with org_id and project_id.
224
*
225
* Supports two modes:
226
* 1. Interactive: Fetches projects from the API and prompts for selection
@@ -546,15 +238,11 @@ export const initCmd = CliCommand.make(
238
orgId: orgIdOpt,
239
projectId: projectIdOpt,
240
noBrowser: noBrowserOpt,
549
- dryRun: dryRunOpt,
550
- force: forceOpt,
241
yes: yesOpt,
552
- noSkills: noSkillsOpt,
242
},
554
- ({ orgId, projectId, noBrowser, dryRun, force, yes, noSkills }) =>
243
+ ({ orgId, projectId, noBrowser, yes }) =>
244
Effect.gen(function* () {
245
const ui = yield* TerminalUI;
557
- const ctx = yield* ComposioUserContext;
246
const proc = yield* NodeProcess;
247
248
yield* ui.intro('composio init');
@@ -569,20 +257,32 @@ export const initCmd = CliCommand.make(
257
projectName: Option.none(),
258
orgName: Option.none(),
259
email: Option.none(),
260
+ testUserId: Option.none(),
261
};
262
574
- const config = yield* runInitWizard(proc.cwd, { noSkills });
575
- yield* writeProjectConfig(composioDir, selected, config);
576
- yield* runInstallStep({ config, cwd: proc.cwd, dryRun, force, yes });
577
- yield* runSkillsInstallStep({ config, cwd: proc.cwd, dryRun, yes });
263
+ yield* writeProjectConfig(composioDir, selected);
264
+ yield* ensureProjectApiKeyInEnv({ cwd: proc.cwd, selected }).pipe(
265
+ Effect.catchTag('services/HttpServerError', e =>
266
+ Effect.gen(function* () {
267
+ yield* Effect.logDebug('Failed to resolve project API key from session/info:', e);
268
+ yield* logEnvCreationHttpError(ui)(e);
269
+ })
270
+ ),
271
+ Effect.catchTag('services/HttpDecodingError', e =>
272
+ Effect.gen(function* () {
273
+ yield* Effect.logDebug('Failed to decode API key response:', e);
274
+ yield* logEnvCreationDecodingError(ui)(e);
275
+ })
276
+ )
277
+ );
278
279
yield* ui.log.success(`Project initialized in ${composioDir}/`);
580
- yield* ui.output(makeOutputJson(selected, config, composioDir));
280
+ yield* ui.output(makeOutputJson(selected, composioDir));
281
yield* ui.outro('');
282
return;
283
}
284
585
- yield* initInteractiveFlow({ composioDir, noBrowser, dryRun, force, yes, noSkills });
285
+ yield* initInteractiveFlow({ composioDir, noBrowser, yes });
286
})
287
).pipe(CliCommand.withDescription('Initialize a Composio project in the current directory.'));
288
@@ -590,33 +290,27 @@ export const initCmd = CliCommand.make(
290
* Interactive init flow — handles login, project selection, wizard, install.
291
* Extracted to keep the main command handler under the line limit.
292
*/
593
-const initInteractiveFlow = (params: {
594
- composioDir: string;
595
- noBrowser: boolean;
596
- dryRun: boolean;
597
- force: boolean;
598
- yes: boolean;
599
- noSkills: boolean;
600
-}) =>
293
+const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean; yes: boolean }) =>
294
Effect.gen(function* () {
602
- const { composioDir, noBrowser, dryRun, force, yes, noSkills } = params;
295
+ const { composioDir, noBrowser, yes } = params;
296
const ui = yield* TerminalUI;
297
const ctx = yield* ComposioUserContext;
298
const proc = yield* NodeProcess;
299
607
- // 1. Ensure user is logged in
608
- if (!ctx.isLoggedIn()) {
300
+ // 1. Ensure global user API key exists (ignore local/project keys).
301
+ let globalApiKey = yield* getGlobalUserApiKey();
302
+ if (!globalApiKey) {
303
yield* ui.log.step('No credentials found. Logging in...');
304
yield* browserLogin({ scope: 'project', noBrowser });
305
+ globalApiKey = yield* getGlobalUserApiKey();
306
}
307
308
// 2. Fetch projects
614
- const apiKey = Option.getOrUndefined(ctx.data.apiKey);
309
const orgIdValue = Option.getOrUndefined(ctx.data.orgId);
310
const projectIdValue = Option.getOrUndefined(ctx.data.projectId);
617
- if (!apiKey || !orgIdValue || !projectIdValue) {
311
+ if (!globalApiKey || !orgIdValue || !projectIdValue) {
312
yield* ui.log.warn(
619
- 'No API key, org ID, or project ID found. Please try `composio login` first.'
313
+ 'No global API key, org ID, or project ID found. Please try `composio login` first.'
314
);
315
yield* ui.outro('');
316
return;
@@ -624,7 +318,7 @@ const initInteractiveFlow = (params: {
318
319
const orgProjects = yield* listOrgProjects({
320
baseURL: ctx.data.baseURL,
627
- apiKey,
321
+ apiKey: globalApiKey,
322
orgId: orgIdValue,
323
projectId: projectIdValue,
324
}).pipe(
@@ -668,11 +362,16 @@ const initInteractiveFlow = (params: {
362
projectName: Option.some(p.name),
363
orgName: Option.none(),
364
email: Option.some(p.email),
365
+ testUserId: Option.none(),
366
});
367
368
const selectedProject: OrgProject =
674
- orgProjects.data.length === 1
675
- ? orgProjects.data[0]
369
+ yes || orgProjects.data.length === 1
370
+ ? (selectDefaultProject({
371
+ projects: orgProjects.data,
372
+ defaultOrgId: orgIdValue,
373
+ defaultProjectId: projectIdValue,
374
+ }) ?? orgProjects.data[0])
375
: yield* ui.select<OrgProject>(
376
'Select a project:',
377
orgProjects.data.map(p => ({ value: p, label: p.name, hint: p.id }))
@@ -681,13 +380,24 @@ const initInteractiveFlow = (params: {
380
const selected = orgProjectToKeys(selectedProject);
381
yield* ui.log.step(`Using project "${selectedProject.name}"`);
382
684
- // 4. Run wizard + write config + install
685
- const config = yield* runInitWizard(proc.cwd, { noSkills });
686
- yield* writeProjectConfig(composioDir, selected, config);
687
- yield* runInstallStep({ config, cwd: proc.cwd, dryRun, force, yes });
688
- yield* runSkillsInstallStep({ config, cwd: proc.cwd, dryRun, yes });
383
+ // 4. Write project config
384
+ yield* writeProjectConfig(composioDir, selected);
385
+ yield* ensureProjectApiKeyInEnv({ cwd: proc.cwd, selected }).pipe(
386
+ Effect.catchTag('services/HttpServerError', e =>
387
+ Effect.gen(function* () {
388
+ yield* Effect.logDebug('Failed to resolve project API key from session/info:', e);
389
+ yield* logEnvCreationHttpError(ui)(e);
390
+ })
391
+ ),
392
+ Effect.catchTag('services/HttpDecodingError', e =>
393
+ Effect.gen(function* () {
394
+ yield* Effect.logDebug('Failed to decode API key response:', e);
395
+ yield* logEnvCreationDecodingError(ui)(e);
396
+ })
397
+ )
398
+ );
399
400
yield* ui.log.success(`Project initialized in ${composioDir}/`);
691
- yield* ui.output(makeOutputJson(selected, config, composioDir));
401
+ yield* ui.output(makeOutputJson(selected, composioDir));
402
yield* ui.outro('');
403
});
ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts
+88
-69
@@ -17,6 +17,12 @@ const userId = Options.text('user-id').pipe(
17
Options.withDescription('User ID for connection status (default: "default")')
18
);
19
20
+const allDetails = Options.boolean('all').pipe(
21
+ Options.withAlias('a'),
22
+ Options.withDefault(false),
23
+ Options.withDescription('Show all available toolkit details, including auth config fields')
24
+);
25
+
26
/**
27
* View details of a specific toolkit including connection status.
28
*
@@ -26,85 +32,98 @@ const userId = Options.text('user-id').pipe(
32
* composio toolkits info "github" --user-id "alice"
33
* ```
34
*/
29
-export const toolkitsCmd$Info = Command.make('info', { slug, userId }, ({ slug, userId }) =>
30
- Effect.gen(function* () {
31
- if (!(yield* requireAuth)) return;
32
-
33
- const ui = yield* TerminalUI;
34
-
35
- // Missing slug guard
36
- if (Option.isNone(slug)) {
37
- yield* ui.log.warn('Missing required argument: <slug>');
38
- yield* ui.log.step('Try specifying a toolkit slug, e.g.:\n> composio toolkits info "gmail"');
39
- return;
40
- }
41
-
42
- const slugValue = slug.value;
43
-
44
- const resultOpt = yield* ui
45
- .withSpinner(
46
- `Fetching toolkit "${slugValue}"...`,
47
- Effect.gen(function* () {
48
- const { client, sessionId } = yield* resolveToolRouterSession(userId);
49
- return yield* Effect.tryPromise(() =>
50
- client.toolRouter.session.toolkits(sessionId, {
51
- toolkits: [slugValue],
52
- })
53
- );
54
- })
55
- )
56
- .pipe(
57
- Effect.asSome,
58
- Effect.catchAll(error =>
35
+export const toolkitsCmd$Info = Command.make(
36
+ 'info',
37
+ { slug, userId, allDetails },
38
+ ({ slug, userId, allDetails }) =>
39
+ Effect.gen(function* () {
40
+ if (!(yield* requireAuth)) return;
41
+
42
+ const ui = yield* TerminalUI;
43
+
44
+ // Missing slug guard
45
+ if (Option.isNone(slug)) {
46
+ yield* ui.log.warn('Missing required argument: <slug>');
47
+ yield* ui.log.step(
48
+ 'Try specifying a toolkit slug, e.g.:\n> composio toolkits info "gmail"'
49
+ );
50
+ return;
51
+ }
52
+
53
+ const slugValue = slug.value;
54
+ const repo = yield* ComposioToolkitsRepository;
55
+
56
+ const resultOpt = yield* ui
57
+ .withSpinner(
58
+ `Fetching toolkit "${slugValue}"...`,
59
Effect.gen(function* () {
60
- const message = extractMessage(error) ?? `Failed to fetch toolkit "${slugValue}".`;
61
- yield* ui.log.error(message);
62
- yield* Effect.logDebug('Toolkit info error:', error);
63
- yield* ui.log.step('Browse available toolkits:\n> composio toolkits list');
64
- return Option.none();
60
+ const [{ client, sessionId }, detailedToolkitOpt] = yield* Effect.all(
61
+ [
62
+ resolveToolRouterSession(userId),
63
+ repo.getToolkitDetailed(slugValue).pipe(Effect.option),
64
+ ],
65
+ { concurrency: 'unbounded' }
66
+ );
67
+ const sessionToolkits = yield* Effect.tryPromise(() =>
68
+ client.toolRouter.session.toolkits(sessionId, { toolkits: [slugValue] })
69
+ );
70
+ return { sessionToolkits, detailedToolkitOpt };
71
})
72
)
67
- );
73
+ .pipe(
74
+ Effect.asSome,
75
+ Effect.catchAll(error =>
76
+ Effect.gen(function* () {
77
+ const message = extractMessage(error) ?? `Failed to fetch toolkit "${slugValue}".`;
78
+ yield* ui.log.error(message);
79
+ yield* Effect.logDebug('Toolkit info error:', error);
80
+ yield* ui.log.step('Browse available toolkits:\n> composio toolkits list');
81
+ return Option.none();
82
+ })
83
+ )
84
+ );
85
69
- if (Option.isNone(resultOpt)) {
70
- return;
71
- }
86
+ if (Option.isNone(resultOpt)) {
87
+ return;
88
+ }
89
73
- const result = resultOpt.value;
74
- const toolkit = result.items[0];
90
+ const result = resultOpt.value;
91
+ const toolkit = result.sessionToolkits.items[0];
92
+ const detailedToolkit = Option.getOrUndefined(result.detailedToolkitOpt);
93
76
- if (!toolkit) {
77
- yield* ui.log.warn(`Toolkit "${slugValue}" not found.`);
94
+ if (!toolkit) {
95
+ yield* ui.log.warn(`Toolkit "${slugValue}" not found.`);
96
79
- // "Did you mean?" suggestions via legacy search
80
- const repo = yield* ComposioToolkitsRepository;
81
- const suggestions = yield* repo.searchToolkits({ search: slugValue, limit: 3 }).pipe(
82
- Effect.map(r =>
83
- r.items.map(s => ({
84
- label: `${s.slug} — ${s.meta.description}`,
85
- command: `> composio toolkits info "${s.slug}"`,
86
- }))
87
- ),
88
- Effect.catchAll(() => Effect.succeed([] as { label: string; command: string }[]))
89
- );
97
+ // "Did you mean?" suggestions via legacy search
98
+ const suggestions = yield* repo.searchToolkits({ search: slugValue, limit: 3 }).pipe(
99
+ Effect.map(r =>
100
+ r.items.map(s => ({
101
+ label: `${s.slug} — ${s.meta.description}`,
102
+ command: `> composio toolkits info "${s.slug}"`,
103
+ }))
104
+ ),
105
+ Effect.catchAll(() => Effect.succeed([] as { label: string; command: string }[]))
106
+ );
107
91
- const [first] = suggestions;
92
- if (first) {
93
- const lines = suggestions.map(s => ` ${s.label}`).join('\n');
94
- yield* ui.log.step(`Did you mean?\n${lines}\n\n${first.command}`);
95
- } else {
96
- yield* ui.log.step('Browse available toolkits:\n> composio toolkits list');
108
+ const [first] = suggestions;
109
+ if (first) {
110
+ const lines = suggestions.map(s => ` ${s.label}`).join('\n');
111
+ yield* ui.log.step(`Did you mean?\n${lines}\n\n${first.command}`);
112
+ } else {
113
+ yield* ui.log.step('Browse available toolkits:\n> composio toolkits list');
114
+ }
115
+ return;
116
}
98
- return;
99
- }
117
101
- yield* ui.note(formatToolkitInfo(toolkit), `Toolkit: ${toolkit.name}`);
118
+ yield* ui.log.message(
119
+ `Toolkit: ${toolkit.name}\n\n${formatToolkitInfo(toolkit, detailedToolkit, allDetails)}`
120
+ );
121
103
- // Next step hint
104
- yield* ui.log.step(
105
- `To list tools in this toolkit:\n> composio tools list --toolkits "${toolkit.slug}"`
106
- );
122
+ // Next step hint
123
+ yield* ui.log.step(
124
+ `To list tools in this toolkit:\n> composio tools list --toolkits "${toolkit.slug}"`
125
+ );
126
108
- yield* ui.output(formatToolkitInfoJson(toolkit));
109
- })
127
+ yield* ui.output(formatToolkitInfoJson(toolkit, detailedToolkit, allDetails));
128
+ })
129
).pipe(Command.withDescription('View details of a specific toolkit.'));
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
+71
-19
@@ -3,8 +3,15 @@ import { Effect, Option } from 'effect';
3
import { TerminalUI } from 'src/services/terminal-ui';
4
import { requireAuth } from 'src/effects/require-auth';
5
import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
6
+import { ComposioToolkitsRepository } from 'src/services/composio-clients';
7
+import { ProjectContext } from 'src/services/project-context';
8
import { clampLimit } from 'src/ui/clamp-limit';
7
-import { formatToolkitsTable, formatToolkitsJson } from '../format';
9
+import {
10
+ formatLegacyToolkitsJson,
11
+ formatLegacyToolkitsTable,
12
+ formatToolkitsJson,
13
+ formatToolkitsTable,
14
+} from '../format';
15
16
const query = Options.text('query').pipe(
17
Options.withDescription('Text search by name, slug, or description'),
@@ -22,8 +29,8 @@ const connected = Options.boolean('connected').pipe(
29
);
30
31
const userId = Options.text('user-id').pipe(
25
- Options.withDefault('default'),
26
- Options.withDescription('User ID for connection status (default: "default")')
32
+ Options.optional,
33
+ Options.withDescription('User ID for connection status (defaults to project test_user_id)')
34
);
35
36
/**
@@ -45,36 +52,81 @@ export const toolkitsCmd$List = Command.make(
52
if (!(yield* requireAuth)) return;
53
54
const ui = yield* TerminalUI;
55
+ const repo = yield* ComposioToolkitsRepository;
56
+ const projectContext = yield* ProjectContext;
57
58
const clampedLimit = clampLimit(limit);
59
+ const resolvedProjectContext = yield* projectContext.resolve;
60
+ const testUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
61
+ const resolvedUserId = Option.orElse(userId, () => testUserId);
62
+ const usingDefaultTestUserId = Option.isNone(userId) && Option.isSome(testUserId);
63
+
64
+ if (usingDefaultTestUserId && Option.isSome(testUserId)) {
65
+ yield* ui.log.info(`Showing connection status for user id "${testUserId.value}"`);
66
+ yield* ui.log.message('To show status for a specific user, use `--user-id`.');
67
+ }
68
+
69
+ if (Option.isSome(resolvedUserId)) {
70
+ const result = yield* ui.withSpinner(
71
+ 'Fetching toolkits...',
72
+ Effect.gen(function* () {
73
+ const { client, sessionId } = yield* resolveToolRouterSession(resolvedUserId.value);
74
+ return yield* Effect.tryPromise(() =>
75
+ client.toolRouter.session.toolkits(sessionId, {
76
+ search: Option.getOrUndefined(query),
77
+ limit: clampedLimit,
78
+ is_connected: Option.getOrUndefined(connected),
79
+ })
80
+ );
81
+ })
82
+ );
83
+
84
+ const { items } = result;
85
+ if (items.length === 0) {
86
+ yield* ui.log.warn('No toolkits found. Try broadening your search.');
87
+ yield* ui.output('[]');
88
+ return;
89
+ }
90
+
91
+ const showing = items.length;
92
+ const total = result.total_items;
93
+ yield* ui.log.info(
94
+ `Listing ${showing} of ${total} toolkits\n\n${formatToolkitsTable(items)}`
95
+ );
96
+
97
+ const firstSlug = items[0]?.slug;
98
+ if (firstSlug) {
99
+ yield* ui.log.step(
100
+ `To view details of a toolkit:\n> composio toolkits info "${firstSlug}"`
101
+ );
102
+ }
103
+ yield* ui.output(formatToolkitsJson(items));
104
+ return;
105
+ }
106
+
107
+ if (Option.isSome(connected)) {
108
+ yield* ui.log.warn(
109
+ '`--connected` requires a user id. Use `--user-id` or run `composio init`.'
110
+ );
111
+ }
112
113
const result = yield* ui.withSpinner(
114
'Fetching toolkits...',
53
- Effect.gen(function* () {
54
- const { client, sessionId } = yield* resolveToolRouterSession(userId);
55
- return yield* Effect.tryPromise(() =>
56
- client.toolRouter.session.toolkits(sessionId, {
57
- search: Option.getOrUndefined(query),
58
- limit: clampedLimit,
59
- is_connected: Option.getOrUndefined(connected),
60
- })
61
- );
115
+ repo.searchToolkits({
116
+ search: Option.getOrUndefined(query),
117
+ limit: clampedLimit,
118
})
119
);
64
-
65
- const { items } = result;
66
-
120
+ const items = result.items;
121
if (items.length === 0) {
122
yield* ui.log.warn('No toolkits found. Try broadening your search.');
123
yield* ui.output('[]');
124
return;
125
}
72
-
126
const showing = items.length;
127
const total = result.total_items;
75
-
128
yield* ui.log.info(
77
- `Listing ${showing} of ${total} toolkits\n\n${formatToolkitsTable(items)}`
129
+ `Listing ${showing} of ${total} toolkits\n\n${formatLegacyToolkitsTable(items)}`
130
);
131
132
// Next step hint
@@ -85,6 +137,6 @@ export const toolkitsCmd$List = Command.make(
137
);
138
}
139
88
- yield* ui.output(formatToolkitsJson(items));
140
+ yield* ui.output(formatLegacyToolkitsJson(items));
141
})
142
).pipe(Command.withDescription('List available toolkits with connection status.'));
ts/packages/cli/src/commands/toolkits/format.ts
+109
-5
@@ -1,10 +1,26 @@
1
-import type { Toolkit } from 'src/models/toolkits';
1
+import type { Toolkit, ToolkitDetailed } from 'src/models/toolkits';
2
import type { SessionToolkitsResponse } from '@composio/client/resources/tool-router';
3
import { bold, gray, green, dim } from 'src/ui/colors';
4
import { truncate } from 'src/ui/truncate';
5
6
type SessionToolkitItem = SessionToolkitsResponse.Item;
7
8
+const formatAuthConfigField = (field: {
9
+ name: string;
10
+ displayName: string;
11
+ description: string;
12
+ type: string;
13
+ required: boolean;
14
+ default: string | null;
15
+}): string =>
16
+ [
17
+ ` - ${field.name} (${field.type})`,
18
+ ` display: ${field.displayName}`,
19
+ ` required: ${field.required ? 'yes' : 'no'}`,
20
+ ` default: ${field.default ?? '-'}`,
21
+ ` description: ${field.description || '-'}`,
22
+ ].join('\n');
23
+
24
// ---------- Tool Router format functions ----------
25
26
/**
@@ -69,12 +85,79 @@ export function formatToolkitsJson(toolkits: ReadonlyArray<SessionToolkitItem>):
85
/**
86
* Format a single session toolkit for detailed interactive display.
87
*/
72
-export function formatToolkitInfo(toolkit: SessionToolkitItem): string {
88
+export function formatToolkitInfo(
89
+ toolkit: SessionToolkitItem,
90
+ detailed?: ToolkitDetailed,
91
+ showAllDetails = false
92
+): string {
93
const lines: string[] = [];
94
+ const detailedMeta = detailed?.meta;
95
+ const availableVersions = detailedMeta?.available_versions ?? [];
96
+ const latestVersion = availableVersions.at(-1);
97
+ const authModes = detailed?.auth_config_details.map(detail => detail.mode) ?? [];
98
99
lines.push(`${bold('Name:')} ${toolkit.name}`);
100
lines.push(`${bold('Slug:')} ${toolkit.slug}`);
77
- lines.push(`${bold('Description:')} ${toolkit.meta.description || '(none)'}`);
101
+ lines.push(
102
+ `${bold('Description:')} ${detailedMeta?.description || toolkit.meta.description || '(none)'}`
103
+ );
104
+ lines.push(`${bold('Latest Version:')} ${latestVersion ?? '-'}`);
105
+ lines.push(`${bold('Tools Count:')} ${detailedMeta?.tools_count ?? '-'}`);
106
+ lines.push(`${bold('Triggers Count:')} ${detailedMeta?.triggers_count ?? '-'}`);
107
+ if (authModes.length > 0) {
108
+ lines.push(`${bold('Auth Modes:')} ${authModes.join(', ')}`);
109
+ }
110
+ if (showAllDetails && detailed) {
111
+ lines.push(`${bold('No Auth:')} ${detailed.no_auth ? 'Yes' : 'No'}`);
112
+ lines.push(`${bold('Is Local Toolkit:')} ${detailed.is_local_toolkit ? 'Yes' : 'No'}`);
113
+ lines.push(`${bold('Created At:')} ${String(detailed.meta.created_at)}`);
114
+ lines.push(`${bold('Updated At:')} ${String(detailed.meta.updated_at)}`);
115
+ lines.push(
116
+ `${bold('Composio Managed Auth Schemes:')} ${
117
+ detailed.composio_managed_auth_schemes.length > 0
118
+ ? detailed.composio_managed_auth_schemes.join(', ')
119
+ : '-'
120
+ }`
121
+ );
122
+ lines.push('');
123
+ lines.push(bold('Auth Config Details:'));
124
+ if (detailed.auth_config_details.length === 0) {
125
+ lines.push(' - none');
126
+ } else {
127
+ for (const detail of detailed.auth_config_details) {
128
+ lines.push(` - ${detail.mode} (${detail.name})`);
129
+ const creationRequired = detail.fields.auth_config_creation.required;
130
+ const creationOptional = detail.fields.auth_config_creation.optional;
131
+ const initiationRequired = detail.fields.connected_account_initiation.required;
132
+ const initiationOptional = detail.fields.connected_account_initiation.optional;
133
+
134
+ lines.push(' auth_config_creation.required:');
135
+ lines.push(
136
+ creationRequired.length > 0
137
+ ? creationRequired.map(formatAuthConfigField).join('\n')
138
+ : ' - none'
139
+ );
140
+ lines.push(' auth_config_creation.optional:');
141
+ lines.push(
142
+ creationOptional.length > 0
143
+ ? creationOptional.map(formatAuthConfigField).join('\n')
144
+ : ' - none'
145
+ );
146
+ lines.push(' connected_account_initiation.required:');
147
+ lines.push(
148
+ initiationRequired.length > 0
149
+ ? initiationRequired.map(formatAuthConfigField).join('\n')
150
+ : ' - none'
151
+ );
152
+ lines.push(' connected_account_initiation.optional:');
153
+ lines.push(
154
+ initiationOptional.length > 0
155
+ ? initiationOptional.map(formatAuthConfigField).join('\n')
156
+ : ' - none'
157
+ );
158
+ }
159
+ }
160
+ }
161
162
if (toolkit.is_no_auth) {
163
lines.push(`${bold('Auth:')} No authentication required`);
@@ -109,14 +192,23 @@ export function formatToolkitInfo(toolkit: SessionToolkitItem): string {
192
* Format a single session toolkit as JSON for piped output.
193
* Produces a stable, curated schema — does not leak the raw API response.
194
*/
112
-export function formatToolkitInfoJson(toolkit: SessionToolkitItem): string {
195
+export function formatToolkitInfoJson(
196
+ toolkit: SessionToolkitItem,
197
+ detailed?: ToolkitDetailed,
198
+ showAllDetails = false
199
+): string {
200
+ const availableVersions = detailed?.meta.available_versions ?? [];
201
+ const latestVersion = availableVersions.at(-1) ?? null;
202
return JSON.stringify(
203
{
204
name: toolkit.name,
205
slug: toolkit.slug,
206
meta: {
118
- description: toolkit.meta.description,
207
+ description: detailed?.meta.description ?? toolkit.meta.description,
208
logo: toolkit.meta.logo,
209
+ latest_version: latestVersion,
210
+ tools_count: detailed?.meta.tools_count ?? null,
211
+ triggers_count: detailed?.meta.triggers_count ?? null,
212
},
213
is_no_auth: toolkit.is_no_auth,
214
enabled: toolkit.enabled,
@@ -129,6 +221,18 @@ export function formatToolkitInfoJson(toolkit: SessionToolkitItem): string {
221
}
222
: null,
223
composio_managed_auth_schemes: toolkit.composio_managed_auth_schemes,
224
+ auth_modes: detailed?.auth_config_details.map(detail => detail.mode) ?? [],
225
+ ...(showAllDetails && detailed
226
+ ? {
227
+ detailed: {
228
+ is_local_toolkit: detailed.is_local_toolkit,
229
+ no_auth: detailed.no_auth,
230
+ created_at: String(detailed.meta.created_at),
231
+ updated_at: String(detailed.meta.updated_at),
232
+ auth_config_details: detailed.auth_config_details,
233
+ },
234
+ }
235
+ : {}),
236
},
237
null,
238
2
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+22
-5
@@ -12,6 +12,7 @@ import {
12
ToolsExecutor,
13
} from 'src/services/tools-executor';
14
import type { ToolExecuteParams } from 'src/services/tools-executor';
15
+import { ProjectContext } from 'src/services/project-context';
16
import {
17
extractApiErrorDetails,
18
extractMessage,
@@ -30,8 +31,8 @@ const data = Options.text('data').pipe(
31
);
32
33
const userId = Options.text('user-id').pipe(
33
- Options.withDefault('default'),
34
- Options.withDescription('User ID to execute the tool for (default: "default")')
34
+ Options.optional,
35
+ Options.withDescription('User ID to execute the tool for (falls back to project test_user_id)')
36
);
37
38
const resolveInput = (input: Option.Option<string>) =>
@@ -243,12 +244,27 @@ export const toolsCmd$Execute = Command.make(
244
245
const ui = yield* TerminalUI;
246
const executor = yield* ToolsExecutor;
247
+ const projectContext = yield* ProjectContext;
248
+ const resolvedProjectContext = yield* projectContext.resolve;
249
+ const testUserId = Option.flatMap(resolvedProjectContext, keys => keys.testUserId);
250
+ const resolvedUserId = Option.match(userId, {
251
+ onSome: value => Option.some(value),
252
+ onNone: () => testUserId,
253
+ });
254
+ if (Option.isNone(resolvedUserId)) {
255
+ return yield* Effect.fail(
256
+ new Error('Missing user id. Provide --user-id or run composio init to set test_user_id.')
257
+ );
258
+ }
259
+ if (Option.isNone(userId) && Option.isSome(testUserId)) {
260
+ yield* ui.log.warn(`Using test user id "${testUserId.value}"`);
261
+ }
262
263
const input = yield* resolveInput(data);
264
const args = yield* parseArguments(input);
265
266
const params: ToolExecuteParams = {
251
- userId,
267
+ userId: resolvedUserId.value,
268
arguments: args,
269
};
270
@@ -261,7 +277,7 @@ export const toolsCmd$Execute = Command.make(
277
yield* spinner.error();
278
const summary = yield* handleExecutionError(ui, resultEither.left, {
279
toolSlug: slug,
264
- userId,
280
+ userId: resolvedUserId.value,
281
});
282
yield* ui.output(
283
JSON.stringify({ successful: false, ...summary }, ciRedactReplacer, 2)
@@ -280,7 +296,7 @@ export const toolsCmd$Execute = Command.make(
296
297
const summary = yield* handleExecutionError(ui, result.error ?? result, {
298
toolSlug: slug,
283
- userId,
299
+ userId: resolvedUserId.value,
300
});
301
yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));
302
return yield* Effect.fail(new ToolExecutionError(summary.error));
@@ -291,6 +307,7 @@ export const toolsCmd$Execute = Command.make(
307
? ` (logId: ${redact({ value: result.logId, prefix: 'log_' })})`
308
: '';
309
yield* spinner.stop(`Execution successful${logId}`);
310
+ yield* ui.log.message(`Response\n${JSON.stringify(result, ciRedactReplacer, 2)}`);
311
yield* ui.output(JSON.stringify(result, ciRedactReplacer, 2));
312
})
313
);
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+82
-19
@@ -1,10 +1,11 @@
1
import { Args, Command, Options } from '@effect/cli';
2
import { Effect, Option } from 'effect';
3
-import { ComposioToolkitsRepository } from 'src/services/composio-clients';
3
import { TerminalUI } from 'src/services/terminal-ui';
4
import { requireAuth } from 'src/effects/require-auth';
5
import { clampLimit } from 'src/ui/clamp-limit';
7
-import { formatToolsTable, formatToolsJson } from '../format';
6
+import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
7
+import { formatToolsTable } from '../format';
8
+import type { Tool } from 'src/models/tools';
9
10
const query = Args.text({ name: 'query' }).pipe(
11
Args.withDescription('Search query (e.g. "send emails")')
@@ -38,38 +39,100 @@ export const toolsCmd$Search = Command.make(
39
if (!(yield* requireAuth)) return;
40
41
const ui = yield* TerminalUI;
41
- const repo = yield* ComposioToolkitsRepository;
42
-
42
const clampedLimit = clampLimit(limit);
43
+ const toolkitFilter = Option.getOrUndefined(toolkits);
44
+ const toolkitList =
45
+ toolkitFilter && toolkitFilter.trim().length > 0
46
+ ? toolkitFilter
47
+ .split(',')
48
+ .map(s => s.trim().toLowerCase())
49
+ .filter(Boolean)
50
+ : undefined;
51
45
- const result = yield* ui.withSpinner(
52
+ const searchResponse = yield* ui.withSpinner(
53
`Searching tools for "${query}"...`,
47
- repo.searchTools({
48
- search: query,
49
- toolkit_slug: Option.getOrUndefined(toolkits),
50
- limit: clampedLimit,
54
+ Effect.gen(function* () {
55
+ const { client, sessionId } = yield* resolveToolRouterSession('default-cli', {
56
+ toolkits: toolkitList,
57
+ });
58
+ return yield* Effect.tryPromise(() =>
59
+ client.toolRouter.session.search(sessionId, {
60
+ queries: [{ use_case: query }],
61
+ })
62
+ );
63
})
64
);
65
54
- if (result.items.length === 0) {
66
+ const toolkitSet = toolkitList && toolkitList.length > 0 ? new Set(toolkitList) : undefined;
67
+
68
+ const mergedSlugs: string[] = [];
69
+ const seen = new Set<string>();
70
+ for (const item of searchResponse.results) {
71
+ for (const slug of [...item.primary_tool_slugs, ...item.related_tool_slugs]) {
72
+ if (!seen.has(slug)) {
73
+ seen.add(slug);
74
+ mergedSlugs.push(slug);
75
+ }
76
+ }
77
+ }
78
+
79
+ const toolsList: Tool[] = [];
80
+ for (const slug of mergedSlugs) {
81
+ const schema = searchResponse.tool_schemas[slug];
82
+ if (!schema) continue;
83
+ if (toolkitSet && !toolkitSet.has(schema.toolkit.toLowerCase())) continue;
84
+
85
+ toolsList.push({
86
+ slug: schema.tool_slug,
87
+ name: schema.tool_slug,
88
+ description: schema.description ?? '',
89
+ tags: [],
90
+ available_versions: [],
91
+ input_parameters: (schema.input_schema ?? {}) as Record<string, unknown>,
92
+ output_parameters: (schema.output_schema ?? {}) as Record<string, unknown>,
93
+ } as Tool);
94
+
95
+ if (toolsList.length >= clampedLimit) break;
96
+ }
97
+
98
+ if (toolsList.length === 0) {
99
yield* ui.log.warn(`No tools found matching "${query}". Try broadening your search.`);
100
return;
101
}
102
59
- const showing = result.items.length;
60
- const totalPages = result.total_pages;
61
- yield* ui.log.info(
62
- totalPages > 1
63
- ? `Found ${showing} tools (page 1 of ${totalPages})\n\n${formatToolsTable(result.items)}`
64
- : `Found ${showing} tools\n\n${formatToolsTable(result.items)}`
103
+ const showing = toolsList.length;
104
+ yield* ui.log.info(`Found ${showing} tools\n\n${formatToolsTable(toolsList)}`);
105
+
106
+ const planSteps = Array.from(
107
+ new Set(searchResponse.results.flatMap(result => result.recommended_plan_steps ?? []))
108
);
109
+ if (planSteps.length > 0) {
110
+ yield* ui.log.info(`Plan:\n${planSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}`);
111
+ } else if (searchResponse.next_steps_guidance.length > 0) {
112
+ yield* ui.log.info(
113
+ `Plan:\n${searchResponse.next_steps_guidance
114
+ .map((step, i) => `${i + 1}. ${step}`)
115
+ .join('\n')}`
116
+ );
117
+ }
118
119
// Next step hint
68
- const firstSlug = result.items[0]?.slug;
120
+ const firstSlug = toolsList[0]?.slug;
121
if (firstSlug) {
70
- yield* ui.log.step(`To view details:\n> composio tools info "${firstSlug}"`);
122
+ yield* ui.log.step(
123
+ [
124
+ 'Hints:',
125
+ `> composio tools info "${firstSlug}"`,
126
+ `> composio tools execute "${firstSlug}" --user-id "<user-id>" --arguments '{}'`,
127
+ ].join('\n')
128
+ );
129
+ }
130
+
131
+ if (searchResponse.error) {
132
+ yield* ui.log.warn(searchResponse.error);
133
}
134
73
- yield* ui.output(formatToolsJson(result.items));
135
+ // For machine-readable output (e.g. piping to jq), expose the full API payload.
136
+ yield* ui.output(JSON.stringify(searchResponse, null, 2));
137
})
138
).pipe(Command.withDescription('Search tools by use case.'));
ts/packages/cli/src/commands/triggers/commands/triggers.listen.cmd.ts
+1
-1
@@ -298,7 +298,7 @@ export const triggersCmd$Listen = Command.make(
298
'webhook-id': webhookId,
299
'webhook-timestamp': webhookTimestamp,
300
'webhook-signature': webhookSignature,
301
- 'x-composio-webhook-version': webhookVersion,
301
+ 'webhook-version': webhookVersion,
302
},
303
body: payloadForForwarding,
304
});
ts/packages/cli/src/effects/create-tool-router-session.ts
+6
@@ -5,6 +5,8 @@ import { ComposioClientSingleton } from 'src/services/composio-clients';
5
export interface CreateToolRouterSessionOptions {
6
/** Enable auto connection management. Default: false. */
7
readonly manageConnections?: boolean;
8
+ /** Restrict session to these toolkit slugs. */
9
+ readonly toolkits?: ReadonlyArray<string>;
10
}
11
12
/**
@@ -24,6 +26,10 @@ export const createToolRouterSession = (
26
client.toolRouter.session.create({
27
user_id: userId,
28
manage_connections: { enable: options?.manageConnections ?? false },
29
+ toolkits:
30
+ options?.toolkits && options.toolkits.length > 0
31
+ ? { enable: [...options.toolkits] }
32
+ : undefined,
33
})
34
).pipe(Effect.map(session => session.session_id));
35
ts/packages/cli/src/models/project-keys.ts
+7
@@ -38,6 +38,13 @@ export const ProjectKeys = Schema.Struct({
38
email: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
39
Schema.fromKey('email')
40
),
41
+
42
+ /**
43
+ * Optional test user identifier used by CLI/e2e flows.
44
+ */
45
+ testUserId: Schema.propertySignature(OptionFromNullishOr(Schema.String, null)).pipe(
46
+ Schema.fromKey('test_user_id')
47
+ ),
48
}).annotations({
49
identifier: 'ProjectKeys',
50
description: 'Organization and project identifiers for a CLI project profile',
ts/packages/cli/src/services/composio-clients.ts
+116
-12
@@ -27,6 +27,7 @@ import {
27
import { Session, RetrievedSession } from 'src/models/session';
28
import { TriggerType, TriggerTypes, TriggerTypesAsEnums } from 'src/models/trigger-types';
29
import { ComposioUserContext, ComposioUserContextLive } from './user-context';
30
+import { ProjectContext } from './project-context';
31
import type { NoSuchElementException } from 'effect/Cause';
32
import { renderPrettyError } from './utils/pretty-error';
33
@@ -358,19 +359,28 @@ export const SessionInfoResponse = Schema.Struct({
359
}),
360
org_member: Schema.Struct({
361
id: Schema.String,
362
+ user_id: Schema.optional(Schema.String),
363
email: Schema.String,
364
name: Schema.String,
365
role: Schema.String,
366
}),
365
- api_key: Schema.Struct({
366
- name: Schema.String,
367
- project_id: Schema.String,
368
- id: Schema.String,
369
- org_member_id: Schema.String,
370
- }),
367
+ api_key: Schema.NullOr(
368
+ Schema.Struct({
369
+ name: Schema.String,
370
+ project_id: Schema.String,
371
+ id: Schema.String,
372
+ org_member_id: Schema.String,
373
+ api_key: Schema.optional(Schema.String),
374
+ key: Schema.optional(Schema.String),
375
+ })
376
+ ),
377
}).annotations({ identifier: 'SessionInfoResponse' });
378
export type SessionInfoResponse = Schema.Schema.Type<typeof SessionInfoResponse>;
379
380
+const authHeaderForApiKey = (apiKey: string): Record<string, string> => ({
381
+ 'x-user-api-key': apiKey,
382
+});
383
+
384
export interface TriggerInstancesListActiveParams {
385
user_ids?: string[];
386
connected_account_ids?: string[];
@@ -708,8 +718,8 @@ export type OrgProjectListResponse = Schema.Schema.Type<typeof OrgProjectListRes
718
*
719
* @param params.baseURL - API base URL
720
* @param params.apiKey - UAK (sent as `x-user-api-key`)
711
- * @param params.orgId - Organization ID (sent as `x-composio-org-id`)
712
- * @param params.projectId - Project ID (sent as `x-composio-project-id`)
721
+ * @param params.orgId - Organization ID (sent as `x-org-id`)
722
+ * @param params.projectId - Project ID (sent as `x-project-id`)
723
* @param params.limit - Max projects to return (default 100)
724
*/
725
export const listOrgProjects = (params: {
@@ -730,8 +740,8 @@ export const listOrgProjects = (params: {
740
redirect: 'error',
741
headers: {
742
'x-user-api-key': params.apiKey,
733
- 'x-composio-org-id': params.orgId,
734
- 'x-composio-project-id': params.projectId,
743
+ 'x-org-id': params.orgId,
744
+ 'x-project-id': params.projectId,
745
'User-Agent': '@composio/cli',
746
Accept: 'application/json',
747
'Content-Type': 'application/json',
@@ -777,7 +787,7 @@ export const getSessionInfo = (params: {
787
method: 'GET',
788
redirect: 'error',
789
headers: {
780
- 'x-api-key': params.apiKey,
790
+ ...authHeaderForApiKey(params.apiKey),
791
'x-org-id': params.orgId,
792
'x-project-id': params.projectId,
793
'User-Agent': '@composio/cli',
@@ -849,6 +859,82 @@ export const getSessionInfoByUserApiKey = (params: {
859
);
860
});
861
862
+const getApiKeyFromPayload = (payload: unknown): string | undefined => {
863
+ const candidates = new Set<string>(['api_key', 'apiKey', 'key', 'token']);
864
+ const keyPrefixes = ['uak_', 'ak_'];
865
+ const queue: unknown[] = [payload];
866
+
867
+ while (queue.length > 0) {
868
+ const current = queue.shift();
869
+ if (!current || typeof current !== 'object') continue;
870
+
871
+ if (Array.isArray(current)) {
872
+ queue.push(...current);
873
+ continue;
874
+ }
875
+
876
+ const entries = Object.entries(current as Record<string, unknown>);
877
+ for (const [key, value] of entries) {
878
+ if (
879
+ typeof value === 'string' &&
880
+ candidates.has(key) &&
881
+ keyPrefixes.some(prefix => value.startsWith(prefix))
882
+ ) {
883
+ return value;
884
+ }
885
+ if (value && typeof value === 'object') {
886
+ queue.push(value);
887
+ }
888
+ }
889
+ }
890
+
891
+ return undefined;
892
+};
893
+
894
+export const createProjectApiKey = (params: {
895
+ baseURL: string;
896
+ apiKey: string;
897
+ orgId: string;
898
+ projectId: string;
899
+ name: string;
900
+}): Effect.Effect<string, HttpServerError | HttpDecodingError> =>
901
+ Effect.gen(function* () {
902
+ const response = yield* Effect.tryPromise({
903
+ try: () =>
904
+ fetch(`${params.baseURL}/api/v3/org/project/${params.projectId}/api_keys/create`, {
905
+ method: 'POST',
906
+ redirect: 'error',
907
+ headers: {
908
+ ...authHeaderForApiKey(params.apiKey),
909
+ 'x-org-id': params.orgId,
910
+ 'x-project-id': params.projectId,
911
+ 'User-Agent': '@composio/cli',
912
+ Accept: '*/*',
913
+ 'Content-Type': 'application/json',
914
+ },
915
+ body: JSON.stringify({ name: params.name }),
916
+ }),
917
+ catch: error => new HttpServerError({ cause: error }),
918
+ });
919
+
920
+ if (!response.ok) {
921
+ return yield* handleHttpErrorResponse(response);
922
+ }
923
+
924
+ const { json } = yield* streamResponseWithByteCount(response);
925
+ const createdApiKey = getApiKeyFromPayload(json);
926
+
927
+ if (!createdApiKey) {
928
+ return yield* Effect.fail(
929
+ new HttpDecodingError({
930
+ cause: 'Create API key response did not contain an API key',
931
+ })
932
+ );
933
+ }
934
+
935
+ return createdApiKey;
936
+ });
937
+
938
// Utility function for calling the Composio API and decoding its response.
939
// eslint-disable-next-line @typescript-eslint/no-explicit-any
940
const callClient = <T, S extends Schema.Schema<any, any>>(
@@ -1006,6 +1092,7 @@ export class ComposioClientSingleton extends Effect.Service<ComposioClientSingle
1092
accessors: true,
1093
effect: Effect.gen(function* () {
1094
const ctx = yield* ComposioUserContext;
1095
+ const projectContextOpt = yield* Effect.serviceOption(ProjectContext);
1096
let ref = Option.none<_RawComposioClient>();
1097
1098
return {
@@ -1017,9 +1104,26 @@ export class ComposioClientSingleton extends Effect.Service<ComposioClientSingle
1104
// Note: `api_key` is not required in every API request.
1105
const apiKey = ctx.data.apiKey.pipe(Option.getOrUndefined);
1106
const baseURL = ctx.data.baseURL;
1107
+ const resolvedProjectContext = yield* Option.match(projectContextOpt, {
1108
+ onNone: () => Effect.succeed(Option.none()),
1109
+ onSome: projectContext =>
1110
+ projectContext.resolve.pipe(Effect.catchAll(() => Effect.succeed(Option.none()))),
1111
+ });
1112
+ const defaultHeaders = Option.match(resolvedProjectContext, {
1113
+ onNone: () => undefined,
1114
+ onSome: keys =>
1115
+ ({
1116
+ 'x-org-id': keys.orgId,
1117
+ 'x-project-id': keys.projectId,
1118
+ }) satisfies Record<string, string>,
1119
+ });
1120
1121
yield* Effect.logDebug('Creating raw Composio client...');
1022
- const client = new _RawComposioClient({ apiKey, baseURL });
1122
+ const client = new _RawComposioClient({
1123
+ apiKey,
1124
+ baseURL,
1125
+ defaultHeaders,
1126
+ });
1127
1128
ref = Option.some(client);
1129
return client;
ts/packages/cli/src/services/project-context.ts
+2
@@ -75,6 +75,7 @@ export class ProjectContext extends Effect.Service<ProjectContext>()('services/P
75
projectName: Option.none(),
76
orgName: Option.none(),
77
email: Option.none(),
78
+ testUserId: Option.none(),
79
});
80
}
81
@@ -105,6 +106,7 @@ export class ProjectContext extends Effect.Service<ProjectContext>()('services/P
106
projectName: Option.none(),
107
orgName: Option.none(),
108
email: Option.none(),
109
+ testUserId: Option.none(),
110
});
111
}
112
}
ts/packages/cli/test/__utils__/services/test-layer.ts
+71
@@ -49,11 +49,13 @@ import type {
49
SessionExecuteResponse,
50
SessionExecuteMetaResponse,
51
SessionLinkResponse,
52
+ SessionSearchResponse,
53
SessionToolkitsResponse,
54
SessionCreateParams,
55
SessionExecuteParams,
56
SessionExecuteMetaParams,
57
SessionLinkParams,
58
+ SessionSearchParams,
59
SessionToolkitsParams,
60
} from '@composio/client/resources/tool-router';
61
import { Stdin } from 'src/services/stdin';
@@ -163,6 +165,8 @@ export interface TestLiveInput {
165
) => Promise<SessionExecuteMetaResponse>;
166
/** Override `session.link`. Receives sessionId and params. */
167
link?: (sessionId: string, params: SessionLinkParams) => Promise<SessionLinkResponse>;
168
+ /** Override `session.search`. Receives sessionId and params. */
169
+ search?: (sessionId: string, params: SessionSearchParams) => Promise<SessionSearchResponse>;
170
/** Override `session.toolkits`. Receives sessionId and optional params. */
171
toolkits?: (
172
sessionId: string,
@@ -795,6 +799,72 @@ export const TestLayer = (input?: TestLiveInput) =>
799
};
800
};
801
802
+ const defaultSearchHandler = async (
803
+ _sessionId: string,
804
+ params: SessionSearchParams
805
+ ): Promise<SessionSearchResponse> => {
806
+ const queryUseCase = params.queries[0]?.use_case ?? '';
807
+ const normalizedQuery = queryUseCase.toLowerCase();
808
+ const matchedTools = toolkitsData.tools.filter(
809
+ tool =>
810
+ tool.name.toLowerCase().includes(normalizedQuery) ||
811
+ tool.slug.toLowerCase().includes(normalizedQuery) ||
812
+ tool.description.toLowerCase().includes(normalizedQuery)
813
+ );
814
+
815
+ const primaryToolSlugs = matchedTools.map(tool => tool.slug);
816
+ const toolSchemas = Object.fromEntries(
817
+ matchedTools.map(tool => [
818
+ tool.slug,
819
+ {
820
+ tool_slug: tool.slug,
821
+ toolkit: tool.slug.split('_')[0]?.toLowerCase() ?? '',
822
+ description: tool.description,
823
+ hasFullSchema: true,
824
+ input_schema: tool.input_parameters,
825
+ output_schema: tool.output_parameters,
826
+ },
827
+ ])
828
+ );
829
+ const toolkitConnectionStatuses = Array.from(
830
+ new Set(
831
+ matchedTools.map(tool => tool.slug.split('_')[0]?.toLowerCase() ?? '').filter(Boolean)
832
+ )
833
+ ).map(toolkitSlug => ({
834
+ toolkit: toolkitSlug,
835
+ description: `${toolkitSlug} toolkit`,
836
+ has_active_connection: false,
837
+ status_message: 'No active connection',
838
+ }));
839
+
840
+ return {
841
+ success: true,
842
+ error: null,
843
+ results: [
844
+ {
845
+ index: 1,
846
+ use_case: queryUseCase,
847
+ primary_tool_slugs: primaryToolSlugs,
848
+ related_tool_slugs: [],
849
+ toolkits: toolkitConnectionStatuses.map(t => t.toolkit),
850
+ },
851
+ ],
852
+ tool_schemas: toolSchemas,
853
+ toolkit_connection_statuses: toolkitConnectionStatuses,
854
+ next_steps_guidance: [],
855
+ session: {
856
+ id: 'trs_test_session',
857
+ generate_id: false,
858
+ instructions: 'Reuse this session id for follow-up calls.',
859
+ },
860
+ time_info: {
861
+ current_time_utc: '2026-01-01T00:00:00.000Z',
862
+ current_time_utc_epoch_seconds: 1767225600,
863
+ message: 'UTC time',
864
+ },
865
+ };
866
+ };
867
+
868
const mockComposioClient = {
869
toolRouter: {
870
session: {
@@ -827,6 +897,7 @@ export const TestLayer = (input?: TestLiveInput) =>
897
link_token: 'lt_test_token',
898
redirect_url: 'https://app.composio.dev/link?token=lt_test_token',
899
})),
900
+ search: toolRouterOverrides?.search ?? defaultSearchHandler,
901
toolkits: toolRouterOverrides?.toolkits ?? defaultToolkitsHandler,
902
tools: async () => ({
903
items: [],
ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap
+2
-2
@@ -35,7 +35,7 @@ Composio CLI - A tool for managing Python and TypeScript composio.dev projects.
35
36
- logout Log out from the Composio SDK.
37
38
- - init [--org-id text] [--project-id text] [--no-browser] [--dry-run] [--force] [(-y, --yes)] [--no-skills] Initialize a Composio project in the current directory.
38
+ - init [--org-id text] [--project-id text] [--no-browser] [(-y, --yes)] Initialize a Composio project in the current directory.
39
40
- generate [(-o, --output-dir directory)] [--type-tools] --toolkits text... Generate type stubs for toolkits, tools, and triggers, auto-detecting project language (TypeScript | Python)
41
@@ -59,7 +59,7 @@ Environment Variables:
59
60
- toolkits list [--query text] [--limit integer] [--connected] [--user-id text] List available toolkits with connection status.
61
62
- - toolkits info [--user-id text] [<slug>] View details of a specific toolkit.
62
+ - toolkits info [--user-id text] [(-a, --all)] [<slug>] View details of a specific toolkit.
63
64
- toolkits search [--limit integer] <query> Search toolkits by use case.
65
ts/packages/cli/test/src/commands/connected-accounts/connected-accounts.link.cmd.test.ts
+4
-2
@@ -59,15 +59,17 @@ describe('CLI: composio connected-accounts link', () => {
59
);
60
61
layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(
62
- '[Given] valid --auth-config with default user-id [Then] creates link',
62
+ '[Given] valid --auth-config with explicit --user-id [Then] creates link',
63
it => {
64
- it.scoped('uses default user-id', () =>
64
+ it.scoped('uses explicit user-id', () =>
65
Effect.gen(function* () {
66
yield* cli([
67
'connected-accounts',
68
'link',
69
'--auth-config',
70
'ac_gmail_oauth',
71
+ '--user-id',
72
+ 'default',
73
'--no-browser',
74
]);
75
const lines = yield* MockConsole.getLines({ stripAnsi: true });
ts/packages/cli/test/src/commands/init.cmd.test.ts
+24
-484
@@ -1,512 +1,52 @@
1
import path from 'node:path';
2
import { describe, expect, layer } from '@effect/vitest';
3
-import { vi, afterEach, beforeAll, afterAll } from 'vitest';
4
-import { Console, Effect, Exit } from 'effect';
5
-import { CommandExecutor, FileSystem } from '@effect/platform';
3
+import { Effect } from 'effect';
4
+import { FileSystem } from '@effect/platform';
5
import { NodeProcess } from 'src/services/node-process';
7
-import { CommandRunner } from 'src/services/command-runner';
8
-import { TerminalUI } from 'src/services/terminal-ui';
6
import { cli, TestLive, MockConsole } from 'test/__utils__';
7
11
-// ── Helpers ──────────────────────────────────────────────────────────────────
12
-
13
-const makeSessionInfoBody = () => ({
14
- project: {
15
- name: 'test-project',
16
- id: 'proj_test_123',
17
- org_id: 'org_test_456',
18
- nano_id: 'pr_nano_789',
19
- email: 'test@composio.dev',
20
- created_at: '2026-01-01T00:00:00.000Z',
21
- updated_at: '2026-01-01T00:00:00.000Z',
22
- org: { name: 'Test Org', id: 'org_test_456', plan: 'free' },
23
- },
24
- org_member: {
25
- id: 'org_test_456',
26
- email: 'test@composio.dev',
27
- name: 'Test User',
28
- role: 'admin',
29
- },
30
- api_key: {
31
- name: 'default',
32
- project_id: 'proj_test_123',
33
- id: 'ak_test',
34
- org_member_id: 'org_test_456',
35
- },
36
-});
37
-
38
-function mockFetchResponse(body: unknown, status = 200): Response {
39
- return new Response(JSON.stringify(body), {
40
- status,
41
- headers: { 'Content-Type': 'application/json' },
42
- });
43
-}
44
-
45
-const makeCommandRunnerSuccess = () =>
46
- new CommandRunner({
47
- run: () => Effect.succeed(CommandExecutor.ExitCode(0)),
48
- });
49
-
50
-const makeCommandRunnerFail = (exitCode = 1) =>
51
- new CommandRunner({
52
- run: () => Effect.succeed(CommandExecutor.ExitCode(exitCode)),
53
- });
54
-
55
-/**
56
- * Creates a TerminalUI where specific `select()` calls return custom values.
57
- * `selectOverrides` maps call index (0-based) to the option index to pick.
58
- * Calls without overrides default to picking the first option (index 0).
59
- */
60
-const makeTerminalUIWithSelectOverrides = (selectOverrides: Record<number, number>): TerminalUI => {
61
- let selectCallIndex = 0;
62
-
63
- return TerminalUI.of({
64
- output: data => Console.log(data),
65
- intro: title => Console.log(`-- ${title} --`),
66
- outro: message => Console.log(`-- ${message} --`),
67
- log: {
68
- info: message => Console.log(message),
69
- success: message => Console.log(message),
70
- warn: message => Console.warn(message),
71
- error: message => Console.error(message),
72
- step: message => Console.log(message),
73
- message: message => Console.log(message),
74
- },
75
- note: (message, title) => Console.log(title ? `[${title}] ${message}` : message),
76
- select: (_message, options) => {
77
- const idx = selectCallIndex++;
78
- const optionIdx = selectOverrides[idx] ?? 0;
79
- return Effect.succeed(options[optionIdx].value);
80
- },
81
- confirm: (_message, options) => Effect.succeed(options?.defaultValue ?? true),
82
- withSpinner: (message, effect, options) =>
83
- Effect.gen(function* () {
84
- const result = yield* effect;
85
- const successMsg =
86
- typeof options?.successMessage === 'function'
87
- ? options.successMessage(result)
88
- : (options?.successMessage ?? message);
89
- yield* Console.log(successMsg);
90
- return result;
91
- }),
92
- useMakeSpinner: (message, use) =>
93
- Effect.gen(function* () {
94
- let stopped = false;
95
- const handle = {
96
- message: (_msg: string) => Effect.void,
97
- stop: (msg?: string) =>
98
- Effect.gen(function* () {
99
- stopped = true;
100
- if (msg) yield* Console.log(msg);
101
- }),
102
- error: (msg?: string) =>
103
- Effect.gen(function* () {
104
- stopped = true;
105
- if (msg) yield* Console.error(msg);
106
- }),
107
- };
108
- const exit = yield* Effect.exit(use(handle));
109
- if (Exit.isFailure(exit) && !stopped) {
110
- yield* Console.error(message);
111
- }
112
- return yield* exit;
113
- }),
114
- });
115
-};
116
-
117
-// ── Tests ────────────────────────────────────────────────────────────────────
118
-
8
describe('CLI: composio init', () => {
120
- let savedUserAgent: string | undefined;
121
-
122
- beforeAll(() => {
123
- savedUserAgent = process.env.npm_config_user_agent;
124
- delete process.env.npm_config_user_agent;
125
- });
126
-
127
- afterAll(() => {
128
- if (savedUserAgent !== undefined) {
129
- process.env.npm_config_user_agent = savedUserAgent;
130
- } else {
131
- delete process.env.npm_config_user_agent;
132
- }
133
- });
134
-
135
- afterEach(() => {
136
- vi.restoreAllMocks();
137
- });
138
-
139
- describe('[Given] --org-id + --project-id flags with TS project', () => {
140
- layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(
141
- it => {
142
- it.scoped('[Then] detects TS project and installs dependency', () =>
143
- Effect.gen(function* () {
144
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(
145
- mockFetchResponse(makeSessionInfoBody())
146
- );
147
-
148
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
149
- yield* cli(args);
150
-
151
- const lines = yield* MockConsole.getLines();
152
- const output = lines.join('\n');
153
-
154
- expect(output).toContain('typescript');
155
- expect(output).toContain('Installed @composio/core');
156
- })
157
- );
158
- }
159
- );
160
- });
161
-
162
- describe('[Given] --org-id + --project-id flags with Python project', () => {
163
- layer(TestLive({ fixture: 'python-project', commandRunner: makeCommandRunnerSuccess() }))(
164
- it => {
165
- it.scoped('[Then] detects Python project and shows correct install command', () =>
166
- Effect.gen(function* () {
167
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(
168
- mockFetchResponse(makeSessionInfoBody())
169
- );
170
-
171
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];
172
- yield* cli(args);
173
-
174
- const lines = yield* MockConsole.getLines();
175
- const output = lines.join('\n');
176
-
177
- expect(output).toContain('python');
178
- expect(output).toContain('pip install composio');
179
- expect(output).toContain('Dry run complete.');
180
- })
181
- );
182
- }
183
- );
184
- });
185
-
186
- describe('[Given] --dry-run flag with TS project', () => {
9
+ describe('[Given] --org-id + --project-id flags', () => {
10
layer(TestLive({ fixture: 'typescript-project' }))(it => {
188
- it.scoped('[Then] prints install command without executing', () =>
11
+ it.scoped('[Then] it initializes project config and prints machine output', () =>
12
Effect.gen(function* () {
190
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
191
-
192
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];
193
- yield* cli(args);
194
-
195
- const lines = yield* MockConsole.getLines();
196
- const output = lines.join('\n');
197
-
198
- expect(output).toContain('npm install -S @composio/core');
199
- expect(output).toContain('Dry run complete.');
200
- expect(output).not.toContain('Installed @composio/core');
201
- })
202
- );
203
- });
204
- });
205
-
206
- describe('[Given] @composio/core already in node_modules', () => {
207
- layer(
208
- TestLive({
209
- fixture: 'typescript-project-with-composio-core',
210
- commandRunner: makeCommandRunnerSuccess(),
211
- })
212
- )(it => {
213
- it.scoped('[Then] skips install', () =>
214
- Effect.gen(function* () {
215
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
216
-
217
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1'];
218
- yield* cli(args);
219
-
220
- const lines = yield* MockConsole.getLines();
221
- const output = lines.join('\n');
222
-
223
- expect(output).toContain('Dependency already installed');
224
- expect(output).not.toContain('Installed @composio/core');
225
- })
226
- );
227
- });
228
- });
229
-
230
- describe('[Given] --force flag with dependency installed', () => {
231
- layer(
232
- TestLive({
233
- fixture: 'typescript-project-with-composio-core',
234
- commandRunner: makeCommandRunnerSuccess(),
235
- })
236
- )(it => {
237
- it.scoped('[Then] reinstalls', () =>
238
- Effect.gen(function* () {
239
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
240
-
241
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--force', '--yes'];
242
- yield* cli(args);
243
-
244
- const lines = yield* MockConsole.getLines();
245
- const output = lines.join('\n');
246
-
247
- expect(output).toContain('Reinstalling due to --force');
248
- expect(output).toContain('Installed @composio/core');
249
- })
250
- );
251
- });
252
- });
253
-
254
- describe('[Given] install command fails', () => {
255
- layer(
256
- TestLive({
257
- fixture: 'typescript-project',
258
- commandRunner: makeCommandRunnerFail(1),
259
- })
260
- )(it => {
261
- it.scoped('[Then] shows error and suggests manual install', () =>
262
- Effect.gen(function* () {
263
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
13
+ const fs = yield* FileSystem.FileSystem;
14
+ const proc = yield* NodeProcess;
15
265
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
266
- yield* cli(args);
16
+ yield* cli(['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes']);
17
268
- const lines = yield* MockConsole.getLines();
18
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
19
const output = lines.join('\n');
20
271
- expect(output).toContain('Install failed');
272
- expect(output).toContain('install manually');
273
- })
274
- );
275
- });
276
- });
277
-
278
- describe('[Given] pnpm monorepo fixture', () => {
279
- layer(
280
- TestLive({
281
- fixture: 'typescript-pnpm-monorepo',
282
- commandRunner: makeCommandRunnerSuccess(),
283
- })
284
- )(it => {
285
- it.scoped('[Then] detects pnpm and uses pnpm add', () =>
286
- Effect.gen(function* () {
287
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
288
-
289
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];
290
- yield* cli(args);
21
+ expect(output).toContain('-- composio init --');
22
+ expect(output).toContain('Project initialized in');
23
+ expect(output).toContain('"org_id":"org1"');
24
+ expect(output).toContain('"project_id":"proj1"');
25
292
- const lines = yield* MockConsole.getLines();
293
- const output = lines.join('\n');
26
+ const projectConfigPath = path.join(proc.cwd, '.composio', 'project.json');
27
+ const exists = yield* fs.exists(projectConfigPath);
28
+ expect(exists).toBe(true);
29
295
- expect(output).toContain('pnpm');
296
- expect(output).toContain('pnpm add @composio/core');
30
+ const projectConfigRaw = yield* fs.readFileString(projectConfigPath, 'utf8');
31
+ const projectConfig = JSON.parse(projectConfigRaw) as Record<string, unknown>;
32
+ expect(projectConfig.org_id).toBe('org1');
33
+ expect(projectConfig.project_id).toBe('proj1');
34
})
35
);
36
});
37
});
38
302
- // ── Skills installation tests ──────────────────────────────────────────────
303
-
304
- describe('[Given] skills install with --yes flag', () => {
305
- layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(
306
- it => {
307
- it.scoped('[Then] installs Composio skills', () =>
308
- Effect.gen(function* () {
309
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(
310
- mockFetchResponse(makeSessionInfoBody())
311
- );
312
-
313
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
314
- yield* cli(args);
315
-
316
- const lines = yield* MockConsole.getLines();
317
- const output = lines.join('\n');
318
-
319
- expect(output).toContain('Installed Composio skills');
320
- })
321
- );
322
- }
323
- );
324
- });
325
-
326
- describe('[Given] --dry-run flag shows skills command', () => {
39
+ describe('[Given] explicit project ids but no global credentials', () => {
40
layer(TestLive({ fixture: 'typescript-project' }))(it => {
328
- it.scoped('[Then] prints skills install command without executing', () =>
329
- Effect.gen(function* () {
330
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
331
-
332
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--dry-run'];
333
- yield* cli(args);
334
-
335
- const lines = yield* MockConsole.getLines();
336
- const output = lines.join('\n');
337
-
338
- expect(output).toContain('npx skills add composiohq/skills');
339
- expect(output).not.toContain('Installed Composio skills');
340
- })
341
- );
342
- });
343
- });
344
-
345
- describe('[Given] skills install command fails', () => {
346
- layer(
347
- TestLive({
348
- fixture: 'typescript-project',
349
- commandRunner: makeCommandRunnerFail(1),
350
- })
351
- )(it => {
352
- it.scoped('[Then] shows error and suggests manual skills install', () =>
41
+ it.scoped('[Then] it warns and skips .env.local creation', () =>
42
Effect.gen(function* () {
354
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
355
-
356
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
357
- yield* cli(args);
43
+ yield* cli(['init', '--org-id', 'org1', '--project-id', 'proj1']);
44
359
- const lines = yield* MockConsole.getLines();
45
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
46
const output = lines.join('\n');
361
-
362
- expect(output).toContain('Skills install failed');
363
- expect(output).toContain('npx skills add composiohq/skills');
47
+ expect(output).toContain('No global API key found; skipping .env.local creation.');
48
})
49
);
50
});
51
});
368
-
369
- // ── --no-skills flag tests ─────────────────────────────────────────────────
370
-
371
- describe('[Given] --no-skills flag', () => {
372
- layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(
373
- it => {
374
- it.scoped('[Then] skips skills prompt and does not install skills', () =>
375
- Effect.gen(function* () {
376
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(
377
- mockFetchResponse(makeSessionInfoBody())
378
- );
379
-
380
- const proc = yield* NodeProcess;
381
- const fs = yield* FileSystem.FileSystem;
382
- const args = [
383
- 'init',
384
- '--org-id',
385
- 'org1',
386
- '--project-id',
387
- 'proj1',
388
- '--yes',
389
- '--no-skills',
390
- ];
391
- yield* cli(args);
392
-
393
- const lines = yield* MockConsole.getLines();
394
- const output = lines.join('\n');
395
-
396
- // Should NOT install skills
397
- expect(output).not.toContain('Installed Composio skills');
398
- // Should still install the core dependency
399
- expect(output).toContain('Installed @composio/core');
400
-
401
- // config.json should have install_skills: false
402
- const configPath = path.join(proc.cwd, '.composio', 'config.json');
403
- const configContent = yield* fs.readFileString(configPath);
404
- const config = JSON.parse(configContent);
405
- expect(config.install_skills).toBe(false);
406
- })
407
- );
408
- }
409
- );
410
- });
411
-
412
- // ── MCP mode and PM-skip tests ─────────────────────────────────────────────
413
-
414
- describe('[Given] MCP usage mode selected', () => {
415
- // Select overrides: 0th select (usage mode) → index 1 ("Composio MCP")
416
- const mcpUI = makeTerminalUIWithSelectOverrides({ 0: 1 });
417
-
418
- layer(
419
- TestLive({
420
- fixture: 'typescript-project',
421
- commandRunner: makeCommandRunnerSuccess(),
422
- terminalUI: mcpUI,
423
- })
424
- )(it => {
425
- it.scoped('[Then] skips env detection and dependency install', () =>
426
- Effect.gen(function* () {
427
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
428
-
429
- const proc = yield* NodeProcess;
430
- const fs = yield* FileSystem.FileSystem;
431
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
432
- yield* cli(args);
433
-
434
- const lines = yield* MockConsole.getLines();
435
- const output = lines.join('\n');
436
-
437
- // Should NOT detect environment or install dependency in MCP mode
438
- expect(output).not.toContain('Detected:');
439
- expect(output).not.toContain('Installed @composio/core');
440
- expect(output).toContain('Project initialized');
441
-
442
- // config.json should not have detected_language or package_manager
443
- const configPath = path.join(proc.cwd, '.composio', 'config.json');
444
- const configContent = yield* fs.readFileString(configPath);
445
- const config = JSON.parse(configContent);
446
- expect(config.usage_mode).toBe('mcp');
447
- expect(config.detected_language).toBeUndefined();
448
- expect(config.package_manager).toBeUndefined();
449
- })
450
- );
451
- });
452
- });
453
-
454
- describe('[Given] native mode but user skips PM confirmation', () => {
455
- // Select overrides:
456
- // 0th select (usage mode) → index 0 ("Native tools")
457
- // 1st select (framework) → index 0 ("Skip")
458
- // 2nd select (PM confirm) → index 1 ("Skip")
459
- const skipPmUI = makeTerminalUIWithSelectOverrides({ 2: 1 });
460
-
461
- layer(
462
- TestLive({
463
- fixture: 'typescript-project',
464
- commandRunner: makeCommandRunnerSuccess(),
465
- terminalUI: skipPmUI,
466
- })
467
- )(it => {
468
- it.scoped('[Then] detects env but skips dependency install', () =>
469
- Effect.gen(function* () {
470
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockFetchResponse(makeSessionInfoBody()));
471
-
472
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
473
- yield* cli(args);
474
-
475
- const lines = yield* MockConsole.getLines();
476
- const output = lines.join('\n');
477
-
478
- // Should detect environment but NOT install dependency
479
- expect(output).toContain('Detected:');
480
- expect(output).not.toContain('Installed @composio/core');
481
- expect(output).toContain('Project initialized');
482
- })
483
- );
484
- });
485
- });
486
-
487
- describe('[Given] config files are written', () => {
488
- layer(TestLive({ fixture: 'typescript-project', commandRunner: makeCommandRunnerSuccess() }))(
489
- it => {
490
- it.scoped('[Then] config.json includes detection info', () =>
491
- Effect.gen(function* () {
492
- vi.spyOn(globalThis, 'fetch').mockResolvedValue(
493
- mockFetchResponse(makeSessionInfoBody())
494
- );
495
-
496
- const proc = yield* NodeProcess;
497
- const fs = yield* FileSystem.FileSystem;
498
- const args = ['init', '--org-id', 'org1', '--project-id', 'proj1', '--yes'];
499
- yield* cli(args);
500
-
501
- const configPath = path.join(proc.cwd, '.composio', 'config.json');
502
- const configContent = yield* fs.readFileString(configPath);
503
- const config = JSON.parse(configContent);
504
-
505
- expect(config.detected_language).toBeDefined();
506
- expect(config.package_manager).toBeDefined();
507
- })
508
- );
509
- }
510
- );
511
- });
52
});
ts/packages/cli/test/src/commands/login.cmd.test.ts
+1
-1
@@ -101,7 +101,7 @@ describe('CLI: composio login', () => {
101
const [url, init] = fetchSpy.mock.calls[0]!;
102
expect(url).toContain('/api/v3/auth/session/info');
103
expect((init as RequestInit).headers).toMatchObject({
104
- 'x-api-key': 'uak_test_key',
104
+ 'x-user-api-key': 'uak_test_key',
105
'x-org-id': 'org_initial',
106
'x-project-id': 'proj_initial',
107
});
ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.ts
+26
@@ -142,6 +142,11 @@ describe('CLI: composio toolkits info', () => {
142
expect(output).toContain('Gmail');
143
expect(output).toContain('gmail');
144
expect(output).toContain('Email service to send and receive emails');
145
+ expect(output).toContain('Latest Version:');
146
+ expect(output).toContain('20250909');
147
+ expect(output).toContain('Tools Count: 36');
148
+ expect(output).toContain('Triggers Count: 2');
149
+ expect(output).toContain('Auth Modes: OAUTH2, BEARER_TOKEN');
150
// Connection status
151
expect(output).toContain('Not connected');
152
})
@@ -159,12 +164,33 @@ describe('CLI: composio toolkits info', () => {
164
const output = lines.join('\n');
165
166
expect(output).toContain('Code Interpreter');
167
+ expect(output).toContain('Execute code snippets');
168
+ expect(output).toContain('Tools Count: 5');
169
expect(output).toContain('No authentication required');
170
})
171
);
172
}
173
);
174
175
+ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
176
+ '[Given] --all flag',
177
+ it => {
178
+ it.scoped('shows full auth config setup fields', () =>
179
+ Effect.gen(function* () {
180
+ yield* cli(['toolkits', 'info', 'gmail', '--all']);
181
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
182
+ const output = lines.join('\n');
183
+
184
+ expect(output).toContain('Auth Config Details:');
185
+ expect(output).toContain('auth_config_creation.required');
186
+ expect(output).toContain('connected_account_initiation.required');
187
+ expect(output).toContain('apiKey');
188
+ expect(output).toContain('API Key');
189
+ })
190
+ );
191
+ }
192
+ );
193
+
194
layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
195
'[Given] invalid slug',
196
it => {
ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts
+20
-3
@@ -69,9 +69,9 @@ const testConfigProvider = ConfigProvider.fromMap(
69
70
describe('CLI: composio toolkits list', () => {
71
layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
72
- '[Given] no flags [Then] lists all toolkits',
72
+ '[Given] no flags [Then] lists all toolkits without connected status',
73
it => {
74
- it.scoped('lists all toolkits', () =>
74
+ it.scoped('lists all toolkits without connected column', () =>
75
Effect.gen(function* () {
76
yield* cli(['toolkits', 'list']);
77
const lines = yield* MockConsole.getLines({ stripAnsi: true });
@@ -81,7 +81,24 @@ describe('CLI: composio toolkits list', () => {
81
expect(output).toContain('gmail');
82
expect(output).toContain('Slack');
83
expect(output).toContain('GitHub');
84
- // Connection status column
84
+ // Legacy table fallback removes connection status when no user id is available.
85
+ expect(output).not.toContain('Connected');
86
+ expect(output).toContain('Version');
87
+ expect(output).toContain('Listing 3 of 3 toolkits');
88
+ })
89
+ );
90
+ }
91
+ );
92
+
93
+ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
94
+ '[Given] explicit --user-id [Then] shows connected status column',
95
+ it => {
96
+ it.scoped('shows connected column with explicit user id', () =>
97
+ Effect.gen(function* () {
98
+ yield* cli(['toolkits', 'list', '--user-id', 'default']);
99
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
100
+ const output = lines.join('\n');
101
+
102
expect(output).toContain('Connected');
103
expect(output).toContain('Listing 3 of 3 toolkits');
104
})
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+62
-14
@@ -48,7 +48,15 @@ describe('CLI: composio tools execute', () => {
48
)('[Given] -d inline JSON [Then] executes via Tool Router with defaults', it => {
49
it.scoped('executes via Tool Router with defaults', () =>
50
Effect.gen(function* () {
51
- yield* cli(['tools', 'execute', 'GMAIL_SEND_EMAIL', '-d', '{"recipient":"a"}']);
51
+ yield* cli([
52
+ 'tools',
53
+ 'execute',
54
+ 'GMAIL_SEND_EMAIL',
55
+ '--user-id',
56
+ 'default',
57
+ '-d',
58
+ '{"recipient":"a"}',
59
+ ]);
60
const lines = yield* MockConsole.getLines({ stripAnsi: true });
61
const output = parseLastJson(lines);
62
@@ -69,7 +77,7 @@ describe('CLI: composio tools execute', () => {
77
)('[Given] stdin is piped [Then] reads input from stdin', it => {
78
it.scoped('reads stdin input', () =>
79
Effect.gen(function* () {
72
- yield* cli(['tools', 'execute', 'GITHUB_GET_REPOS']);
80
+ yield* cli(['tools', 'execute', 'GITHUB_GET_REPOS', '--user-id', 'default']);
81
const lines = yield* MockConsole.getLines({ stripAnsi: true });
82
const output = parseLastJson(lines);
83
@@ -98,6 +106,8 @@ describe('CLI: composio tools execute', () => {
106
'tools',
107
'execute',
108
'GMAIL_CREATE_EMAIL_DRAFT',
109
+ '--user-id',
110
+ 'default',
111
'-d',
112
'{\"recipient\":\"to@example.com\"}',
113
]).pipe(Effect.catchAll(() => Effect.void));
@@ -138,6 +148,8 @@ describe('CLI: composio tools execute', () => {
148
'tools',
149
'execute',
150
'GMAIL_CREATE_EMAIL_DRAFT',
151
+ '--user-id',
152
+ 'default',
153
'-d',
154
'{"recipient":"to@example.com"}',
155
]).pipe(Effect.catchAll(() => Effect.void));
@@ -170,6 +182,8 @@ describe('CLI: composio tools execute', () => {
182
'tools',
183
'execute',
184
'GITHUB_STAR_REPO',
185
+ '--user-id',
186
+ 'default',
187
'-d',
188
'{"owner":"composio","repo":"composio"}',
189
]);
@@ -203,6 +217,8 @@ describe('CLI: composio tools execute', () => {
217
'tools',
218
'execute',
219
'GMAIL_CREATE_EMAIL_DRAFT',
220
+ '--user-id',
221
+ 'default',
222
'-d',
223
'{\"recipient\":\"to@example.com\"}',
224
]).pipe(Effect.catchAll(() => Effect.void));
@@ -229,6 +245,8 @@ describe('CLI: composio tools execute', () => {
245
'tools',
246
'execute',
247
'GMAIL_CREATE_EMAIL_DRAFT',
248
+ '--user-id',
249
+ 'default',
250
'-d',
251
'{\"recipient\":\"to@example.com\"}',
252
]).pipe(Effect.catchAll(() => Effect.void));
@@ -264,6 +282,8 @@ describe('CLI: composio tools execute', () => {
282
'tools',
283
'execute',
284
'GMAIL_CREATE_EMAIL_DRAFT',
285
+ '--user-id',
286
+ 'default',
287
'-d',
288
'{\"recipient\":\"to@example.com\"}',
289
]).pipe(Effect.catchAll(() => Effect.void));
@@ -300,6 +320,8 @@ describe('CLI: composio tools execute', () => {
320
'tools',
321
'execute',
322
'GMAIL_CREATE_EMAIL_DRAFT',
323
+ '--user-id',
324
+ 'default',
325
'-d',
326
'{\"recipient\":\"to@example.com\"}',
327
]).pipe(Effect.catchAll(() => Effect.void));
@@ -332,9 +354,15 @@ describe('CLI: composio tools execute', () => {
354
)('[Given] meta tool NoActiveConnection error [Then] does not suggest "link composio"', it => {
355
it.scoped('omits connection tips for meta tool slugs', () =>
356
Effect.gen(function* () {
335
- yield* cli(['tools', 'execute', 'COMPOSIO_SEARCH_TOOLS', '-d', '{"query":"email"}']).pipe(
336
- Effect.catchAll(() => Effect.void)
337
- );
357
+ yield* cli([
358
+ 'tools',
359
+ 'execute',
360
+ 'COMPOSIO_SEARCH_TOOLS',
361
+ '--user-id',
362
+ 'default',
363
+ '-d',
364
+ '{"query":"email"}',
365
+ ]).pipe(Effect.catchAll(() => Effect.void));
366
const lines = yield* MockConsole.getLines({ stripAnsi: true });
367
const output = lines.join('\n');
368
@@ -359,6 +387,8 @@ describe('CLI: composio tools execute', () => {
387
'tools',
388
'execute',
389
'GMAIL_SEND_EMAIL',
390
+ '--user-id',
391
+ 'default',
392
'-d',
393
'not-valid-json',
394
]).pipe(Effect.catchAll(e => Effect.succeed(e)));
@@ -379,9 +409,15 @@ describe('CLI: composio tools execute', () => {
409
)('[Given] -d with JSON array [Then] fails with expected-object error', it => {
410
it.scoped('fails with expected object error', () =>
411
Effect.gen(function* () {
382
- const result = yield* cli(['tools', 'execute', 'GMAIL_SEND_EMAIL', '-d', '[1,2,3]']).pipe(
383
- Effect.catchAll(e => Effect.succeed(e))
384
- );
412
+ const result = yield* cli([
413
+ 'tools',
414
+ 'execute',
415
+ 'GMAIL_SEND_EMAIL',
416
+ '--user-id',
417
+ 'default',
418
+ '-d',
419
+ '[1,2,3]',
420
+ ]).pipe(Effect.catchAll(e => Effect.succeed(e)));
421
422
expect(result).toBeDefined();
423
expect(result instanceof Error ? result.message : String(result)).toContain(
@@ -403,6 +439,8 @@ describe('CLI: composio tools execute', () => {
439
'tools',
440
'execute',
441
'GMAIL_SEND_EMAIL',
442
+ '--user-id',
443
+ 'default',
444
'-d',
445
'"just a string"',
446
]).pipe(Effect.catchAll(e => Effect.succeed(e)));
@@ -423,9 +461,13 @@ describe('CLI: composio tools execute', () => {
461
)('[Given] no -d and TTY stdin [Then] fails with missing input error', it => {
462
it.scoped('fails with missing input error', () =>
463
Effect.gen(function* () {
426
- const result = yield* cli(['tools', 'execute', 'GMAIL_SEND_EMAIL']).pipe(
427
- Effect.catchAll(e => Effect.succeed(e))
428
- );
464
+ const result = yield* cli([
465
+ 'tools',
466
+ 'execute',
467
+ 'GMAIL_SEND_EMAIL',
468
+ '--user-id',
469
+ 'default',
470
+ ]).pipe(Effect.catchAll(e => Effect.succeed(e)));
471
472
expect(result).toBeDefined();
473
expect(result instanceof Error ? result.message : String(result)).toContain(
@@ -443,9 +485,13 @@ describe('CLI: composio tools execute', () => {
485
)('[Given] empty piped stdin [Then] fails with parse error', it => {
486
it.scoped('fails with error for empty stdin', () =>
487
Effect.gen(function* () {
446
- const result = yield* cli(['tools', 'execute', 'GMAIL_SEND_EMAIL']).pipe(
447
- Effect.catchAll(e => Effect.succeed(e))
448
- );
488
+ const result = yield* cli([
489
+ 'tools',
490
+ 'execute',
491
+ 'GMAIL_SEND_EMAIL',
492
+ '--user-id',
493
+ 'default',
494
+ ]).pipe(Effect.catchAll(e => Effect.succeed(e)));
495
496
expect(result).toBeDefined();
497
expect(result instanceof Error ? result.message : String(result)).toContain(
@@ -489,6 +535,8 @@ describe('CLI: composio tools execute', () => {
535
'tools',
536
'execute',
537
'GMAIL_SEND_EMAIL',
538
+ '--user-id',
539
+ 'default',
540
'-d',
541
'{"recipient_email":"to@example.com"}',
542
]);
ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+178
-3
@@ -1,5 +1,9 @@
1
import { describe, expect, layer } from '@effect/vitest';
2
import { ConfigProvider, Effect } from 'effect';
3
+import type {
4
+ SessionCreateParams,
5
+ SessionSearchParams,
6
+} from '@composio/client/resources/tool-router';
7
import { extendConfigProvider } from 'src/services/config';
8
import { cli, TestLive, MockConsole } from 'test/__utils__';
9
import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -85,10 +89,181 @@ describe('CLI: composio tools search', () => {
89
yield* cli(['tools', 'search', 'send', '--toolkits', 'gmail']);
90
const lines = yield* MockConsole.getLines({ stripAnsi: true });
91
const output = lines.join('\n');
92
+ const humanOutput = output.split('\n{')[0] ?? output;
93
89
- expect(output).toContain('GMAIL_SEND_EMAIL');
90
- expect(output).not.toContain('SLACK_SEND_MESSAGE');
91
- expect(output).toContain('Found 1 tools');
94
+ expect(humanOutput).toContain('GMAIL_SEND_EMAIL');
95
+ expect(humanOutput).not.toContain('SLACK_SEND_MESSAGE');
96
+ expect(humanOutput).toContain('Found 1 tools');
97
+ })
98
+ );
99
+ }
100
+ );
101
+
102
+ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
103
+ '[Given] tools search [Then] JSON output includes full tool-router payload',
104
+ it => {
105
+ it.scoped('prints full search response for jq', () =>
106
+ Effect.gen(function* () {
107
+ yield* cli(['tools', 'search', 'send']);
108
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
109
+ const output = lines.join('\n');
110
+
111
+ expect(output).toContain('"results"');
112
+ expect(output).toContain('"tool_schemas"');
113
+ expect(output).toContain('"toolkit_connection_statuses"');
114
+ expect(output).toContain('"session"');
115
+ expect(output).toContain('"time_info"');
116
+ })
117
+ );
118
+ }
119
+ );
120
+
121
+ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
122
+ '[Given] --toolkits filter [Then] it is passed to session create as enabled toolkits',
123
+ it => {
124
+ it.scoped('passes toolkit filter into tool router session', () =>
125
+ Effect.gen(function* () {
126
+ let createParams: SessionCreateParams | undefined;
127
+ let searchParams: SessionSearchParams | undefined;
128
+
129
+ const live = TestLive({
130
+ baseConfigProvider: testConfigProvider,
131
+ toolkitsData,
132
+ toolRouter: {
133
+ create: async params => {
134
+ createParams = params;
135
+ return {
136
+ session_id: 'trs_test_session',
137
+ config: { user_id: params.user_id },
138
+ mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
139
+ tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
140
+ };
141
+ },
142
+ search: async (_sessionId, params) => {
143
+ searchParams = params;
144
+ return {
145
+ success: true,
146
+ error: null,
147
+ results: [
148
+ {
149
+ index: 1,
150
+ use_case: params.queries[0]?.use_case ?? '',
151
+ primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
152
+ related_tool_slugs: [],
153
+ toolkits: ['gmail'],
154
+ },
155
+ ],
156
+ tool_schemas: {
157
+ GMAIL_SEND_EMAIL: {
158
+ tool_slug: 'GMAIL_SEND_EMAIL',
159
+ toolkit: 'gmail',
160
+ description: 'Sends an email',
161
+ hasFullSchema: true,
162
+ input_schema: { type: 'object', properties: {} },
163
+ output_schema: { type: 'object', properties: {} },
164
+ },
165
+ },
166
+ toolkit_connection_statuses: [
167
+ {
168
+ toolkit: 'gmail',
169
+ description: 'gmail toolkit',
170
+ has_active_connection: false,
171
+ status_message: 'No active connection',
172
+ },
173
+ ],
174
+ next_steps_guidance: [],
175
+ session: {
176
+ id: 'trs_test_session',
177
+ generate_id: false,
178
+ instructions: 'Reuse this session id for follow-up calls.',
179
+ },
180
+ time_info: {
181
+ current_time_utc: '2026-01-01T00:00:00.000Z',
182
+ current_time_utc_epoch_seconds: 1767225600,
183
+ message: 'UTC time',
184
+ },
185
+ };
186
+ },
187
+ },
188
+ });
189
+
190
+ yield* cli(['tools', 'search', 'send', '--toolkits', 'gmail,outlook']).pipe(
191
+ Effect.provide(live)
192
+ );
193
+
194
+ expect(createParams?.toolkits).toEqual({ enable: ['gmail', 'outlook'] });
195
+ expect(searchParams?.queries[0]?.use_case).toBe('send');
196
+ })
197
+ );
198
+ }
199
+ );
200
+
201
+ layer(TestLive({ baseConfigProvider: testConfigProvider, toolkitsData }))(
202
+ '[Given] search response with recommended plan [Then] it prints plan and execute hint',
203
+ it => {
204
+ it.scoped('prints plan and command hints', () =>
205
+ Effect.gen(function* () {
206
+ const live = TestLive({
207
+ baseConfigProvider: testConfigProvider,
208
+ toolkitsData,
209
+ toolRouter: {
210
+ search: async (_sessionId, params) => ({
211
+ success: true,
212
+ error: null,
213
+ results: [
214
+ {
215
+ index: 1,
216
+ use_case: params.queries[0]?.use_case ?? '',
217
+ primary_tool_slugs: ['GMAIL_SEND_EMAIL'],
218
+ related_tool_slugs: [],
219
+ toolkits: ['gmail'],
220
+ recommended_plan_steps: ['Collect recipient details', 'Execute send action'],
221
+ },
222
+ ],
223
+ tool_schemas: {
224
+ GMAIL_SEND_EMAIL: {
225
+ tool_slug: 'GMAIL_SEND_EMAIL',
226
+ toolkit: 'gmail',
227
+ description: 'Sends an email',
228
+ hasFullSchema: true,
229
+ input_schema: { type: 'object', properties: {} },
230
+ output_schema: { type: 'object', properties: {} },
231
+ },
232
+ },
233
+ toolkit_connection_statuses: [
234
+ {
235
+ toolkit: 'gmail',
236
+ description: 'gmail toolkit',
237
+ has_active_connection: false,
238
+ status_message: 'No active connection',
239
+ },
240
+ ],
241
+ next_steps_guidance: ['Fallback guidance'],
242
+ session: {
243
+ id: 'trs_test_session',
244
+ generate_id: false,
245
+ instructions: 'Reuse this session id for follow-up calls.',
246
+ },
247
+ time_info: {
248
+ current_time_utc: '2026-01-01T00:00:00.000Z',
249
+ current_time_utc_epoch_seconds: 1767225600,
250
+ message: 'UTC time',
251
+ },
252
+ }),
253
+ },
254
+ });
255
+
256
+ yield* cli(['tools', 'search', 'send email']).pipe(Effect.provide(live));
257
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
258
+ const output = lines.join('\n');
259
+
260
+ expect(output).toContain('Plan:');
261
+ expect(output).toContain('1. Collect recipient details');
262
+ expect(output).toContain('Hints:');
263
+ expect(output).toContain('composio tools info "GMAIL_SEND_EMAIL"');
264
+ expect(output).toContain(
265
+ `composio tools execute "GMAIL_SEND_EMAIL" --user-id "<user-id>" --arguments '{}'`
266
+ );
267
})
268
);
269
}
ts/packages/cli/test/src/commands/triggers/triggers.listen.cmd.test.ts
+1
-1
@@ -71,7 +71,7 @@ const startWebhookServer = async (): Promise<{
71
webhookId: (req.headers['webhook-id'] as string | undefined) ?? '',
72
webhookTimestamp: (req.headers['webhook-timestamp'] as string | undefined) ?? '',
73
webhookSignature: (req.headers['webhook-signature'] as string | undefined) ?? '',
74
- webhookVersion: (req.headers['x-composio-webhook-version'] as string | undefined) ?? '',
74
+ webhookVersion: (req.headers['webhook-version'] as string | undefined) ?? '',
75
},
76
});
77
res.statusCode = 200;
ts/packages/cli/test/src/models/project-keys.test.ts
+15
@@ -14,6 +14,7 @@ describe('ProjectKeys', () => {
14
expect(Option.isNone(result.projectName)).toBe(true);
15
expect(Option.isNone(result.orgName)).toBe(true);
16
expect(Option.isNone(result.email)).toBe(true);
17
+ expect(Option.isNone(result.testUserId)).toBe(true);
18
});
19
20
it('decodes valid JSON with all fields', () => {
@@ -23,6 +24,7 @@ describe('ProjectKeys', () => {
24
project_name: 'My Project',
25
org_name: 'My Org',
26
email: 'test@test.com',
27
+ test_user_id: 'pg-test-user-123',
28
});
29
30
const result = Effect.runSync(projectKeysFromJSON(json));
@@ -32,6 +34,7 @@ describe('ProjectKeys', () => {
34
expect(Option.getOrUndefined(result.projectName)).toBe('My Project');
35
expect(Option.getOrUndefined(result.orgName)).toBe('My Org');
36
expect(Option.getOrUndefined(result.email)).toBe('test@test.com');
37
+ expect(Option.getOrUndefined(result.testUserId)).toBe('pg-test-user-123');
38
});
39
40
it('decodes null optional fields as Option.none()', () => {
@@ -41,6 +44,7 @@ describe('ProjectKeys', () => {
44
project_name: null,
45
org_name: null,
46
email: null,
47
+ test_user_id: null,
48
});
49
50
const result = Effect.runSync(projectKeysFromJSON(json));
@@ -50,6 +54,7 @@ describe('ProjectKeys', () => {
54
expect(Option.isNone(result.projectName)).toBe(true);
55
expect(Option.isNone(result.orgName)).toBe(true);
56
expect(Option.isNone(result.email)).toBe(true);
57
+ expect(Option.isNone(result.testUserId)).toBe(true);
58
});
59
60
it('ignores extra keys in decoded JSON', () => {
@@ -105,6 +110,7 @@ describe('ProjectKeys', () => {
110
projectName: Option.some('My Project'),
111
orgName: Option.some('My Org'),
112
email: Option.some('test@test.com'),
113
+ testUserId: Option.some('pg-test-user-123'),
114
};
115
116
const json = Effect.runSync(projectKeysToJSON(keys));
@@ -115,6 +121,7 @@ describe('ProjectKeys', () => {
121
expect(parsed.project_name).toBe('My Project');
122
expect(parsed.org_name).toBe('My Org');
123
expect(parsed.email).toBe('test@test.com');
124
+ expect(parsed.test_user_id).toBe('pg-test-user-123');
125
});
126
127
it('encodes None optional fields as null', () => {
@@ -124,6 +131,7 @@ describe('ProjectKeys', () => {
131
projectName: Option.none(),
132
orgName: Option.none(),
133
email: Option.none(),
134
+ testUserId: Option.none(),
135
};
136
137
const json = Effect.runSync(projectKeysToJSON(keys));
@@ -134,6 +142,7 @@ describe('ProjectKeys', () => {
142
expect(parsed.project_name).toBeNull();
143
expect(parsed.org_name).toBeNull();
144
expect(parsed.email).toBeNull();
145
+ expect(parsed.test_user_id).toBeNull();
146
});
147
});
148
@@ -145,6 +154,7 @@ describe('ProjectKeys', () => {
154
projectName: Option.some('Test Project'),
155
orgName: Option.some('Test Org'),
156
email: Option.some('user@example.com'),
157
+ testUserId: Option.some('pg-test-user-123'),
158
};
159
160
const json = Effect.runSync(projectKeysToJSON(original));
@@ -157,6 +167,9 @@ describe('ProjectKeys', () => {
167
);
168
expect(Option.getOrUndefined(decoded.orgName)).toBe(Option.getOrUndefined(original.orgName));
169
expect(Option.getOrUndefined(decoded.email)).toBe(Option.getOrUndefined(original.email));
170
+ expect(Option.getOrUndefined(decoded.testUserId)).toBe(
171
+ Option.getOrUndefined(original.testUserId)
172
+ );
173
});
174
175
it('encode then decode preserves None values', () => {
@@ -166,6 +179,7 @@ describe('ProjectKeys', () => {
179
projectName: Option.none(),
180
orgName: Option.none(),
181
email: Option.none(),
182
+ testUserId: Option.none(),
183
};
184
185
const json = Effect.runSync(projectKeysToJSON(original));
@@ -176,6 +190,7 @@ describe('ProjectKeys', () => {
190
expect(Option.isNone(decoded.projectName)).toBe(true);
191
expect(Option.isNone(decoded.orgName)).toBe(true);
192
expect(Option.isNone(decoded.email)).toBe(true);
193
+ expect(Option.isNone(decoded.testUserId)).toBe(true);
194
});
195
});
196
});