Skip to content

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

Add connection removal CLI (#3259)

Rahul Tarakd80e109e2641
diff --git a/ts/packages/cli/README.md b/ts/packages/cli/README.md
index 7fa5b7de0..1c8a4fd8c 100644
--- a/ts/packages/cli/README.md
+++ b/ts/packages/cli/README.md
@@ -39,6 +39,7 @@ composio [--log-level all|trace|debug|info|warning|error|fatal|none]
- `composio tools list|info`: Inspect available tools and their cached schemas.
- `composio triggers list <toolkit>|info`: Inspect toolkit-scoped trigger types and their schemas.
- `composio connections list [--toolkit <toolkit>]`: Print toolkit connection statuses as JSON.
+- `composio connections remove <account>`: Interactively remove a toolkit connection after confirmation.
- `composio artifacts cwd`: Print the cwd-scoped CLI session artifacts directory.
- `composio dev <subcommand>`: Developer workflows for init, playground execution, logs, toolkits, auth configs, accounts, triggers, orgs, and projects.
- `composio generate [-o, --output-dir <directory>] [--toolkits <toolkit>] [--type-tools]`: Auto-detect the project language (Python or TypeScript) and generate type stubs for toolkits, tools, and triggers.
diff --git a/ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts b/ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts
new file mode 100644
index 000000000..ab0893720
--- /dev/null
+++ b/ts/packages/cli/src/commands/connections/commands/connections.remove.cmd.ts
@@ -0,0 +1,146 @@
+import { Args, Command } from '@effect/cli';
+import { Effect, Schema } from 'effect';
+import { requireAuth } from 'src/effects/require-auth';
+import type { ConnectedAccountItem } from 'src/models/connected-accounts';
+import {
+ ComposioClientSingleton,
+ ConnectedAccountListResponse,
+} from 'src/services/composio-clients';
+import {
+ formatResolveCommandProjectError,
+ resolveCommandProject,
+} from 'src/services/command-project';
+import { TerminalUI } from 'src/services/terminal-ui';
+import { bold } from 'src/ui/colors';
+import { redact } from 'src/ui/redact';
+
+const account = Args.text({ name: 'account' }).pipe(
+ Args.withDescription('Connection selector: toolkit slug, alias, word_id, or connected account ID')
+);
+
+const normalizeSelector = (value: string): string => value.trim().toLowerCase();
+
+const selectorMatches = (item: ConnectedAccountItem, selector: string): boolean => {
+ const normalized = normalizeSelector(selector);
+ return (
+ normalizeSelector(item.id) === normalized ||
+ normalizeSelector(item.alias ?? '') === normalized ||
+ normalizeSelector(item.word_id ?? '') === normalized ||
+ normalizeSelector(item.toolkit.slug) === normalized
+ );
+};
+
+const formatAccountSummary = (item: ConnectedAccountItem): string =>
+ [
+ `${bold('Toolkit:')} ${item.toolkit.slug}`,
+ `${bold('Alias:')} ${item.alias || '-'}`,
+ `${bold('Word Id:')} ${item.word_id || '-'}`,
+ `${bold('Connected Account:')} ${redact({ value: item.id, prefix: 'con_' })}`,
+ `${bold('Status:')} ${item.status}`,
+ ].join('\n');
+
+const formatAccountChoice = (item: ConnectedAccountItem): string => {
+ const labels = [item.alias, item.word_id].filter(
+ (value): value is string => typeof value === 'string' && value.trim().length > 0
+ );
+ const selectors = labels.length > 0 ? ` (${labels.join(' / ')})` : '';
+ return `${item.toolkit.slug}${selectors}: ${redact({ value: item.id, prefix: 'con_' })}`;
+};
+
+const resolveAccount = (params: {
+ readonly accounts: ReadonlyArray<ConnectedAccountItem>;
+ readonly selector: string;
+}): ConnectedAccountItem | { readonly error: string } => {
+ const matches = params.accounts.filter(item => selectorMatches(item, params.selector));
+
+ if (matches.length === 0) {
+ return {
+ error: `No connection matched "${params.selector}". Run \`composio connections list\` to inspect available connections.`,
+ };
+ }
+
+ const idMatches = matches.filter(
+ item => normalizeSelector(item.id) === normalizeSelector(params.selector)
+ );
+ if (idMatches.length === 1) {
+ return idMatches[0]!;
+ }
+
+ if (matches.length === 1) {
+ return matches[0]!;
+ }
+
+ return {
+ error: [
+ `Multiple connections matched "${params.selector}". Use a unique alias, word_id, or connected account ID.`,
+ '',
+ ...matches.map(item => `- ${formatAccountChoice(item)}`),
+ ].join('\n'),
+ };
+};
+
+export const connectionsCmd$Remove = Command.make('remove', { account }, ({ account }) =>
+ Effect.gen(function* () {
+ if (!(yield* requireAuth)) return;
+
+ const ui = yield* TerminalUI;
+ const clientSingleton = yield* ComposioClientSingleton;
+ const resolvedProject = yield* resolveCommandProject({
+ mode: 'consumer',
+ }).pipe(Effect.mapError(formatResolveCommandProjectError));
+
+ const consumerUserId = resolvedProject.consumerUserId;
+ if (!consumerUserId) {
+ return yield* Effect.fail(
+ new Error('Missing consumer user id. Run `composio login` and try again.')
+ );
+ }
+
+ const client = yield* clientSingleton.getFor({
+ orgId: resolvedProject.orgId,
+ projectId: resolvedProject.projectId,
+ });
+ const rawResult = yield* ui.withSpinner(
+ 'Fetching connections...',
+ Effect.tryPromise(() =>
+ client.connectedAccounts.list({
+ user_ids: [consumerUserId],
+ limit: 1000,
+ })
+ )
+ );
+ const result = yield* Schema.decodeUnknown(ConnectedAccountListResponse)(rawResult);
+ const resolved = resolveAccount({ accounts: result.items, selector: account });
+
+ if ('error' in resolved) {
+ yield* ui.log.warn(resolved.error);
+ return;
+ }
+
+ yield* ui.note(
+ `${formatAccountSummary(resolved)}\n\nThis will remove the connection from Composio and tools will no longer be able to use it.`,
+ 'Remove Connection'
+ );
+
+ const confirmed = yield* ui.confirm(`Remove ${resolved.toolkit.slug} connection?`, {
+ defaultValue: false,
+ });
+ if (!confirmed) {
+ yield* ui.log.warn('No connection removed.');
+ return;
+ }
+
+ yield* ui.withSpinner(
+ `Removing ${resolved.toolkit.slug} connection...`,
+ Effect.tryPromise(() => client.connectedAccounts.delete(resolved.id)),
+ {
+ successMessage: `Removed ${resolved.toolkit.slug} connection.`,
+ errorMessage: `Failed to remove ${resolved.toolkit.slug} connection.`,
+ }
+ );
+ })
+).pipe(
+ Command.withDescription(
+ 'Interactively remove a connection by toolkit slug, alias, word_id, or connected account ID.'
+ )
+);
diff --git a/ts/packages/cli/src/commands/connections/connections.cmd.ts b/ts/packages/cli/src/commands/connections/connections.cmd.ts
index d13e084af..bf42af48a 100644
--- a/ts/packages/cli/src/commands/connections/connections.cmd.ts
+++ b/ts/packages/cli/src/commands/connections/connections.cmd.ts
@@ -1,7 +1,8 @@
import { Command } from '@effect/cli';
import { connectionsCmd$List } from './commands/connections.list.cmd';
+import { connectionsCmd$Remove } from './commands/connections.remove.cmd';
export const rootConnectionsCmd = Command.make('connections').pipe(
- Command.withDescription('Inspect connected toolkit accounts in a script-friendly format.'),
- Command.withSubcommands([connectionsCmd$List])
+ Command.withDescription('Inspect and remove connected toolkit accounts.'),
+ Command.withSubcommands([connectionsCmd$List, connectionsCmd$Remove])
);
diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.ts
index b7c4c63fd..1203fd8e2 100644
--- a/ts/packages/cli/src/commands/root-help.ts
+++ b/ts/packages/cli/src/commands/root-help.ts
@@ -181,6 +181,7 @@ const FULL_COMMANDS: ReadonlyArray<TaggedValue<CompactCommand>> = [
full({ name: 'triggers list', description: 'List trigger types for a toolkit' }),
full({ name: 'triggers info', description: 'Inspect a trigger type and schema summary' }),
full({ name: 'connections list', description: 'Print toolkit connection statuses as JSON' }),
+ full({ name: 'connections remove', description: 'Interactively remove a toolkit connection' }),
full({ name: 'generate ts', description: 'Generate TypeScript stubs for selected toolkits' }),
full({ name: 'generate py', description: 'Generate Python stubs for selected toolkits' }),
full({
@@ -551,6 +552,26 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHel
'composio dev connected-accounts list Inspect the full connected-account table',
],
},
+ 'connections remove': {
+ usage: 'composio connections remove <account>',
+ description:
+ 'Interactively remove a connected toolkit account. The command prompts for confirmation and defaults to No.',
+ args: [
+ {
+ name: '<account>',
+ description: 'Toolkit slug, alias, word_id, or connected account ID',
+ },
+ ],
+ examples: [
+ 'composio connections remove gmail',
+ 'composio connections remove work',
+ 'composio connections remove castle',
+ ],
+ seeAlso: [
+ 'composio connections list Find connection selectors',
+ 'composio link <toolkit> Reconnect a toolkit account',
+ ],
+ },
run: {
usage: 'composio run <code> [-- ...args] | run -f <file> [-- ...args]',
description:
diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.ts
index aba4d85a4..2d657d9f2 100644
--- a/ts/packages/cli/test/__utils__/services/test-layer.ts
+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts
@@ -109,6 +109,7 @@ export interface TestLiveInput {
items?: ConnectedAccountItem[];
linkResponse?: LinkCreateResponse;
onPatch?: (params: { path: string; body: Record<string, unknown> | undefined }) => void;
+ onDelete?: (nanoid: string) => void;
};
/**
@@ -1058,6 +1059,14 @@ export const TestLayer = (input?: TestLiveInput) =>
}
return found;
},
+ delete: async (nanoid: string) => {
+ const found = connectedAccountsData.items.find(item => item.id === nanoid);
+ if (!found) {
+ throw new Error(`Connected account "${nanoid}" not found`);
+ }
+ connectedAccountsData.onDelete?.(nanoid);
+ return {};
+ },
},
triggerInstances: {
upsert: async (
diff --git a/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts b/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
index d3a95efd5..116e58875 100644
--- a/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/connections/connections.list.cmd.test.ts
@@ -1,7 +1,8 @@
import { describe, expect, layer } from '@effect/vitest';
-import { ConfigProvider, Effect } from 'effect';
+import { ConfigProvider, Console, Effect } from 'effect';
import type { ConnectedAccountItem } from 'src/models/connected-accounts';
import { extendConfigProvider } from 'src/services/config';
+import { TerminalUI } from 'src/services/terminal-ui';
import { ComposioUserContext } from 'src/services/user-context';
import { cli, TestLive, MockConsole } from 'test/__utils__';
import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -87,6 +88,40 @@ const testConfigProvider = ConfigProvider.fromMap(
new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
).pipe(extendConfigProvider);
+const terminalUIWithConfirm = (confirmed: boolean) =>
+ TerminalUI.of({
+ output: data => Console.log(data),
+ intro: title => Console.log(`-- ${title} --`),
+ outro: message => Console.log(`-- ${message} --`),
+ log: {
+ info: message => Console.log(message),
+ success: message => Console.log(message),
+ warn: message => Console.warn(message),
+ error: message => Console.error(message),
+ step: message => Console.log(message),
+ message: message => Console.log(message),
+ },
+ note: (message, title) => Console.log(title ? `[${title}] ${message}` : message),
+ select: (_message, options) => Effect.succeed(options[0]!.value),
+ confirm: () => Effect.succeed(confirmed),
+ withSpinner: (message, effect, options) =>
+ Effect.gen(function* () {
+ const result = yield* effect;
+ const successMsg =
+ typeof options?.successMessage === 'function'
+ ? options.successMessage(result)
+ : (options?.successMessage ?? message);
+ yield* Console.log(successMsg);
+ return result;
+ }),
+ useMakeSpinner: (_message, use) =>
+ use({
+ message: (_msg: string) => Effect.void,
+ stop: (msg?: string) => (msg ? Console.log(msg) : Effect.void),
+ error: (msg?: string) => (msg ? Console.error(msg) : Effect.void),
+ }),
+ });
+
describe('CLI: composio connections list', () => {
layer(TestLive({ baseConfigProvider: testConfigProvider, connectedAccountsData }))(it => {
it.scoped('[Given] no filter [Then] prints connection JSON with aliases for duplicates', () =>
@@ -199,3 +234,88 @@ describe('CLI: composio connections list', () => {
);
});
});
+
+describe('CLI: composio connections remove', () => {
+ const confirmedDeleteCalls: string[] = [];
+ layer(
+ TestLive({
+ baseConfigProvider: testConfigProvider,
+ connectedAccountsData: {
+ items: testConnections,
+ onDelete: nanoid => confirmedDeleteCalls.push(nanoid),
+ },
+ terminalUI: terminalUIWithConfirm(true),
+ })
+ )(it => {
+ it.scoped('[Given] a unique toolkit selector and consent [Then] removes that connection', () =>
+ Effect.gen(function* () {
+ confirmedDeleteCalls.length = 0;
+
+ const userContext = yield* ComposioUserContext;
+ yield* userContext.login('test_api_key', 'org_test');
+ yield* cli(['connections', 'remove', 'gmail']);
+
+ expect(confirmedDeleteCalls).toEqual(['con_gmail_active']);
+
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ expect(lines.join('\n')).toContain('Removed gmail connection.');
+ })
+ );
+ });
+
+ const deniedDeleteCalls: string[] = [];
+ layer(
+ TestLive({
+ baseConfigProvider: testConfigProvider,
+ connectedAccountsData: {
+ items: testConnections,
+ onDelete: nanoid => deniedDeleteCalls.push(nanoid),
+ },
+ terminalUI: terminalUIWithConfirm(false),
+ })
+ )(it => {
+ it.scoped('[Given] consent is denied [Then] does not remove the connection', () =>
+ Effect.gen(function* () {
+ deniedDeleteCalls.length = 0;
+
+ const userContext = yield* ComposioUserContext;
+ yield* userContext.login('test_api_key', 'org_test');
+ yield* cli(['connections', 'remove', 'work']);
+
+ expect(deniedDeleteCalls).toEqual([]);
+
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ expect(lines.join('\n')).toContain('No connection removed.');
+ })
+ );
+ });
+
+ const ambiguousDeleteCalls: string[] = [];
+ layer(
+ TestLive({
+ baseConfigProvider: testConfigProvider,
+ connectedAccountsData: {
+ items: testConnections,
+ onDelete: nanoid => ambiguousDeleteCalls.push(nanoid),
+ },
+ terminalUI: terminalUIWithConfirm(true),
+ })
+ )(it => {
+ it.scoped(
+ '[Given] a selector matches multiple accounts [Then] asks for a unique selector',
+ () =>
+ Effect.gen(function* () {
+ ambiguousDeleteCalls.length = 0;
+
+ const userContext = yield* ComposioUserContext;
+ yield* userContext.login('test_api_key', 'org_test');
+ yield* cli(['connections', 'remove', 'github']);
+
+ expect(ambiguousDeleteCalls).toEqual([]);
+
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ expect(lines.join('\n')).toContain('Multiple connections matched "github"');
+ })
+ );
+ });
+});