Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Add direct user API key login to the CLI (#3132)
Rahul Tarakd1ef6b25ecf9
diff --git a/ts/packages/cli/AGENTS.md b/ts/packages/cli/AGENTS.mdindex a842947ff..d61092e6a 100644--- a/ts/packages/cli/AGENTS.md+++ b/ts/packages/cli/AGENTS.md@@ -31,7 +31,7 @@ Each command is declared with `@effect/cli`'s `Command.make()` pattern:| -------------------------------------------------------- | ------------------------------------------------------------------------------------- || `composio version` | Display CLI version || `composio whoami` | Show logged-in user's API key |-| `composio login [--no-browser] [--no-wait] [--key text]` | Login with browser redirect |+| `composio login [--no-browser] [--no-wait] [--key text] [--user-api-key text] [--org text]` | Login with browser redirect or direct user API key || `composio logout` | Clear stored API key || `composio upgrade` | Self-update binary from GitHub releases || `composio generate` | Auto-detect project language, delegate to `ts` or `py` |diff --git a/ts/packages/cli/README.md b/ts/packages/cli/README.mdindex 00fe13037..f22a1d499 100644--- a/ts/packages/cli/README.md+++ b/ts/packages/cli/README.md@@ -27,7 +27,7 @@ composio [--log-level all|trace|debug|info|warning|error|fatal|none]- `composio version`: Display the current CLI version.- `composio whoami`: Show the currently logged-in user/account.-- `composio login [--no-browser] [--no-wait] [--key text] [-y, --yes] [--no-skill-install]`: Log in to the Composio CLI session.+- `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.- `composio logout`: Log out from the Composio CLI session.- `composio orgs list|switch`: Inspect and switch your default organization context.- `composio search <query...> [--toolkits text] [--limit integer] [--human]`: Find tools by use case across toolkits/apps.diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.tsindex be41a3ca5..49e88736a 100644--- a/ts/packages/cli/src/commands/login.cmd.ts+++ b/ts/packages/cli/src/commands/login.cmd.ts@@ -5,6 +5,7 @@ import {ComposioSessionRepository,getSessionInfo,getSessionInfoByUserApiKey,+ listOrganizations,type SessionInfoResponse,} from 'src/services/composio-clients';import { ComposioUserContext } from 'src/services/user-context';@@ -32,6 +33,16 @@ const keyOpt = Options.text('key').pipe(Options.optional);+const userApiKeyOpt = Options.text('user-api-key').pipe(+ Options.withDescription('Log in directly with a Composio user API key'),+ Options.optional+);++const orgOpt = Options.text('org').pipe(+ Options.withDescription('Default organization ID or name to store for CLI commands'),+ Options.optional+);+const yesOpt = Options.boolean('yes').pipe(Options.withAlias('y'),Options.withDefault(false),@@ -57,10 +68,107 @@ const formatLoginSuccessMessage = (params: { email?: string; orgName?: string })return 'Logged in successfully';};+const emitLoginComplete = (params: {+ email?: string;+ orgId: string;+ orgName?: string;+ skipHints?: boolean;+}) =>+ Effect.gen(function* () {+ const ui = yield* TerminalUI;+ const { email, orgId, orgName, skipHints = false } = params;++ yield* ui.log.success(formatLoginSuccessMessage({ email, orgName }));+ if (!skipHints) {+ yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));+ yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));+ }++ yield* ui.output(+ JSON.stringify({+ email,+ org_id: orgId,+ org_name: orgName ?? '',+ })+ );++ if (!skipHints) {+ yield* ui.outro("You're all set!");+ }+ });++const resolveDirectLoginOrganization = (params: {+ apiKey: string;+ baseURL: string;+ requestedOrg?: string;+ fallbackOrgId: string;+ fallbackOrgName?: string;+}) =>+ Effect.gen(function* () {+ const ui = yield* TerminalUI;+ const { apiKey, baseURL, requestedOrg, fallbackOrgId, fallbackOrgName } = params;++ if (!requestedOrg) {+ return {+ id: fallbackOrgId,+ name: fallbackOrgName ?? fallbackOrgId,+ };+ }++ const organizations = yield* listOrganizations({+ baseURL,+ apiKey,+ });+ const match = organizations.data.find(+ org => org.id === requestedOrg || org.name === requestedOrg+ );++ if (!match) {+ yield* ui.log.error(`Organization "${requestedOrg}" was not found for this API key.`);+ return yield* Effect.fail(+ new Error('Invalid organization. Run `composio orgs list` to inspect available orgs.')+ );+ }++ return match;+ });++const directLogin = (params: { userApiKey: string; org?: string }) =>+ Effect.gen(function* () {+ const ctx = yield* ComposioUserContext;+ const sessionInfo = yield* getSessionInfoByUserApiKey({+ baseURL: ctx.data.baseURL,+ userApiKey: params.userApiKey,+ });++ const selectedOrg = yield* resolveDirectLoginOrganization({+ apiKey: params.userApiKey,+ baseURL: ctx.data.baseURL,+ requestedOrg: params.org,+ fallbackOrgId: sessionInfo.project.org.id,+ fallbackOrgName: sessionInfo.project.org.name,+ });++ const sessionUserId = sessionInfo.org_member.user_id ?? sessionInfo.org_member.id;+ const testUserId = sessionUserId+ ? `pg-test-${sessionUserId}`+ : Option.getOrUndefined(ctx.data.testUserId);++ yield* ctx.login(params.userApiKey, selectedOrg.id, testUserId);+ yield* primeConsumerConnectedToolkitsCacheInBackground({+ orgId: selectedOrg.id,+ });+ yield* emitLoginComplete({+ email: sessionInfo.org_member.email || undefined,+ orgId: selectedOrg.id,+ orgName: selectedOrg.name,+ });+ });+/*** Verifies credentials via session/info and stores them.*- * Resolves TerminalUI and ComposioUserContext from the Effect context rather+ * Resolves ComposioUserContext from the Effect context rather* than accepting them as parameters -- this keeps the signature focused on* data and avoids hand-rolled structural types.*/@@ -76,7 +184,6 @@ const storeCredentials = (params: {skipOutput?: boolean;}) =>Effect.gen(function* () {- const ui = yield* TerminalUI;const ctx = yield* ComposioUserContext;const {@@ -131,27 +238,13 @@ const storeCredentials = (params: {orgId,});- const email = sessionInfo?.org_member.email || fallbackEmail || undefined;- const orgName = sessionInfo?.project.org.name || undefined;- yield* ui.log.success(formatLoginSuccessMessage({ email, orgName }));- if (!skipHints) {- yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));- yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));- }-- // Emit structured JSON for piped/scripted consumption (agent-native)if (!skipOutput) {- yield* ui.output(- JSON.stringify({- email,- org_id: orgId,- org_name: sessionInfo?.project.org.name ?? '',- })- );- }-- if (!skipHints) {- yield* ui.outro("You're all set!");+ yield* emitLoginComplete({+ email: sessionInfo?.org_member.email || fallbackEmail || undefined,+ orgId,+ orgName: sessionInfo?.project.org.name || undefined,+ skipHints,+ });}});@@ -256,25 +349,14 @@ const loginWithKey = (params: { key: string; noWait: boolean; skipOrgProjectPickyield* primeConsumerConnectedToolkitsCacheInBackground({orgId: result.id,});- yield* ui.log.success(- formatLoginSuccessMessage({- email: uakSessionInfo.org_member.email || linkedSession.account.email || undefined,- orgName: result.name,- })- );}const finalOrgId = result?.id ?? xOrgId;const finalOrgName = result?.name ?? uakSessionInfo.project.org.name ?? '';- yield* ui.output(- JSON.stringify({- email: linkedSession.account.email ?? undefined,- org_id: finalOrgId,- org_name: finalOrgName,- })- );- yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));- yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));- yield* ui.outro("You're all set!");+ yield* emitLoginComplete({+ email: linkedSession.account.email ?? undefined,+ orgId: finalOrgId,+ orgName: finalOrgName,+ });}});@@ -421,25 +503,14 @@ export const browserLogin = (params: {yield* primeConsumerConnectedToolkitsCacheInBackground({orgId: result.id,});- yield* ui.log.success(- formatLoginSuccessMessage({- email: uakSessionInfo.org_member.email || linkedSession.account.email || undefined,- orgName: result.name,- })- );}const finalOrgId = result?.id ?? xOrgId;const finalOrgName = result?.name ?? uakSessionInfo.project.org.name ?? '';- yield* ui.output(- JSON.stringify({- email: linkedSession.account.email ?? undefined,- org_id: finalOrgId,- org_name: finalOrgName,- })- );- yield* ui.log.info(commandHintStep('Execute a tool directly', 'root.execute'));- yield* ui.log.info(commandHintStep('Switch your default org', 'root.orgs.switch'));- yield* ui.outro("You're all set!");+ yield* emitLoginComplete({+ email: linkedSession.account.email ?? undefined,+ orgId: finalOrgId,+ orgName: finalOrgName,+ });}});@@ -451,6 +522,7 @@ export const browserLogin = (params: {* Use --no-wait to print login URL and session info (JSON) then exit without opening browser or waiting.* Use --key to complete login with a session key from --no-wait. Without --no-wait, polls until linked;* with --no-wait, checks once and fails if not linked.+ * Use --user-api-key to log in directly without a browser flow, and --org to override the default org.* Use -y to skip org picker and use session default org.** @example@@ -460,19 +532,45 @@ export const browserLogin = (params: {* composio login --no-wait* composio login --key <key>* composio login --key <key> --no-wait+ * composio login --user-api-key <uak>+ * composio login --user-api-key <uak> --org <org>* composio login -y* ```*/export const loginCmd = Command.make('login',- { noBrowser, noWait, key: keyOpt, yes: yesOpt, noSkillInstall },- ({ noBrowser, noWait, key, yes, noSkillInstall }) =>+ {+ noBrowser,+ noWait,+ key: keyOpt,+ userApiKey: userApiKeyOpt,+ org: orgOpt,+ yes: yesOpt,+ noSkillInstall,+ },+ ({ noBrowser, noWait, key, userApiKey, org, yes, noSkillInstall }) =>Effect.gen(function* () {const ui = yield* TerminalUI;const ctx = yield* ComposioUserContext;yield* ui.intro('composio login');+ if (Option.isSome(key) && Option.isSome(userApiKey)) {+ return yield* Effect.fail(new Error('Use either `--key` or `--user-api-key`, not both.'));+ }++ if (Option.isSome(org) && Option.isNone(userApiKey)) {+ return yield* Effect.fail(new Error('`--org` requires `--user-api-key`.'));+ }++ if (Option.isSome(userApiKey) && (noBrowser || noWait || Option.isSome(key))) {+ return yield* Effect.fail(+ new Error(+ '`--user-api-key` is a direct login path and cannot be combined with browser or session flags.'+ )+ );+ }+if (Option.isSome(key)) {yield* loginWithKey({key: key.value,@@ -485,6 +583,17 @@ export const loginCmd = Command.make(return;}+ if (Option.isSome(userApiKey)) {+ yield* directLogin({+ userApiKey: userApiKey.value,+ org: Option.getOrUndefined(org),+ });+ if (!noSkillInstall) {+ yield* installSkillSafe({ channel: inferSkillReleaseChannel(APP_VERSION) });+ }+ return;+ }+if (ctx.isLoggedIn()) {if (Option.isSome(ctx.data.orgId)) {yield* ui.log.warn(`You're already logged in!`);diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.tsindex c965063d8..c86baca44 100644--- a/ts/packages/cli/src/commands/root-help.ts+++ b/ts/packages/cli/src/commands/root-help.ts@@ -516,7 +516,7 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHellogin: {usage:- 'composio login [--no-browser] [--no-wait] [--key text] [-y, --yes] [--no-skill-install]',+ 'composio login [--no-browser] [--no-wait] [--key text] [--user-api-key text] [--org text] [-y, --yes] [--no-skill-install]',description:'Log in to the Composio CLI session. By default, also installs the composio-cli skill for Claude Code.',options: [@@ -524,6 +524,14 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHelname: '--key <text>',description: 'Complete login using session key from composio login --no-wait',},+ {+ name: '--user-api-key <text>',+ description: 'Log in directly with a Composio user API key',+ },+ {+ name: '--org <text>',+ description: 'Default organization ID or name to store for CLI commands',+ },],flags: [{ name: '--no-browser', description: 'Login without browser interaction' },diff --git a/ts/packages/cli/test/src/commands/login.cmd.test.ts b/ts/packages/cli/test/src/commands/login.cmd.test.tsindex cdf3b174f..9efb705bd 100644--- a/ts/packages/cli/test/src/commands/login.cmd.test.ts+++ b/ts/packages/cli/test/src/commands/login.cmd.test.ts@@ -1,7 +1,17 @@import { describe, expect, layer } from '@effect/vitest';import { vi, afterEach } from 'vitest';import { Effect } from 'effect';+import path from 'node:path';+import { FileSystem } from '@effect/platform';import { cli, MockConsole, TestLive } from 'test/__utils__';+import * as constants from 'src/constants';+import { setupCacheDir } from 'src/effects/setup-cache-dir';++const mockFetchResponse = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), {+ status,+ headers: { 'Content-Type': 'application/json' },+ });// ── Tests ────────────────────────────────────────────────────────────────────@@ -12,21 +22,93 @@ describe('CLI: composio login', () => {describe('login --help', () => {layer(TestLive())(it => {- it.scoped(- '[Then] shows --no-browser, --no-wait, --key and -y/--yes (skip picker), no --api-key',- () =>- Effect.gen(function* () {- yield* cli(['login', '--help']);- const lines = yield* MockConsole.getLines();- const output = lines.join('\n');- expect(output).toContain('--no-browser');- expect(output).toContain('--no-wait');- expect(output).toContain('--key');- expect(output).toContain('--yes');- expect(output).toContain('-y');- expect(output).not.toContain('--api-key');- })+ it.scoped('[Then] shows browser, session, direct-login flags and no legacy --api-key', () =>+ Effect.gen(function* () {+ yield* cli(['login', '--help']);+ const lines = yield* MockConsole.getLines();+ const output = lines.join('\n');+ expect(output).toContain('--no-browser');+ expect(output).toContain('--no-wait');+ expect(output).toContain('--key');+ expect(output).toContain('--user-api-key');+ expect(output).toContain('--org');+ expect(output).toContain('--yes');+ expect(output).toContain('-y');+ expect(output).not.toMatch(/(^|\s)--api-key(?:\s|$)/);+ }));});});++ layer(TestLive())(it => {+ it.scoped('[When] logging in with --user-api-key --org [Then] stores the chosen org', () =>+ Effect.gen(function* () {+ vi.spyOn(globalThis, 'fetch').mockImplementation(+ async (requestInput: RequestInfo | URL, init?: RequestInit) => {+ const url =+ typeof requestInput === 'string'+ ? requestInput+ : requestInput instanceof URL+ ? requestInput.toString()+ : requestInput.url;++ if (url.includes('/api/v3/auth/session/info')) {+ return mockFetchResponse({+ project: {+ name: 'Default Project',+ id: 'project_id_default',+ org_id: 'org_default',+ nano_id: 'project_default',+ email: '[email protected]',+ created_at: '2026-01-01T00:00:00.000Z',+ updated_at: '2026-01-01T00:00:00.000Z',+ org: { id: 'org_default', name: 'Default Org', plan: 'enterprise' },+ },+ org_member: {+ id: 'member_123',+ user_id: 'user_123',+ email: '[email protected]',+ name: 'CLI User',+ role: 'admin',+ },+ api_key: null,+ });+ }++ if (url.includes('/api/v3/org/list?limit=50')) {+ expect(new Headers(init?.headers).get('x-user-api-key')).toBe('uak_direct_key');+ return mockFetchResponse({+ organizations: [+ { id: 'org_default', name: 'Default Org' },+ { id: 'org_selected', name: 'Selected Org' },+ ],+ });+ }++ return mockFetchResponse({});+ }+ );++ yield* cli([+ 'login',+ '--user-api-key',+ 'uak_direct_key',+ '--org',+ 'org_selected',+ '--no-skill-install',+ ]);++ const fs = yield* FileSystem.FileSystem;+ const cacheDir = yield* setupCacheDir;+ const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);+ const rawUserConfig = yield* fs.readFileString(userConfigPath, 'utf8');+ const userConfig = JSON.parse(rawUserConfig) as Record<string, unknown>;+ expect(userConfig.api_key).toBe('uak_direct_key');+ expect(userConfig.org_id).toBe('org_selected');++ const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');+ expect(output).toContain('Logged in as [email protected] in "Selected Org"');+ })+ );+ });});