@devries-cameron20 / composio Mirror · read-only / commits / 5890693e8
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, 05:45 UTC

feat(cli): add global org/project switch and list commands (#2793)

Musthaq Ahamad committed Feb 28, 2026 at 12:42 UTC 5890693e8c8e3e2955e2b54f3cf3ba0bbac66c90
21 files changed +993 -11
.changeset/spotty-bats-shine.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/cli': patch
3 +---
4 +
5 +Add a new commands for CLI org switching and project switching
ts/e2e-tests/cli/whoami/e2e.test.ts
+10 -4
@@ -23,6 +23,12 @@ e2e(import.meta.url, {
23 },
24 defineTests: ({ runCmd }) => {
25 const expectedApiKey = Bun.env.COMPOSIO_USER_API_KEY.trim();
26 + const expectedWhoamiJson = JSON.stringify({
27 + global_user_api_key: expectedApiKey,
28 + default_org_id: null,
29 + default_project_id: null,
30 + test_user_id: null,
31 + });
32 let whoamiResult: E2ETestResult;
33 let redirectedResult: E2ETestResultWithFiles<'out.txt'>;
34
@@ -39,8 +45,8 @@ e2e(import.meta.url, {
45 expect(whoamiResult.exitCode).toBe(0);
46 });
47
42 - it('stdout contains the API key', () => {
43 - expect(sanitizeOutput(whoamiResult.stdout)).toBe(expectedApiKey);
48 + it('stdout contains global user context JSON', () => {
49 + expect(sanitizeOutput(whoamiResult.stdout)).toBe(expectedWhoamiJson);
50 });
51
52 it('stderr is empty', () => {
@@ -61,8 +67,8 @@ e2e(import.meta.url, {
67 expect(redirectedResult.stderr).toBe('');
68 });
69
64 - it('out.txt contains the API key', () => {
65 - expect(sanitizeOutput(redirectedResult.files['out.txt'])).toBe(expectedApiKey);
70 + it('out.txt contains global user context JSON', () => {
71 + expect(sanitizeOutput(redirectedResult.files['out.txt'])).toBe(expectedWhoamiJson);
72 });
73 });
74 },
ts/packages/cli/src/commands/index.ts
+4
@@ -18,6 +18,8 @@ import { authConfigsCmd } from './auth-configs/auth-configs.cmd';
18 import { connectedAccountsCmd } from './connected-accounts/connected-accounts.cmd';
19 import { triggersCmd } from './triggers/triggers.cmd';
20 import { logsCmd } from './logs-cmd/logs.cmd';
21 +import { orgsCmd } from './orgs/orgs.cmd';
22 +import { projectsCmd } from './projects/projects.cmd';
23 import { showToolsExecuteInputHelp } from './tools/commands/tools.execute.cmd';
24
25 const $cmd = $defaultCmd.pipe(
@@ -37,6 +39,8 @@ const $cmd = $defaultCmd.pipe(
39 connectedAccountsCmd,
40 triggersCmd,
41 logsCmd,
42 + orgsCmd,
43 + projectsCmd,
44 ])
45 );
46
ts/packages/cli/src/commands/init.cmd.ts
+6
@@ -277,6 +277,9 @@ export const initCmd = CliCommand.make(
277 );
278
279 yield* ui.log.success(`Project initialized in ${composioDir}/`);
280 + yield* ui.log.info(
281 + 'To switch your default global org/project later, run `composio orgs switch`.'
282 + );
283 yield* ui.output(makeOutputJson(selected, composioDir));
284 yield* ui.outro('');
285 return;
@@ -395,6 +398,9 @@ const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean;
398 );
399
400 yield* ui.log.success(`Project initialized in ${composioDir}/`);
401 + yield* ui.log.info(
402 + 'To switch your default global org/project later, run `composio orgs switch`.'
403 + );
404 yield* ui.output(makeOutputJson(selected, composioDir));
405 yield* ui.outro('');
406 });
ts/packages/cli/src/commands/login.cmd.ts
+3
@@ -117,6 +117,9 @@ const storeCredentials = (params: {
117 const email = sessionInfo?.org_member.email || fallbackEmail || undefined;
118 yield* ui.log.success(email ? `Logged in as ${email}` : 'Logged in successfully');
119 yield* ui.log.info('Run `composio init` in your project directory to set up project context.');
120 + yield* ui.log.info(
121 + 'To switch your default global org/project later, run `composio orgs switch`.'
122 + );
123
124 // Emit structured JSON for piped/scripted consumption (agent-native)
125 yield* ui.output(
ts/packages/cli/src/commands/orgs/commands/orgs.list.cmd.ts new
+66
@@ -0,0 +1,66 @@
1 +import { Command, Options } from '@effect/cli';
2 +import { Effect, Option } from 'effect';
3 +import { requireAuth } from 'src/effects/require-auth';
4 +import { TerminalUI } from 'src/services/terminal-ui';
5 +import { listOrganizations } from 'src/services/composio-clients';
6 +import { ComposioUserContext } from 'src/services/user-context';
7 +import { clampLimit } from 'src/ui/clamp-limit';
8 +
9 +const limit = Options.integer('limit').pipe(
10 + Options.withDefault(50),
11 + Options.withDescription('Max organizations to fetch from API (default: 50)')
12 +);
13 +
14 +export const orgsCmd$List = Command.make('list', { limit }, ({ limit }) =>
15 + Effect.gen(function* () {
16 + if (!(yield* requireAuth)) return;
17 +
18 + const ui = yield* TerminalUI;
19 + const ctx = yield* ComposioUserContext;
20 + const apiKey = Option.getOrUndefined(ctx.data.apiKey);
21 + if (!apiKey) {
22 + yield* ui.log.warn('No user API key found. Run `composio login` first.');
23 + return;
24 + }
25 +
26 + const clampedLimit = clampLimit(limit);
27 + const defaultOrgId = Option.getOrUndefined(ctx.data.orgId);
28 +
29 + yield* ui.intro(`composio orgs list`);
30 +
31 + const organizations = yield* ui.withSpinner(
32 + 'Loading organizations...',
33 + listOrganizations({
34 + baseURL: ctx.data.baseURL,
35 + apiKey,
36 + limit: clampedLimit,
37 + }),
38 + {
39 + successMessage: result => `Loaded ${result.data.length} orgs`,
40 + errorMessage: 'Failed to fetch organizations',
41 + }
42 + );
43 +
44 + if (organizations.data.length === 0) {
45 + yield* ui.log.warn('No organizations found.');
46 + return;
47 + }
48 +
49 + const lines = organizations.data.map(org => {
50 + const isSelected = defaultOrgId === org.id;
51 + return `${isSelected ? '✓' : ' '} ${org.name} (${org.id})`;
52 + });
53 + yield* ui.log.info(lines.join('\n'));
54 + yield* ui.outro('Hint: run `composio orgs switch` to switch the default global org/project.');
55 +
56 + yield* ui.output(
57 + JSON.stringify(
58 + organizations.data.map(org => ({
59 + id: org.id,
60 + name: org.name,
61 + is_selected_global_org: defaultOrgId === org.id,
62 + }))
63 + )
64 + );
65 + })
66 +).pipe(Command.withDescription('List organizations and show current global selection.'));
ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts new
+185
@@ -0,0 +1,185 @@
1 +import { Command, Options } from '@effect/cli';
2 +import { Effect, Option } from 'effect';
3 +import { requireAuth } from 'src/effects/require-auth';
4 +import { TerminalUI } from 'src/services/terminal-ui';
5 +import {
6 + listOrganizationProjects,
7 + listOrganizations,
8 + type OrganizationSummary,
9 + type OrganizationProjectSummary,
10 +} from 'src/services/composio-clients';
11 +import { ComposioUserContext } from 'src/services/user-context';
12 +import { clampLimit } from 'src/ui/clamp-limit';
13 +
14 +const orgId = Options.text('org-id').pipe(
15 + Options.optional,
16 + Options.withDescription('Organization ID to use as global default')
17 +);
18 +
19 +const projectId = Options.text('project-id').pipe(
20 + Options.optional,
21 + Options.withDescription('Project ID to use as global default')
22 +);
23 +
24 +const limit = Options.integer('limit').pipe(
25 + Options.withDefault(50),
26 + Options.withDescription('Max org/projects to fetch from API (default: 50)')
27 +);
28 +
29 +const selectOrganization = (params: {
30 + organizations: ReadonlyArray<OrganizationSummary>;
31 + selectedOrgId?: string;
32 +}) =>
33 + Effect.gen(function* () {
34 + const { organizations, selectedOrgId } = params;
35 + const ui = yield* TerminalUI;
36 + if (organizations.length === 0) return undefined;
37 +
38 + if (selectedOrgId) {
39 + const explicitMatch = organizations.find(org => org.id === selectedOrgId);
40 + if (explicitMatch) return explicitMatch;
41 + }
42 +
43 + if (organizations.length === 1) return organizations[0];
44 +
45 + return yield* ui.select('Select a default organization (global scope):', [
46 + ...organizations.map(org => ({
47 + value: org,
48 + label: org.name,
49 + hint: org.id,
50 + })),
51 + ]);
52 + });
53 +
54 +const selectProject = (params: {
55 + projects: ReadonlyArray<OrganizationProjectSummary>;
56 + selectedProjectId?: string;
57 +}) =>
58 + Effect.gen(function* () {
59 + const { projects, selectedProjectId } = params;
60 + const ui = yield* TerminalUI;
61 + if (projects.length === 0) return undefined;
62 +
63 + if (selectedProjectId) {
64 + const explicitMatch = projects.find(project => project.id === selectedProjectId);
65 + if (explicitMatch) return explicitMatch;
66 + }
67 +
68 + if (projects.length === 1) return projects[0];
69 +
70 + return yield* ui.select('Select a default project (global scope):', [
71 + ...projects.map(project => ({
72 + value: project,
73 + label: project.name,
74 + hint: project.id,
75 + })),
76 + ]);
77 + });
78 +
79 +export const orgsCmd$Switch = Command.make(
80 + 'switch',
81 + { orgId, projectId, limit },
82 + ({ orgId, projectId, limit }) =>
83 + Effect.gen(function* () {
84 + if (!(yield* requireAuth)) return;
85 +
86 + const ui = yield* TerminalUI;
87 + const ctx = yield* ComposioUserContext;
88 + yield* ui.intro('composio orgs switch');
89 +
90 + const apiKey = Option.getOrUndefined(ctx.data.apiKey);
91 + if (!apiKey) {
92 + yield* ui.log.warn('No user API key found. Run `composio login` first.');
93 + yield* ui.outro('');
94 + return;
95 + }
96 +
97 + const clampedLimit = clampLimit(limit);
98 + const explicitOrgId = Option.getOrUndefined(orgId);
99 + const explicitProjectId = Option.getOrUndefined(projectId);
100 +
101 + yield* ui.note(
102 + 'This updates your default global org/project context for CLI commands. Use `composio init` for per-project local overrides.',
103 + 'Global defaults'
104 + );
105 +
106 + const selectedOrganization =
107 + explicitOrgId !== undefined
108 + ? ({ id: explicitOrgId, name: explicitOrgId } satisfies OrganizationSummary)
109 + : yield* Effect.gen(function* () {
110 + const organizations = yield* listOrganizations({
111 + baseURL: ctx.data.baseURL,
112 + apiKey,
113 + limit: clampedLimit,
114 + });
115 + yield* ui.log.info(`Loaded ${organizations.data.length} orgs`);
116 + return organizations;
117 + }).pipe(
118 + Effect.flatMap(organizations =>
119 + Effect.gen(function* () {
120 + if (organizations.data.length === 0) {
121 + return undefined;
122 + }
123 + return yield* selectOrganization({
124 + organizations: organizations.data,
125 + selectedOrgId: explicitOrgId,
126 + });
127 + })
128 + )
129 + );
130 +
131 + if (!selectedOrganization) {
132 + yield* ui.log.warn('No organizations found for this API key.');
133 + yield* ui.outro('No org selected.');
134 + return;
135 + }
136 + yield* ui.log.info(
137 + `Selected organization: "${selectedOrganization.name}" (${selectedOrganization.id})`
138 + );
139 +
140 + const projects = yield* listOrganizationProjects({
141 + baseURL: ctx.data.baseURL,
142 + apiKey,
143 + orgId: selectedOrganization.id,
144 + limit: clampedLimit,
145 + });
146 + yield* ui.log.info(`Loaded ${projects.data.length} projects`);
147 +
148 + if (projects.data.length === 0) {
149 + yield* ui.log.warn(`No projects found for org "${selectedOrganization.name}".`);
150 + yield* ui.outro('No projects available.');
151 + return;
152 + }
153 +
154 + const selectedProject = yield* selectProject({
155 + projects: projects.data,
156 + selectedProjectId: explicitProjectId,
157 + });
158 +
159 + if (!selectedProject) {
160 + yield* ui.log.warn('No project selected.');
161 + yield* ui.outro('No project selected.');
162 + return;
163 + }
164 + yield* ui.log.info(`Selected project: "${selectedProject.name}" (${selectedProject.id})`);
165 +
166 + yield* ctx.login(
167 + apiKey,
168 + selectedOrganization.id,
169 + selectedProject.id,
170 + Option.getOrUndefined(ctx.data.testUserId)
171 + );
172 +
173 + yield* ui.log.success(
174 + `Updated global defaults to "${selectedOrganization.name}" / "${selectedProject.name}".`
175 + );
176 + yield* ui.output(
177 + JSON.stringify({
178 + scope: 'global',
179 + org_id: selectedOrganization.id,
180 + project_id: selectedProject.id,
181 + })
182 + );
183 + yield* ui.outro('Global org/project defaults updated.');
184 + })
185 +).pipe(Command.withDescription('Switch default global organization/project context.'));
ts/packages/cli/src/commands/orgs/orgs.cmd.ts new
+11
@@ -0,0 +1,11 @@
1 +import { Command } from '@effect/cli';
2 +import { orgsCmd$List } from './commands/orgs.list.cmd';
3 +import { orgsCmd$Switch } from './commands/orgs.switch.cmd';
4 +
5 +/**
6 + * CLI entry point for organization context commands.
7 + */
8 +export const orgsCmd = Command.make('orgs').pipe(
9 + Command.withDescription('Manage default global organization/project context.'),
10 + Command.withSubcommands([orgsCmd$List, orgsCmd$Switch])
11 +);
ts/packages/cli/src/commands/projects/commands/projects.list.cmd.ts new
+86
@@ -0,0 +1,86 @@
1 +import { Command, Options } from '@effect/cli';
2 +import { Effect, Option } from 'effect';
3 +import { requireAuth } from 'src/effects/require-auth';
4 +import { TerminalUI } from 'src/services/terminal-ui';
5 +import { listOrganizationProjects } from 'src/services/composio-clients';
6 +import { ComposioUserContext } from 'src/services/user-context';
7 +import { clampLimit } from 'src/ui/clamp-limit';
8 +
9 +const orgId = Options.text('org-id').pipe(
10 + Options.optional,
11 + Options.withDescription('Organization ID to list projects for (defaults to current global org)')
12 +);
13 +
14 +const limit = Options.integer('limit').pipe(
15 + Options.withDefault(50),
16 + Options.withDescription('Max projects to fetch from API (default: 50)')
17 +);
18 +
19 +export const projectsCmd$List = Command.make('list', { orgId, limit }, ({ orgId, limit }) =>
20 + Effect.gen(function* () {
21 + if (!(yield* requireAuth)) return;
22 +
23 + const ui = yield* TerminalUI;
24 + const ctx = yield* ComposioUserContext;
25 + yield* ui.intro('composio projects list');
26 + const apiKey = Option.getOrUndefined(ctx.data.apiKey);
27 + if (!apiKey) {
28 + yield* ui.log.warn('No user API key found. Run `composio login` first.');
29 + return;
30 + }
31 +
32 + const resolvedOrgId = Option.getOrUndefined(orgId) ?? Option.getOrUndefined(ctx.data.orgId);
33 + if (!resolvedOrgId) {
34 + yield* ui.log.warn('No default org is configured.');
35 + yield* ui.outro('Hint: run `composio orgs switch` first, or pass `--org-id`.');
36 + return;
37 + }
38 +
39 + const clampedLimit = clampLimit(limit);
40 + const defaultOrgId = Option.getOrUndefined(ctx.data.orgId);
41 + const defaultProjectId = Option.getOrUndefined(ctx.data.projectId);
42 +
43 + const projects = yield* ui.withSpinner(
44 + 'Loading projects...',
45 + listOrganizationProjects({
46 + baseURL: ctx.data.baseURL,
47 + apiKey,
48 + orgId: resolvedOrgId,
49 + limit: clampedLimit,
50 + }),
51 + {
52 + successMessage: result => `Loaded ${result.data.length} projects`,
53 + errorMessage: 'Failed to fetch projects',
54 + }
55 + );
56 +
57 + if (projects.data.length === 0) {
58 + yield* ui.log.warn('No projects found.');
59 + yield* ui.outro('Hint: run `composio orgs switch` to switch org/project defaults.');
60 + return;
61 + }
62 +
63 + const lines = projects.data.map(project => {
64 + const isSelected = defaultOrgId === resolvedOrgId && defaultProjectId === project.id;
65 + return `${isSelected ? '✓' : ' '} ${project.name} (${project.id})`;
66 + });
67 + yield* ui.log.step(lines.join('\n'));
68 + yield* ui.outro(
69 + [
70 + 'Hint: run `composio projects switch` to switch the default global project.',
71 + 'Run `composio orgs switch` to switch org and project together.',
72 + ].join('\n')
73 + );
74 +
75 + yield* ui.output(
76 + JSON.stringify(
77 + projects.data.map(project => ({
78 + id: project.id,
79 + name: project.name,
80 + is_selected_global_project:
81 + defaultOrgId === resolvedOrgId && defaultProjectId === project.id,
82 + }))
83 + )
84 + );
85 + })
86 +).pipe(Command.withDescription('List projects and show current global selection.'));
ts/packages/cli/src/commands/projects/commands/projects.switch.cmd.ts new
+132
@@ -0,0 +1,132 @@
1 +import { Command, Options } from '@effect/cli';
2 +import { Effect, Option } from 'effect';
3 +import { requireAuth } from 'src/effects/require-auth';
4 +import { TerminalUI } from 'src/services/terminal-ui';
5 +import {
6 + listOrganizationProjects,
7 + type OrganizationProjectSummary,
8 +} from 'src/services/composio-clients';
9 +import { ComposioUserContext } from 'src/services/user-context';
10 +import { clampLimit } from 'src/ui/clamp-limit';
11 +
12 +const orgId = Options.text('org-id').pipe(
13 + Options.optional,
14 + Options.withDescription('Organization ID to use while switching project')
15 +);
16 +
17 +const projectId = Options.text('project-id').pipe(
18 + Options.optional,
19 + Options.withDescription('Project ID to use as global default')
20 +);
21 +
22 +const limit = Options.integer('limit').pipe(
23 + Options.withDefault(50),
24 + Options.withDescription('Max projects to fetch from API (default: 50)')
25 +);
26 +
27 +const selectProject = (params: {
28 + projects: ReadonlyArray<OrganizationProjectSummary>;
29 + selectedProjectId?: string;
30 +}) =>
31 + Effect.gen(function* () {
32 + const { projects, selectedProjectId } = params;
33 + const ui = yield* TerminalUI;
34 + if (projects.length === 0) return undefined;
35 +
36 + if (selectedProjectId) {
37 + const explicitMatch = projects.find(project => project.id === selectedProjectId);
38 + if (explicitMatch) return explicitMatch;
39 + }
40 +
41 + if (projects.length === 1) return projects[0];
42 +
43 + return yield* ui.select('Select a default project (global scope):', [
44 + ...projects.map(project => ({
45 + value: project,
46 + label: project.name,
47 + hint: project.id,
48 + })),
49 + ]);
50 + });
51 +
52 +export const projectsCmd$Switch = Command.make(
53 + 'switch',
54 + { orgId, projectId, limit },
55 + ({ orgId, projectId, limit }) =>
56 + Effect.gen(function* () {
57 + if (!(yield* requireAuth)) return;
58 +
59 + const ui = yield* TerminalUI;
60 + const ctx = yield* ComposioUserContext;
61 + yield* ui.intro('composio projects switch');
62 +
63 + const apiKey = Option.getOrUndefined(ctx.data.apiKey);
64 + if (!apiKey) {
65 + yield* ui.log.warn('No user API key found. Run `composio login` first.');
66 + yield* ui.outro('');
67 + return;
68 + }
69 +
70 + const resolvedOrgId = Option.getOrUndefined(orgId) ?? Option.getOrUndefined(ctx.data.orgId);
71 + if (!resolvedOrgId) {
72 + yield* ui.log.warn('No default org is configured.');
73 + yield* ui.log.info('Run `composio orgs switch` to select org and project globally.');
74 + yield* ui.outro('');
75 + return;
76 + }
77 +
78 + const clampedLimit = clampLimit(limit);
79 + const explicitProjectId = Option.getOrUndefined(projectId);
80 +
81 + yield* ui.note(
82 + 'This updates your default global project context. To switch organization, use `composio orgs switch`.',
83 + 'Global defaults'
84 + );
85 + yield* ui.log.info(`Using organization: ${resolvedOrgId}`);
86 +
87 + const projects = yield* listOrganizationProjects({
88 + baseURL: ctx.data.baseURL,
89 + apiKey,
90 + orgId: resolvedOrgId,
91 + limit: clampedLimit,
92 + });
93 + yield* ui.log.info(`Loaded ${projects.data.length} projects`);
94 +
95 + if (projects.data.length === 0) {
96 + yield* ui.log.warn('No projects found for the selected org.');
97 + yield* ui.log.info('Use `composio orgs switch` to switch to another organization.');
98 + yield* ui.outro('No projects available.');
99 + return;
100 + }
101 +
102 + const selectedProject = yield* selectProject({
103 + projects: projects.data,
104 + selectedProjectId: explicitProjectId,
105 + });
106 +
107 + if (!selectedProject) {
108 + yield* ui.log.warn('No project selected.');
109 + yield* ui.outro('No project selected.');
110 + return;
111 + }
112 + yield* ui.log.info(`Selected project: "${selectedProject.name}" (${selectedProject.id})`);
113 +
114 + yield* ctx.login(
115 + apiKey,
116 + resolvedOrgId,
117 + selectedProject.id,
118 + Option.getOrUndefined(ctx.data.testUserId)
119 + );
120 +
121 + yield* ui.log.success(`Updated global default project to "${selectedProject.name}".`);
122 + yield* ui.log.info('To switch organization as well, run `composio orgs switch`.');
123 + yield* ui.output(
124 + JSON.stringify({
125 + scope: 'global',
126 + org_id: resolvedOrgId,
127 + project_id: selectedProject.id,
128 + })
129 + );
130 + yield* ui.outro('Global project default updated.');
131 + })
132 +).pipe(Command.withDescription('Switch default global project context.'));
ts/packages/cli/src/commands/projects/projects.cmd.ts new
+11
@@ -0,0 +1,11 @@
1 +import { Command } from '@effect/cli';
2 +import { projectsCmd$List } from './commands/projects.list.cmd';
3 +import { projectsCmd$Switch } from './commands/projects.switch.cmd';
4 +
5 +/**
6 + * CLI entry point for project context commands.
7 + */
8 +export const projectsCmd = Command.make('projects').pipe(
9 + Command.withDescription('Manage default global project context.'),
10 + Command.withSubcommands([projectsCmd$List, projectsCmd$Switch])
11 +);
ts/packages/cli/src/commands/whoami.cmd.ts
+20 -2
@@ -25,9 +25,27 @@ export const whoamiCmd = Command.make('whoami', {}).pipe(
25 onSome: apiKey =>
26 Effect.gen(function* () {
27 const redactedApiKey = redact({ value: apiKey, prefix: 'ak_' });
28 + const defaultOrgId = Option.getOrUndefined(ctx.data.orgId);
29 + const defaultProjectId = Option.getOrUndefined(ctx.data.projectId);
30 + const testUserId = Option.getOrUndefined(ctx.data.testUserId);
31
29 - yield* ui.note(redactedApiKey, 'API Key');
30 - yield* ui.output(apiKey);
32 + yield* ui.note(
33 + [
34 + `Global User API Key: ${redactedApiKey}`,
35 + `Default Org ID: ${defaultOrgId ?? 'not set'}`,
36 + `Default Project ID: ${defaultProjectId ?? 'not set'}`,
37 + `Test User ID: ${testUserId ?? 'not set'}`,
38 + ].join('\n'),
39 + 'Global User Context'
40 + );
41 + yield* ui.output(
42 + JSON.stringify({
43 + global_user_api_key: apiKey,
44 + default_org_id: defaultOrgId ?? null,
45 + default_project_id: defaultProjectId ?? null,
46 + test_user_id: testUserId ?? null,
47 + })
48 + );
49 }),
50 })
51 );
ts/packages/cli/src/services/composio-clients.ts
+155 -2
@@ -712,6 +712,159 @@ export const OrgProjectListResponse = Schema.Struct({
712 }).annotations({ identifier: 'OrgProjectListResponse' });
713 export type OrgProjectListResponse = Schema.Schema.Type<typeof OrgProjectListResponse>;
714
715 +export interface OrganizationSummary {
716 + readonly id: string;
717 + readonly name: string;
718 +}
719 +
720 +export interface OrganizationListResponse {
721 + readonly data: ReadonlyArray<OrganizationSummary>;
722 + readonly total_items: number;
723 +}
724 +
725 +export interface OrganizationProjectSummary {
726 + readonly id: string;
727 + readonly name: string;
728 +}
729 +
730 +export interface OrganizationProjectListResponse {
731 + readonly data: ReadonlyArray<OrganizationProjectSummary>;
732 + readonly total_items: number;
733 +}
734 +
735 +const extractArrayPayload = (json: unknown): ReadonlyArray<unknown> => {
736 + if (Array.isArray(json)) return json;
737 + if (json && typeof json === 'object') {
738 + const record = json as Record<string, unknown>;
739 + if (Array.isArray(record.organizations)) return record.organizations;
740 + if (Array.isArray(record.projects)) return record.projects;
741 + if (Array.isArray(record.data)) return record.data;
742 + if (Array.isArray(record.items)) return record.items;
743 + if (record.data && typeof record.data === 'object') {
744 + const nested = record.data as Record<string, unknown>;
745 + if (Array.isArray(nested.organizations)) return nested.organizations;
746 + if (Array.isArray(nested.projects)) return nested.projects;
747 + if (Array.isArray(nested.items)) return nested.items;
748 + if (Array.isArray(nested.data)) return nested.data;
749 + }
750 + }
751 + return [];
752 +};
753 +
754 +const readIdFromItem = (item: unknown): string | undefined => {
755 + if (!item || typeof item !== 'object') return undefined;
756 + const record = item as Record<string, unknown>;
757 + if (typeof record.id === 'string') return record.id;
758 + if (typeof record.nano_id === 'string') return record.nano_id;
759 + if (typeof record.org_id === 'string') return record.org_id;
760 + if (typeof record.project_id === 'string') return record.project_id;
761 + return undefined;
762 +};
763 +
764 +const readNameFromItem = (item: unknown): string | undefined => {
765 + if (!item || typeof item !== 'object') return undefined;
766 + const record = item as Record<string, unknown>;
767 + if (typeof record.name === 'string' && record.name.trim().length > 0) return record.name;
768 + if (typeof record.slug === 'string' && record.slug.trim().length > 0) return record.slug;
769 + return undefined;
770 +};
771 +
772 +/**
773 + * Lists organizations available to the current user API key.
774 + * Uses plain fetch since this endpoint is not available in @composio/client.
775 + */
776 +export const listOrganizations = (params: {
777 + baseURL: string;
778 + apiKey: string;
779 + limit?: number;
780 +}): Effect.Effect<OrganizationListResponse, HttpServerError | HttpDecodingError> =>
781 + Effect.gen(function* () {
782 + const limit = params.limit ?? 50;
783 + const response = yield* Effect.tryPromise({
784 + try: () =>
785 + fetch(`${params.baseURL}/api/v3/org/list?limit=${limit}`, {
786 + method: 'GET',
787 + redirect: 'error',
788 + headers: {
789 + 'x-user-api-key': params.apiKey,
790 + 'User-Agent': '@composio/cli',
791 + Accept: 'application/json',
792 + 'Content-Type': 'application/json',
793 + },
794 + }),
795 + catch: error => new HttpServerError({ cause: error }),
796 + });
797 +
798 + if (!response.ok) {
799 + return yield* handleHttpErrorResponse(response);
800 + }
801 +
802 + const { json } = yield* streamResponseWithByteCount(response);
803 + const items = extractArrayPayload(json);
804 + const organizations = items
805 + .map(item => {
806 + const id = readIdFromItem(item);
807 + const name = readNameFromItem(item);
808 + if (!id || !name) return undefined;
809 + return { id, name } satisfies OrganizationSummary;
810 + })
811 + .filter((value): value is OrganizationSummary => value !== undefined);
812 +
813 + return {
814 + data: organizations,
815 + total_items: organizations.length,
816 + };
817 + });
818 +
819 +/**
820 + * Lists projects for a specific organization.
821 + * Uses plain fetch since this endpoint is not available in @composio/client.
822 + */
823 +export const listOrganizationProjects = (params: {
824 + baseURL: string;
825 + apiKey: string;
826 + orgId: string;
827 + limit?: number;
828 +}): Effect.Effect<OrganizationProjectListResponse, HttpServerError | HttpDecodingError> =>
829 + Effect.gen(function* () {
830 + const limit = params.limit ?? 50;
831 + const response = yield* Effect.tryPromise({
832 + try: () =>
833 + fetch(`${params.baseURL}/api/v3/org/project/list?limit=${limit}`, {
834 + method: 'GET',
835 + redirect: 'error',
836 + headers: {
837 + 'x-user-api-key': params.apiKey,
838 + 'x-org-id': params.orgId,
839 + 'User-Agent': '@composio/cli',
840 + Accept: 'application/json',
841 + 'Content-Type': 'application/json',
842 + },
843 + }),
844 + catch: error => new HttpServerError({ cause: error }),
845 + });
846 +
847 + if (!response.ok) {
848 + return yield* handleHttpErrorResponse(response);
849 + }
850 +
851 + const { json } = yield* streamResponseWithByteCount(response);
852 + const items = extractArrayPayload(json);
853 + const projects = items
854 + .map(item => {
855 + const id = readIdFromItem(item);
856 + const name = readNameFromItem(item);
857 + if (!id || !name) return undefined;
858 + return { id, name } satisfies OrganizationProjectSummary;
859 + })
860 + .filter((value): value is OrganizationProjectSummary => value !== undefined);
861 +
862 + return {
863 + data: projects,
864 + total_items: projects.length,
865 + };
866 + });
867 +
868 /**
869 * Lists all projects for the logged-in user's organization.
870 * Uses plain fetch since this endpoint is not available in @composio/client.
@@ -719,7 +872,7 @@ export type OrgProjectListResponse = Schema.Schema.Type<typeof OrgProjectListRes
872 * @param params.baseURL - API base URL
873 * @param params.apiKey - UAK (sent as `x-user-api-key`)
874 * @param params.orgId - Organization ID (sent as `x-org-id`)
722 - * @param params.limit - Max projects to return (default 100)
875 + * @param params.limit - Max projects to return (default 50)
876 */
877 export const listOrgProjects = (params: {
878 baseURL: string;
@@ -728,7 +881,7 @@ export const listOrgProjects = (params: {
881 limit?: number;
882 }): Effect.Effect<OrgProjectListResponse, HttpServerError | HttpDecodingError> =>
883 Effect.gen(function* () {
731 - const limit = params.limit ?? 100;
884 + const limit = params.limit ?? 50;
885 const response = yield* Effect.tryPromise({
886 try: () =>
887 fetch(
ts/packages/cli/test/__fixtures__/user-config-with-global-context/.composio/user_data.json new
+5
@@ -0,0 +1,5 @@
1 +{
2 + "api_key": "uak_test_key",
3 + "org_id": "org_1",
4 + "project_id": "project_1"
5 +}
ts/packages/cli/test/src/commands/$default.cmd.test.ts
+1 -1
@@ -15,7 +15,7 @@ describe('CLI: composio', () => {
15 expect(result).toEqual(
16 ValidationError.commandMismatch(
17 HelpDoc.p(
18 - "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'init', 'generate', 'py', 'ts', 'toolkits', 'tools', 'auth-configs', 'connected-accounts', 'triggers', 'logs'"
18 + "Invalid subcommand for composio - use one of 'version', 'upgrade', 'whoami', 'login', 'logout', 'init', 'generate', 'py', 'ts', 'toolkits', 'tools', 'auth-configs', 'connected-accounts', 'triggers', 'logs', 'orgs', 'projects'"
19 )
20 )
21 );
ts/packages/cli/test/src/commands/__snapshots__/$default.cmd.test.ts.snap
+14
@@ -63,6 +63,8 @@ Environment Variables:
63
64 - toolkits search [--limit integer] <query> Search toolkits by use case.
65
66 + - toolkits version <slug> Show latest and recent versions for a toolkit.
67 +
68 - tools Discover and inspect Composio tools.
69
70 - tools list [--query text] [--toolkits text] [--tags text] [--limit integer] List available tools.
@@ -118,5 +120,17 @@ Environment Variables:
120 - logs triggers [--cursor text] [--user-id text] [--connected-account-id text] [--trigger text] [--trigger-id text] [--log-id text] [--from integer] [--to integer] [--limit integer] [--time 5m | 30m | 6h | 1d | 1w | 1month | 1y] [--search text] [--include-payload] [<log_id>] List trigger logs.
121
122 - logs tools [--cursor integer] [--from integer] [--to integer] [--limit integer] [--case-sensitive] [--toolkit text] [--tool text] [--connected-account-id text] [--auth-config-id text] [--status text] [--user-id text] [--log-id text] [--tool-router-session-id text] [--session-id text] [<log_id>] List tool execution logs, or pass a log_id to fetch a specific log.
123 +
124 + - orgs Manage default global organization/project context.
125 +
126 + - orgs list [--limit integer] List organizations and show current global selection.
127 +
128 + - orgs switch [--org-id text] [--project-id text] [--limit integer] Switch default global organization/project context.
129 +
130 + - projects Manage default global project context.
131 +
132 + - projects list [--org-id text] [--limit integer] List projects and show current global selection.
133 +
134 + - projects switch [--org-id text] [--project-id text] [--limit integer] Switch default global project context.
135 "
136 `;
ts/packages/cli/test/src/commands/orgs/orgs.list.cmd.test.ts new
+48
@@ -0,0 +1,48 @@
1 +import { Effect } from 'effect';
2 +import { describe, expect, layer } from '@effect/vitest';
3 +import { afterEach, vi } from 'vitest';
4 +import { cli, MockConsole, TestLive } from 'test/__utils__';
5 +
6 +const mockFetchResponse = (body: unknown, status = 200) =>
7 + new Response(JSON.stringify(body), {
8 + status,
9 + headers: { 'Content-Type': 'application/json' },
10 + });
11 +
12 +describe('CLI: composio orgs list', () => {
13 + afterEach(() => {
14 + vi.restoreAllMocks();
15 + });
16 +
17 + layer(TestLive({ fixture: 'user-config-with-global-context' }))(it => {
18 + it.scoped('[Then] lists orgs, marks selected global org, and shows switch hint', () =>
19 + Effect.gen(function* () {
20 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
21 + mockFetchResponse({
22 + organizations: [
23 + { id: 'org_1', name: 'Org One' },
24 + { id: 'org_2', name: 'Org Two' },
25 + ],
26 + })
27 + );
28 +
29 + yield* cli(['orgs', 'list']);
30 +
31 + expect(fetchSpy).toHaveBeenCalledTimes(1);
32 + const [orgUrl, orgRequest] = fetchSpy.mock.calls[0]!;
33 + expect(orgUrl).toContain('/api/v3/org/list?limit=50');
34 + expect((orgRequest as RequestInit).headers).toMatchObject({
35 + 'x-user-api-key': 'uak_test_key',
36 + });
37 +
38 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
39 + expect(output).toContain('Loaded 2 orgs');
40 + expect(output).toContain('✓ Org One (org_1)');
41 + expect(output).toContain(' Org Two (org_2)');
42 + expect(output).toContain(
43 + 'Hint: run `composio orgs switch` to switch the default global org/project.'
44 + );
45 + })
46 + );
47 + });
48 +});
ts/packages/cli/test/src/commands/orgs/orgs.switch.cmd.test.ts new
+106
@@ -0,0 +1,106 @@
1 +import path from 'node:path';
2 +import { ConfigProvider, Effect } from 'effect';
3 +import { describe, expect, layer } from '@effect/vitest';
4 +import { afterEach, vi } from 'vitest';
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 testConfigProvider = ConfigProvider.fromMap(
11 + new Map([
12 + ['COMPOSIO_USER_API_KEY', 'uak_test_key'],
13 + ['USER_API_KEY', 'uak_test_key'],
14 + ])
15 +);
16 +
17 +const mockFetchResponse = (body: unknown, status = 200) =>
18 + new Response(JSON.stringify(body), {
19 + status,
20 + headers: { 'Content-Type': 'application/json' },
21 + });
22 +
23 +describe('CLI: composio orgs switch', () => {
24 + afterEach(() => {
25 + vi.restoreAllMocks();
26 + });
27 +
28 + layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
29 + it.scoped('[When] no --org-id is provided [Then] lists orgs and projects with limit=50', () =>
30 + Effect.gen(function* () {
31 + const fetchSpy = vi
32 + .spyOn(globalThis, 'fetch')
33 + .mockResolvedValueOnce(
34 + mockFetchResponse({
35 + organizations: [{ id: 'org_1', name: 'Org One' }],
36 + })
37 + )
38 + .mockResolvedValueOnce(
39 + mockFetchResponse({
40 + data: [{ id: 'project_1', name: 'Project One' }],
41 + })
42 + );
43 +
44 + yield* cli(['orgs', 'switch']);
45 +
46 + expect(fetchSpy).toHaveBeenCalledTimes(2);
47 + const [orgUrl, orgRequest] = fetchSpy.mock.calls[0]!;
48 + expect(orgUrl).toContain('/api/v3/org/list?limit=50');
49 + expect((orgRequest as RequestInit).headers).toMatchObject({
50 + 'x-user-api-key': 'uak_test_key',
51 + });
52 +
53 + const [projectUrl, projectRequest] = fetchSpy.mock.calls[1]!;
54 + expect(projectUrl).toContain('/api/v3/org/project/list?limit=50');
55 + expect((projectRequest as RequestInit).headers).toMatchObject({
56 + 'x-user-api-key': 'uak_test_key',
57 + 'x-org-id': 'org_1',
58 + });
59 +
60 + const fs = yield* FileSystem.FileSystem;
61 + const cacheDir = yield* setupCacheDir;
62 + const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
63 + const rawUserConfig = yield* fs.readFileString(userConfigPath, 'utf8');
64 + const userConfig = JSON.parse(rawUserConfig) as Record<string, unknown>;
65 + expect(userConfig.org_id).toBe('org_1');
66 + expect(userConfig.project_id).toBe('project_1');
67 +
68 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
69 + expect(output).toContain('Updated global defaults');
70 + })
71 + );
72 + });
73 +
74 + layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
75 + it.scoped('[When] --org-id is provided [Then] skips org list and selects project', () =>
76 + Effect.gen(function* () {
77 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
78 + mockFetchResponse({
79 + data: [
80 + { id: 'project_1', name: 'Project One' },
81 + { id: 'project_2', name: 'Project Two' },
82 + ],
83 + })
84 + );
85 +
86 + yield* cli(['orgs', 'switch', '--org-id', 'org_manual']);
87 +
88 + expect(fetchSpy).toHaveBeenCalledTimes(1);
89 + const [projectUrl, projectRequest] = fetchSpy.mock.calls[0]!;
90 + expect(projectUrl).toContain('/api/v3/org/project/list?limit=50');
91 + expect((projectRequest as RequestInit).headers).toMatchObject({
92 + 'x-user-api-key': 'uak_test_key',
93 + 'x-org-id': 'org_manual',
94 + });
95 +
96 + const fs = yield* FileSystem.FileSystem;
97 + const cacheDir = yield* setupCacheDir;
98 + const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
99 + const rawUserConfig = yield* fs.readFileString(userConfigPath, 'utf8');
100 + const userConfig = JSON.parse(rawUserConfig) as Record<string, unknown>;
101 + expect(userConfig.org_id).toBe('org_manual');
102 + expect(userConfig.project_id).toBe('project_1');
103 + })
104 + );
105 + });
106 +});
ts/packages/cli/test/src/commands/projects/projects.list.cmd.test.ts new
+50
@@ -0,0 +1,50 @@
1 +import { Effect } from 'effect';
2 +import { describe, expect, layer } from '@effect/vitest';
3 +import { afterEach, vi } from 'vitest';
4 +import { cli, MockConsole, TestLive } from 'test/__utils__';
5 +
6 +const mockFetchResponse = (body: unknown, status = 200) =>
7 + new Response(JSON.stringify(body), {
8 + status,
9 + headers: { 'Content-Type': 'application/json' },
10 + });
11 +
12 +describe('CLI: composio projects list', () => {
13 + afterEach(() => {
14 + vi.restoreAllMocks();
15 + });
16 +
17 + layer(TestLive({ fixture: 'user-config-with-global-context' }))(it => {
18 + it.scoped('[Then] lists projects, marks selected global project, and shows switch hints', () =>
19 + Effect.gen(function* () {
20 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
21 + mockFetchResponse({
22 + data: [
23 + { id: 'project_1', name: 'Project One' },
24 + { id: 'project_2', name: 'Project Two' },
25 + ],
26 + })
27 + );
28 +
29 + yield* cli(['projects', 'list', '--org-id', 'org_1']);
30 +
31 + expect(fetchSpy).toHaveBeenCalledTimes(1);
32 + const [projectUrl, projectRequest] = fetchSpy.mock.calls[0]!;
33 + expect(projectUrl).toContain('/api/v3/org/project/list?limit=50');
34 + expect((projectRequest as RequestInit).headers).toMatchObject({
35 + 'x-user-api-key': 'uak_test_key',
36 + 'x-org-id': 'org_1',
37 + });
38 +
39 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
40 + expect(output).toContain('Loaded 2 projects');
41 + expect(output).toContain('✓ Project One (project_1)');
42 + expect(output).toContain(' Project Two (project_2)');
43 + expect(output).toContain(
44 + 'Hint: run `composio projects switch` to switch the default global project.'
45 + );
46 + expect(output).toContain('Run `composio orgs switch` to switch org and project together.');
47 + })
48 + );
49 + });
50 +});
ts/packages/cli/test/src/commands/projects/projects.switch.cmd.test.ts new
+65
@@ -0,0 +1,65 @@
1 +import path from 'node:path';
2 +import { ConfigProvider, Effect } from 'effect';
3 +import { describe, expect, layer } from '@effect/vitest';
4 +import { afterEach, vi } from 'vitest';
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 testConfigProvider = ConfigProvider.fromMap(
11 + new Map([
12 + ['COMPOSIO_USER_API_KEY', 'uak_test_key'],
13 + ['USER_API_KEY', 'uak_test_key'],
14 + ])
15 +);
16 +
17 +const mockFetchResponse = (body: unknown, status = 200) =>
18 + new Response(JSON.stringify(body), {
19 + status,
20 + headers: { 'Content-Type': 'application/json' },
21 + });
22 +
23 +describe('CLI: composio projects switch', () => {
24 + afterEach(() => {
25 + vi.restoreAllMocks();
26 + });
27 +
28 + layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
29 + it.scoped(
30 + '[When] --org-id is provided [Then] it switches global project and shows org hint',
31 + () =>
32 + Effect.gen(function* () {
33 + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
34 + mockFetchResponse({
35 + data: [
36 + { id: 'project_1', name: 'Project One' },
37 + { id: 'project_2', name: 'Project Two' },
38 + ],
39 + })
40 + );
41 +
42 + yield* cli(['projects', 'switch', '--org-id', 'org_manual']);
43 +
44 + expect(fetchSpy).toHaveBeenCalledTimes(1);
45 + const [projectUrl, projectRequest] = fetchSpy.mock.calls[0]!;
46 + expect(projectUrl).toContain('/api/v3/org/project/list?limit=50');
47 + expect((projectRequest as RequestInit).headers).toMatchObject({
48 + 'x-user-api-key': 'uak_test_key',
49 + 'x-org-id': 'org_manual',
50 + });
51 +
52 + const fs = yield* FileSystem.FileSystem;
53 + const cacheDir = yield* setupCacheDir;
54 + const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
55 + const rawUserConfig = yield* fs.readFileString(userConfigPath, 'utf8');
56 + const userConfig = JSON.parse(rawUserConfig) as Record<string, unknown>;
57 + expect(userConfig.org_id).toBe('org_manual');
58 + expect(userConfig.project_id).toBe('project_1');
59 +
60 + const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
61 + expect(output).toContain('To switch organization as well, run `composio orgs switch`.');
62 + })
63 + );
64 + });
65 +});
ts/packages/cli/test/src/commands/whoami.cmd.test.ts
+10 -2
@@ -9,7 +9,7 @@ describe('CLI: composio whoami', () => {
9 ).pipe(extendConfigProvider);
10
11 layer(TestLive({ baseConfigProvider: testConfigProvider }))('with config override', it => {
12 - it.scoped('[Given] `COMPOSIO_USER_API_KEY` [Then] prints it to stdout', () =>
12 + it.scoped('[Given] `COMPOSIO_USER_API_KEY` [Then] prints global user context JSON', () =>
13 Effect.gen(function* () {
14 const args = ['whoami'];
15 yield* cli(args);
@@ -17,12 +17,16 @@ describe('CLI: composio whoami', () => {
17 const lines = yield* MockConsole.getLines();
18 const output = lines.join('\n');
19 expect(output).toContain(`api_key_from_test_config_provider`);
20 + expect(output).toContain(`"global_user_api_key":"api_key_from_test_config_provider"`);
21 + expect(output).toContain(`"default_org_id":null`);
22 + expect(output).toContain(`"default_project_id":null`);
23 + expect(output).toContain(`"test_user_id":null`);
24 })
25 );
26 });
27
28 layer(TestLive({ fixture: 'user-config-example' }))('with fixture', it => {
25 - it.scoped('[Given] user_data.json in fixture [Then] prints its `api_key` to stdout', () =>
29 + it.scoped('[Given] user_data.json in fixture [Then] prints global user context JSON', () =>
30 Effect.gen(function* () {
31 const args = ['whoami'];
32 yield* cli(args);
@@ -30,6 +34,10 @@ describe('CLI: composio whoami', () => {
34 const lines = yield* MockConsole.getLines();
35 const output = lines.join('\n');
36 expect(output).toContain(`api_key_from_test_fixture`);
37 + expect(output).toContain(`"global_user_api_key":"api_key_from_test_fixture"`);
38 + expect(output).toContain(`"default_org_id":null`);
39 + expect(output).toContain(`"default_project_id":null`);
40 + expect(output).toContain(`"test_user_id":null`);
41 })
42 );
43 });