@devries-cameron20 / composio Mirror · read-only / commits / d1ef6b25e
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 00:45 UTC

Add direct user API key login to the CLI (#3132)

## Summary - Adds a new `composio login --user-api-key` flow for direct login without the browser/session-key path. - Supports selecting a default organization with `--org` and validates incompatible flag combinations. - Updates login help, CLI docs, and command output so the direct login path reports the selected org consistently. - Expands login tests to cover help text and direct API key login behavior. ## Testing - `pnpm test -- login.cmd.test.ts` or equivalent CLI test run covering the updated login command. - Verified help output includes `--user-api-key` and `--org` and no longer advertises legacy `--api-key`. - Verified direct login stores the chosen org and writes the expected user config values. - Not run: full repository test suite.

Rahul Tarak committed Apr 7, 2026 at 19:08 UTC d1ef6b25ecf9643f6b8c6c8af70d2ef1a87ec507
5 files changed +272 -73
ts/packages/cli/AGENTS.md
+1 -1
@@ -31,7 +31,7 @@ Each command is declared with `@effect/cli`'s `Command.make()` pattern:
31 | -------------------------------------------------------- | ------------------------------------------------------------------------------------- |
32 | `composio version` | Display CLI version |
33 | `composio whoami` | Show logged-in user's API key |
34 -| `composio login [--no-browser] [--no-wait] [--key text]` | Login with browser redirect |
34 +| `composio login [--no-browser] [--no-wait] [--key text] [--user-api-key text] [--org text]` | Login with browser redirect or direct user API key |
35 | `composio logout` | Clear stored API key |
36 | `composio upgrade` | Self-update binary from GitHub releases |
37 | `composio generate` | Auto-detect project language, delegate to `ts` or `py` |
ts/packages/cli/README.md
+1 -1
@@ -27,7 +27,7 @@ composio [--log-level all|trace|debug|info|warning|error|fatal|none]
27
28 - `composio version`: Display the current CLI version.
29 - `composio whoami`: Show the currently logged-in user/account.
30 -- `composio login [--no-browser] [--no-wait] [--key text] [-y, --yes] [--no-skill-install]`: Log in to the Composio CLI session.
30 +- `composio login [--no-browser] [--no-wait] [--key text] [--user-api-key text] [--org text] [-y, --yes] [--no-skill-install]`: Log in to the Composio CLI session.
31 - `composio logout`: Log out from the Composio CLI session.
32 - `composio orgs list|switch`: Inspect and switch your default organization context.
33 - `composio search <query...> [--toolkits text] [--limit integer] [--human]`: Find tools by use case across toolkits/apps.
ts/packages/cli/src/commands/login.cmd.ts
+165 -56
@@ -5,6 +5,7 @@ import {
5 ComposioSessionRepository,
6 getSessionInfo,
7 getSessionInfoByUserApiKey,
8 + listOrganizations,
9 type SessionInfoResponse,
10 } from 'src/services/composio-clients';
11 import { ComposioUserContext } from 'src/services/user-context';
@@ -32,6 +33,16 @@ const keyOpt = Options.text('key').pipe(
33 Options.optional
34 );
35
36 +const userApiKeyOpt = Options.text('user-api-key').pipe(
37 + Options.withDescription('Log in directly with a Composio user API key'),
38 + Options.optional
39 +);
40 +
41 +const orgOpt = Options.text('org').pipe(
42 + Options.withDescription('Default organization ID or name to store for CLI commands'),
43 + Options.optional
44 +);
45 +
46 const yesOpt = Options.boolean('yes').pipe(
47 Options.withAlias('y'),
48 Options.withDefault(false),
@@ -57,10 +68,107 @@ const formatLoginSuccessMessage = (params: { email?: string; orgName?: string })
68 return 'Logged in successfully';
69 };
70
71 +const emitLoginComplete = (params: {
72 + email?: string;
73 + orgId: string;
74 + orgName?: string;
75 + skipHints?: boolean;
76 +}) =>
77 + Effect.gen(function* () {
78 + const ui = yield* TerminalUI;
79 + const { email, orgId, orgName, skipHints = false } = params;
80 +
81 + yield* ui.log.success(formatLoginSuccessMessage({ email, orgName }));
82 + if (!skipHints) {
83 + yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
84 + yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));
85 + }
86 +
87 + yield* ui.output(
88 + JSON.stringify({
89 + email,
90 + org_id: orgId,
91 + org_name: orgName ?? '',
92 + })
93 + );
94 +
95 + if (!skipHints) {
96 + yield* ui.outro("You're all set!");
97 + }
98 + });
99 +
100 +const resolveDirectLoginOrganization = (params: {
101 + apiKey: string;
102 + baseURL: string;
103 + requestedOrg?: string;
104 + fallbackOrgId: string;
105 + fallbackOrgName?: string;
106 +}) =>
107 + Effect.gen(function* () {
108 + const ui = yield* TerminalUI;
109 + const { apiKey, baseURL, requestedOrg, fallbackOrgId, fallbackOrgName } = params;
110 +
111 + if (!requestedOrg) {
112 + return {
113 + id: fallbackOrgId,
114 + name: fallbackOrgName ?? fallbackOrgId,
115 + };
116 + }
117 +
118 + const organizations = yield* listOrganizations({
119 + baseURL,
120 + apiKey,
121 + });
122 + const match = organizations.data.find(
123 + org => org.id === requestedOrg || org.name === requestedOrg
124 + );
125 +
126 + if (!match) {
127 + yield* ui.log.error(`Organization "${requestedOrg}" was not found for this API key.`);
128 + return yield* Effect.fail(
129 + new Error('Invalid organization. Run `composio orgs list` to inspect available orgs.')
130 + );
131 + }
132 +
133 + return match;
134 + });
135 +
136 +const directLogin = (params: { userApiKey: string; org?: string }) =>
137 + Effect.gen(function* () {
138 + const ctx = yield* ComposioUserContext;
139 + const sessionInfo = yield* getSessionInfoByUserApiKey({
140 + baseURL: ctx.data.baseURL,
141 + userApiKey: params.userApiKey,
142 + });
143 +
144 + const selectedOrg = yield* resolveDirectLoginOrganization({
145 + apiKey: params.userApiKey,
146 + baseURL: ctx.data.baseURL,
147 + requestedOrg: params.org,
148 + fallbackOrgId: sessionInfo.project.org.id,
149 + fallbackOrgName: sessionInfo.project.org.name,
150 + });
151 +
152 + const sessionUserId = sessionInfo.org_member.user_id ?? sessionInfo.org_member.id;
153 + const testUserId = sessionUserId
154 + ? `pg-test-${sessionUserId}`
155 + : Option.getOrUndefined(ctx.data.testUserId);
156 +
157 + yield* ctx.login(params.userApiKey, selectedOrg.id, testUserId);
158 + yield* primeConsumerConnectedToolkitsCacheInBackground({
159 + orgId: selectedOrg.id,
160 + });
161 + yield* emitLoginComplete({
162 + email: sessionInfo.org_member.email || undefined,
163 + orgId: selectedOrg.id,
164 + orgName: selectedOrg.name,
165 + });
166 + });
167 +
168 /**
169 * Verifies credentials via session/info and stores them.
170 *
63 - * Resolves TerminalUI and ComposioUserContext from the Effect context rather
171 + * Resolves ComposioUserContext from the Effect context rather
172 * than accepting them as parameters -- this keeps the signature focused on
173 * data and avoids hand-rolled structural types.
174 */
@@ -76,7 +184,6 @@ const storeCredentials = (params: {
184 skipOutput?: boolean;
185 }) =>
186 Effect.gen(function* () {
79 - const ui = yield* TerminalUI;
187 const ctx = yield* ComposioUserContext;
188
189 const {
@@ -131,27 +238,13 @@ const storeCredentials = (params: {
238 orgId,
239 });
240
134 - const email = sessionInfo?.org_member.email || fallbackEmail || undefined;
135 - const orgName = sessionInfo?.project.org.name || undefined;
136 - yield* ui.log.success(formatLoginSuccessMessage({ email, orgName }));
137 - if (!skipHints) {
138 - yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
139 - yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));
140 - }
141 -
142 - // Emit structured JSON for piped/scripted consumption (agent-native)
241 if (!skipOutput) {
144 - yield* ui.output(
145 - JSON.stringify({
146 - email,
147 - org_id: orgId,
148 - org_name: sessionInfo?.project.org.name ?? '',
149 - })
150 - );
151 - }
152 -
153 - if (!skipHints) {
154 - yield* ui.outro("You're all set!");
242 + yield* emitLoginComplete({
243 + email: sessionInfo?.org_member.email || fallbackEmail || undefined,
244 + orgId,
245 + orgName: sessionInfo?.project.org.name || undefined,
246 + skipHints,
247 + });
248 }
249 });
250
@@ -256,25 +349,14 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPick
349 yield* primeConsumerConnectedToolkitsCacheInBackground({
350 orgId: result.id,
351 });
259 - yield* ui.log.success(
260 - formatLoginSuccessMessage({
261 - email: uakSessionInfo.org_member.email || linkedSession.account.email || undefined,
262 - orgName: result.name,
263 - })
264 - );
352 }
353 const finalOrgId = result?.id ?? xOrgId;
354 const finalOrgName = result?.name ?? uakSessionInfo.project.org.name ?? '';
268 - yield* ui.output(
269 - JSON.stringify({
270 - email: linkedSession.account.email ?? undefined,
271 - org_id: finalOrgId,
272 - org_name: finalOrgName,
273 - })
274 - );
275 - yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
276 - yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));
277 - yield* ui.outro("You're all set!");
355 + yield* emitLoginComplete({
356 + email: linkedSession.account.email ?? undefined,
357 + orgId: finalOrgId,
358 + orgName: finalOrgName,
359 + });
360 }
361 });
362
@@ -421,25 +503,14 @@ export const browserLogin = (params: {
503 yield* primeConsumerConnectedToolkitsCacheInBackground({
504 orgId: result.id,
505 });
424 - yield* ui.log.success(
425 - formatLoginSuccessMessage({
426 - email: uakSessionInfo.org_member.email || linkedSession.account.email || undefined,
427 - orgName: result.name,
428 - })
429 - );
506 }
507 const finalOrgId = result?.id ?? xOrgId;
508 const finalOrgName = result?.name ?? uakSessionInfo.project.org.name ?? '';
433 - yield* ui.output(
434 - JSON.stringify({
435 - email: linkedSession.account.email ?? undefined,
436 - org_id: finalOrgId,
437 - org_name: finalOrgName,
438 - })
439 - );
440 - yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));
441 - yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));
442 - yield* ui.outro("You're all set!");
509 + yield* emitLoginComplete({
510 + email: linkedSession.account.email ?? undefined,
511 + orgId: finalOrgId,
512 + orgName: finalOrgName,
513 + });
514 }
515 });
516
@@ -451,6 +522,7 @@ export const browserLogin = (params: {
522 * Use --no-wait to print login URL and session info (JSON) then exit without opening browser or waiting.
523 * Use --key to complete login with a session key from --no-wait. Without --no-wait, polls until linked;
524 * with --no-wait, checks once and fails if not linked.
525 + * Use --user-api-key to log in directly without a browser flow, and --org to override the default org.
526 * Use -y to skip org picker and use session default org.
527 *
528 * @example
@@ -460,19 +532,45 @@ export const browserLogin = (params: {
532 * composio login --no-wait
533 * composio login --key <key>
534 * composio login --key <key> --no-wait
535 + * composio login --user-api-key <uak>
536 + * composio login --user-api-key <uak> --org <org>
537 * composio login -y
538 * ```
539 */
540 export const loginCmd = Command.make(
541 'login',
468 - { noBrowser, noWait, key: keyOpt, yes: yesOpt, noSkillInstall },
469 - ({ noBrowser, noWait, key, yes, noSkillInstall }) =>
542 + {
543 + noBrowser,
544 + noWait,
545 + key: keyOpt,
546 + userApiKey: userApiKeyOpt,
547 + org: orgOpt,
548 + yes: yesOpt,
549 + noSkillInstall,
550 + },
551 + ({ noBrowser, noWait, key, userApiKey, org, yes, noSkillInstall }) =>
552 Effect.gen(function* () {
553 const ui = yield* TerminalUI;
554 const ctx = yield* ComposioUserContext;
555
556 yield* ui.intro('composio login');
557
558 + if (Option.isSome(key) && Option.isSome(userApiKey)) {
559 + return yield* Effect.fail(new Error('Use either `--key` or `--user-api-key`, not both.'));
560 + }
561 +
562 + if (Option.isSome(org) && Option.isNone(userApiKey)) {
563 + return yield* Effect.fail(new Error('`--org` requires `--user-api-key`.'));
564 + }
565 +
566 + if (Option.isSome(userApiKey) && (noBrowser || noWait || Option.isSome(key))) {
567 + return yield* Effect.fail(
568 + new Error(
569 + '`--user-api-key` is a direct login path and cannot be combined with browser or session flags.'
570 + )
571 + );
572 + }
573 +
574 if (Option.isSome(key)) {
575 yield* loginWithKey({
576 key: key.value,
@@ -485,6 +583,17 @@ export const loginCmd = Command.make(
583 return;
584 }
585
586 + if (Option.isSome(userApiKey)) {
587 + yield* directLogin({
588 + userApiKey: userApiKey.value,
589 + org: Option.getOrUndefined(org),
590 + });
591 + if (!noSkillInstall) {
592 + yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });
593 + }
594 + return;
595 + }
596 +
597 if (ctx.isLoggedIn()) {
598 if (Option.isSome(ctx.data.orgId)) {
599 yield* ui.log.warn(`You're already logged in!`);
ts/packages/cli/src/commands/root-help.ts
+9 -1
@@ -516,7 +516,7 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHel
516
517 login: {
518 usage:
519 - 'composio login [--no-browser] [--no-wait] [--key text] [-y, --yes] [--no-skill-install]',
519 + 'composio login [--no-browser] [--no-wait] [--key text] [--user-api-key text] [--org text] [-y, --yes] [--no-skill-install]',
520 description:
521 'Log in to the Composio CLI session. By default, also installs the composio-cli skill for Claude Code.',
522 options: [
@@ -524,6 +524,14 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHel
524 name: '--key <text>',
525 description: 'Complete login using session key from composio login --no-wait',
526 },
527 + {
528 + name: '--user-api-key <text>',
529 + description: 'Log in directly with a Composio user API key',
530 + },
531 + {
532 + name: '--org <text>',
533 + description: 'Default organization ID or name to store for CLI commands',
534 + },
535 ],
536 flags: [
537 { name: '--no-browser', description: 'Login without browser interaction' },
ts/packages/cli/test/src/commands/login.cmd.test.ts
+96 -14
@@ -1,7 +1,17 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { vi, afterEach } from 'vitest';
3 import { Effect } from 'effect';
4 +import path from 'node:path';
5 +import { FileSystem } from '@effect/platform';
6 import { cli, MockConsole, TestLive } from 'test/__utils__';
7 +import * as constants from 'src/constants';
8 +import { setupCacheDir } from 'src/effects/setup-cache-dir';
9 +
10 +const mockFetchResponse = (body: unknown, status = 200) =>
11 + new Response(JSON.stringify(body), {
12 + status,
13 + headers: { 'Content-Type': 'application/json' },
14 + });
15
16 // ── Tests ────────────────────────────────────────────────────────────────────
17
@@ -12,21 +22,93 @@ describe('CLI: composio login', () => {
22
23 describe('login --help', () => {
24 layer(TestLive())(it => {
15 - it.scoped(
16 - '[Then] shows --no-browser, --no-wait, --key and -y/--yes (skip picker), no --api-key',
17 - () =>
18 - Effect.gen(function* () {
19 - yield* cli(['login', '--help']);
20 - const lines = yield* MockConsole.getLines();
21 - const output = lines.join('\n');
22 - expect(output).toContain('--no-browser');
23 - expect(output).toContain('--no-wait');
24 - expect(output).toContain('--key');
25 - expect(output).toContain('--yes');
26 - expect(output).toContain('-y');
27 - expect(output).not.toContain('--api-key');
28 - })
25 + it.scoped('[Then] shows browser, session, direct-login flags and no legacy --api-key', () =>
26 + Effect.gen(function* () {
27 + yield* cli(['login', '--help']);
28 + const lines = yield* MockConsole.getLines();
29 + const output = lines.join('\n');
30 + expect(output).toContain('--no-browser');
31 + expect(output).toContain('--no-wait');
32 + expect(output).toContain('--key');
33 + expect(output).toContain('--user-api-key');
34 + expect(output).toContain('--org');
35 + expect(output).toContain('--yes');
36 + expect(output).toContain('-y');
37 + expect(output).not.toMatch(/(^|\s)--api-key(?:\s|$)/);
38 + })
39 );
40 });
41 });
42 +
43 + layer(TestLive())(it => {
44 + it.scoped('[When] logging in with --user-api-key --org [Then] stores the chosen org', () =>
45 + Effect.gen(function* () {
46 + vi.spyOn(globalThis, 'fetch').mockImplementation(
47 + async (requestInput: RequestInfo | URL, init?: RequestInit) => {
48 + const url =
49 + typeof requestInput === 'string'
50 + ? requestInput
51 + : requestInput instanceof URL
52 + ? requestInput.toString()
53 + : requestInput.url;
54 +
55 + if (url.includes('/api/v3/auth/session/info')) {
56 + return mockFetchResponse({
57 + project: {
58 + name: 'Default Project',
59 + id: 'project_id_default',
60 + org_id: 'org_default',
61 + nano_id: 'project_default',
62 + email: 'project@example.com',
63 + created_at: '2026-01-01T00:00:00.000Z',
64 + updated_at: '2026-01-01T00:00:00.000Z',
65 + org: { id: 'org_default', name: 'Default Org', plan: 'enterprise' },
66 + },
67 + org_member: {
68 + id: 'member_123',
69 + user_id: 'user_123',
70 + email: 'cli@example.com',
71 + name: 'CLI User',
72 + role: 'admin',
73 + },
74 + api_key: null,
75 + });
76 + }
77 +
78 + if (url.includes('/api/v3/org/list?limit=50')) {
79 + expect(new Headers(init?.headers).get('x-user-api-key')).toBe('uak_direct_key');
80 + return mockFetchResponse({
81 + organizations: [
82 + { id: 'org_default', name: 'Default Org' },
83 + { id: 'org_selected', name: 'Selected Org' },
84 + ],
85 + });
86 + }
87 +
88 + return mockFetchResponse({});
89 + }
90 + );
91 +
92 + yield* cli([
93 + 'login',
94 + '--user-api-key',
95 + 'uak_direct_key',
96 + '--org',
97 + 'org_selected',
98 + '--no-skill-install',
99 + ]);
100 +
101 + const fs = yield* FileSystem.FileSystem;
102 + const cacheDir = yield* setupCacheDir;
103 + const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
104 + const rawUserConfig = yield* fs.readFileString(userConfigPath, 'utf8');
105 + const userConfig = JSON.parse(rawUserConfig) as Record<string, unknown>;
106 + expect(userConfig.api_key).toBe('uak_direct_key');
107 + expect(userConfig.org_id).toBe('org_selected');
108 +
109 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
110 + expect(output).toContain('Logged in as cli@example.com in "Selected Org"');
111 + })
112 + );
113 + });
114 });