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.

Preload custom auth connections into CLI tool router sessions (#3077)

Rahul Tarake7b5a44fb3fc
diff --git a/.claude/skills/cli-release/SKILL.md b/.claude/skills/cli-release/SKILL.md
new file mode 100644
index 000000000..261dd244d
--- /dev/null
+++ b/.claude/skills/cli-release/SKILL.md
@@ -0,0 +1,194 @@
+---
+description: Release the CLI — diff features since last release, run /full-cli-test on them, and create a changeset PR with patch bump and test results.
+---
+
+# CLI Release
+
+Orchestrates a CLI release by identifying what changed since the last release, testing those changes via `/full-cli-test`, and creating a changeset PR with a patch version bump.
+
+## Overview
+
+Two workstreams run **in parallel**:
+
+1. **Testing** — Run `/full-cli-test` to validate the CLI binary (types/lint CI, local build, bundled build).
+2. **Changeset PR** — Identify changes since the last release, create a changeset file, open a PR.
+
+Once testing completes, update the PR description with test results.
+
+## Step 1: Identify Changes Since Last Release
+
+Find the last release tag or version bump commit for `@composio/cli`:
+
+```bash
+# Find the last release commit (look for "Release: update version" commits that touched the CLI)
+git log --oneline --all -- ts/packages/cli/package.json | head -20
+```
+
+Look for the most recent commit where the CLI version was bumped (typically a "Release: update version" commit). Use that as the base.
+
+Then collect all commits between that base and HEAD that touch the CLI:
+
+```bash
+git log <base_commit>..HEAD --oneline -- ts/packages/cli/
+```
+
+For each commit, read the commit message and understand what it does. Categorize changes as:
+- **Features** — new commands, new flags, new capabilities
+- **Fixes** — bug fixes, error handling improvements
+- **Improvements** — refactors, performance, DX improvements
+
+Also run a full diff to understand the scope:
+
+```bash
+git diff <base_commit>..HEAD -- ts/packages/cli/src/
+```
+
+## Step 2: Run /full-cli-test (Parallel Track 1)
+
+Run the `/full-cli-test` skill. This executes:
+
+1. **Phase 1:** Monitor CI for types/lint passing
+2. **Phase 2:** Local binary build and test (including Slack integration test)
+3. **Phase 3:** Bundled binary build and test via CI (including Slack integration test)
+
+Track the results of each phase — you'll need them for the PR description.
+
+## Step 3: Create Changeset PR (Parallel Track 2)
+
+While testing runs, create the changeset and PR. Do this **in parallel** with Step 2.
+
+### 3a. Create a new branch
+
+```bash
+git checkout -b cli-release/patch-<short-description>
+```
+
+### 3b. Write the changeset file
+
+Create a changeset file at `.changeset/<descriptive-name>.md`. The format is:
+
+```markdown
+---
+"@composio/cli": patch
+---
+
+<summary of all changes since last release>
+```
+
+The summary should be a concise but complete description of all changes. Use the categorized changes from Step 1. Example:
+
+```markdown
+---
+"@composio/cli": patch
+---
+
+feat: add `composio manage triggers` command for listing and inspecting trigger types
+fix: bundle MCP server into subagent helper for standalone binaries
+fix: harden run subAgent structured output and logfile path propagation
+improve: better error messages for missing auth configs
+```
+
+Use `patch` by default. Only use `minor` if explicitly requested by the user.
+
+### 3c. Commit and push
+
+```bash
+git add .changeset/<name>.md
+git commit -m "chore: add changeset for CLI patch release"
+git push -u origin cli-release/patch-<short-description>
+```
+
+### 3d. Open the PR
+
+Create a PR against `next` with a clear description. Use a placeholder for test results that will be filled in once testing completes:
+
+```bash
+gh pr create --base next --title "chore: CLI patch release" --body "$(cat <<'EOF'
+## Changes
+
+<list of changes from Step 1, categorized>
+
+## Changeset
+
+- Bump: `@composio/cli` patch
+- File: `.changeset/<name>.md`
+
+## Testing
+
+⏳ Full CLI test pipeline in progress...
+
+_Test results will be updated once `/full-cli-test` completes._
+
+🤖 Generated with [Claude Code](https://claude.com/claude-code)
+EOF
+)"
+```
+
+## Step 4: Update PR with Test Results
+
+Once `/full-cli-test` completes (all 3 phases), update the PR description with the actual test results:
+
+```bash
+gh pr edit <PR_NUMBER> --body "$(cat <<'EOF'
+## Changes
+
+<same list of changes>
+
+## Changeset
+
+- Bump: `@composio/cli` patch
+- File: `.changeset/<name>.md`
+
+## Testing
+
+✅ Full CLI test pipeline passed
+
+### Phase 1: CI Types/Lint
+- Status: ✅ Passed
+- <link to CI run if available>
+
+### Phase 2: Local Binary Test
+- `composio version`: ✅
+- `composio whoami`: ✅
+- `composio --help`: ✅
+- Slack integration test: ✅
+
+### Phase 3: Bundled Binary Test
+- Binary version: <version>
+- `composio version`: ✅
+- `composio whoami`: ✅
+- `composio --help`: ✅
+- `composio run`: ✅
+- `experimental_subAgent()`: ✅
+- Slack integration test: ✅
+
+### Features Tested
+<for each new feature/fix identified in Step 1, describe how it was tested>
+
+🤖 Generated with [Claude Code](https://claude.com/claude-code)
+EOF
+)"
+```
+
+If any phase fails, update the PR description with the failure details and mark the PR as draft:
+
+```bash
+gh pr ready <PR_NUMBER> --undo # Convert to draft
+```
+
+## Important Notes
+
+- **Default to patch.** Only use `minor` or `major` if the user explicitly requests it.
+- **Don't use `pnpm changeset` CLI** — create the `.changeset/*.md` file manually.
+- **The changeset file format is strict:** YAML frontmatter with package name in quotes and bump type, then a blank line, then the description.
+- **Feature-specific testing:** When identifying changes in Step 1, note any new commands or flags. During testing (Step 2), explicitly test those new features with the built binary beyond the standard test suite.
+- **The PR targets `next`** — this is the main development branch.
+
+## Reference Files
+
+| File | Purpose |
+|---|---|
+| `ts/packages/cli/package.json` | Current CLI version |
+| `.changeset/config.json` | Changeset configuration |
+| `.github/workflows/build-cli-binaries.yml` | CI binary build workflow |
+| `ts/packages/cli/src/commands/` | CLI command implementations |
diff --git a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
index f9608e12e..c67d37a5c 100644
--- a/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+++ b/ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
@@ -186,6 +186,18 @@ const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string) =>
yield* ui.output(dashboardUrl);
});
+const getConsumerCacheScope = (resolvedProject: {
+ readonly orgId: string;
+ readonly projectType: 'CONSUMER' | 'DEVELOPER';
+ readonly consumerUserId?: string;
+}) =>
+ resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
+ ? {
+ orgId: resolvedProject.orgId,
+ consumerUserId: resolvedProject.consumerUserId,
+ }
+ : undefined;
+
const runConnectedAccountsLink = (params: {
toolkit: Option.Option<string>;
authConfig: Option.Option<string>;
@@ -352,6 +364,7 @@ const runConnectedAccountsLink = (params: {
Effect.gen(function* () {
const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
manageConnections: true,
+ cacheScope: getConsumerCacheScope(resolvedProject),
});
return yield* Effect.tryPromise(() =>
client.toolRouter.session.link(sessionId, { toolkit: toolkitSlug })
diff --git a/ts/packages/cli/src/commands/proxy.cmd.ts b/ts/packages/cli/src/commands/proxy.cmd.ts
index 366fce940..75d121f56 100644
--- a/ts/packages/cli/src/commands/proxy.cmd.ts
+++ b/ts/packages/cli/src/commands/proxy.cmd.ts
@@ -314,6 +314,10 @@ export const proxyCmd = Command.make('proxy', {
});
const { sessionId } = yield* resolveToolRouterSession(client, consumerUserId, {
toolkits: [normalizedToolkit],
+ cacheScope: {
+ orgId: resolvedProject.orgId,
+ consumerUserId,
+ },
});
const resultEither = yield* Effect.tryPromise(() =>
diff --git a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
index 3f6b93efd..13a4efa66 100644
--- a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+++ b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
@@ -978,6 +978,13 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
userId: resolvedUserId.value,
arguments: args,
client,
+ cacheScope:
+ resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
+ ? {
+ orgId: resolvedProject.orgId,
+ consumerUserId: resolvedProject.consumerUserId,
+ }
+ : undefined,
},
} satisfies ResolvedExecuteContext;
});
diff --git a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
index 3f23d26b4..7c551d8d7 100644
--- a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+++ b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
@@ -354,6 +354,13 @@ const runToolsSearch = (params: {
}
const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
toolkits: toolkitList,
+ cacheScope:
+ resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
+ ? {
+ orgId: resolvedProject.orgId,
+ consumerUserId: resolvedProject.consumerUserId,
+ }
+ : undefined,
});
const searchResponse = yield* Effect.tryPromise(() =>
client.toolRouter.session.search(sessionId, {
diff --git a/ts/packages/cli/src/effects/create-tool-router-session.ts b/ts/packages/cli/src/effects/create-tool-router-session.ts
index a5ad2b240..140d5c61a 100644
--- a/ts/packages/cli/src/effects/create-tool-router-session.ts
+++ b/ts/packages/cli/src/effects/create-tool-router-session.ts
@@ -1,11 +1,21 @@
-import { Effect } from 'effect';
+import { Effect, Option } from 'effect';
import type { Composio } from '@composio/client';
+import {
+ getFreshConsumerToolRouterAuthConfigsFromCache,
+ writeConsumerConnectedToolkitsCache,
+} from 'src/services/consumer-short-term-cache';
+import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';
export interface CreateToolRouterSessionOptions {
/** Enable auto connection management. Default: false. */
readonly manageConnections?: boolean;
/** Restrict session to these toolkit slugs. */
readonly toolkits?: ReadonlyArray<string>;
+ /** Consumer-only cache scope for rolling auth-config reuse. */
+ readonly cacheScope?: {
+ readonly orgId: string;
+ readonly consumerUserId: string;
+ };
}
/**
@@ -21,16 +31,47 @@ export const createToolRouterSession = (
userId: string,
options?: CreateToolRouterSessionOptions
) =>
- Effect.tryPromise(() =>
- client.toolRouter.session.create({
- user_id: userId,
- manage_connections: { enable: options?.manageConnections ?? false },
- toolkits:
- options?.toolkits && options.toolkits.length > 0
- ? { enable: [...options.toolkits] }
- : undefined,
- })
- ).pipe(Effect.map(session => session.session_id));
+ Effect.gen(function* () {
+ const cachedAuthConfigs = options?.cacheScope
+ ? yield* getFreshConsumerToolRouterAuthConfigsFromCache({
+ orgId: options.cacheScope.orgId,
+ consumerUserId: options.cacheScope.consumerUserId,
+ toolkits: options.toolkits,
+ })
+ : Option.none();
+
+ const connectionContext = Option.isSome(cachedAuthConfigs)
+ ? {
+ connectedToolkits: options?.toolkits ?? [],
+ authConfigs: cachedAuthConfigs.value.authConfigs,
+ }
+ : yield* resolveToolRouterSessionConnections(client, userId, {
+ toolkits: options?.toolkits,
+ });
+
+ if (options?.cacheScope && Option.isNone(cachedAuthConfigs)) {
+ yield* writeConsumerConnectedToolkitsCache({
+ orgId: options.cacheScope.orgId,
+ consumerUserId: options.cacheScope.consumerUserId,
+ toolkits: connectionContext.connectedToolkits,
+ toolRouterAuthConfigs: {
+ authConfigs: connectionContext.authConfigs,
+ },
+ }).pipe(Effect.catchAll(() => Effect.void));
+ }
+
+ return yield* Effect.tryPromise(() =>
+ client.toolRouter.session.create({
+ user_id: userId,
+ auth_configs: connectionContext.authConfigs,
+ manage_connections: { enable: options?.manageConnections ?? false },
+ toolkits:
+ options?.toolkits && options.toolkits.length > 0
+ ? { enable: [...options.toolkits] }
+ : undefined,
+ })
+ ).pipe(Effect.map(session => session.session_id));
+ });
/**
* Resolve the Composio client and create a Tool Router session in one step.
diff --git a/ts/packages/cli/src/services/consumer-short-term-cache.ts b/ts/packages/cli/src/services/consumer-short-term-cache.ts
index 7a9051f24..45737d6ed 100644
--- a/ts/packages/cli/src/services/consumer-short-term-cache.ts
+++ b/ts/packages/cli/src/services/consumer-short-term-cache.ts
@@ -6,19 +6,26 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
import { NodeProcess } from 'src/services/node-process';
import {
ComposioToolkitsRepository,
+ ComposioClientSingleton,
getConsumerConnectedToolkits,
resolveConsumerProject,
} from 'src/services/composio-clients';
import { resolveCommandProject } from 'src/services/command-project';
+import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';
import { ComposioUserContext } from 'src/services/user-context';
const CACHE_FILE = 'consumer-short-term-cache.json';
const CACHE_TTL_MS = 15 * 60 * 1000;
const SEARCH_SESSION_EXTENSION_MS = 5 * 60 * 1000;
+export type ConsumerToolRouterAuthConfigMappings = {
+ readonly authConfigs?: Record<string, string>;
+};
+
type CacheEntry = {
readonly toolkits: ReadonlyArray<string>;
readonly expiresAt: string;
+ readonly toolRouterAuthConfigs?: ConsumerToolRouterAuthConfigMappings;
readonly probablyMyCliSessionsByCwdHash?: Record<
string,
{
@@ -121,6 +128,42 @@ const normalizeCachedToolkits = (
noAuthToolkits: ReadonlyArray<string>
) => [...new Set([...toolkits, ...noAuthToolkits].map(toolkit => toolkit.toLowerCase()))];
+const normalizeAuthConfigMappings = (
+ mappings?: ConsumerToolRouterAuthConfigMappings
+): ConsumerToolRouterAuthConfigMappings | undefined => {
+ if (!mappings) return undefined;
+
+ const authConfigs = Object.fromEntries(
+ Object.entries(mappings.authConfigs ?? {})
+ .map(([toolkit, authConfigId]) => [toolkit.toLowerCase(), authConfigId])
+ .filter(([, authConfigId]) => typeof authConfigId === 'string' && authConfigId.length > 0)
+ );
+ if (Object.keys(authConfigs).length === 0) {
+ return undefined;
+ }
+
+ return {
+ authConfigs,
+ };
+};
+
+const mergeAuthConfigMappings = (params: {
+ readonly current?: ConsumerToolRouterAuthConfigMappings;
+ readonly next?: ConsumerToolRouterAuthConfigMappings;
+}) => {
+ const current = normalizeAuthConfigMappings(params.current);
+ const next = normalizeAuthConfigMappings(params.next);
+ if (!current) return next;
+ if (!next) return current;
+
+ return normalizeAuthConfigMappings({
+ authConfigs: {
+ ...(current.authConfigs ?? {}),
+ ...(next.authConfigs ?? {}),
+ },
+ });
+};
+
export const getFreshConsumerConnectedToolkitsFromCache = (params: {
orgId: string;
consumerUserId: string;
@@ -142,6 +185,53 @@ export const getFreshConsumerConnectedToolkitsFromCache = (params: {
return Option.some(entry.toolkits);
});
+export const getFreshConsumerToolRouterAuthConfigsFromCache = (params: {
+ orgId: string;
+ consumerUserId: string;
+ toolkits?: ReadonlyArray<string>;
+}) =>
+ Effect.gen(function* () {
+ const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;
+ if (disabled) {
+ return Option.none<ConsumerToolRouterAuthConfigMappings>();
+ }
+ const state = yield* readCache();
+ const entry = state[cacheKey(params.orgId, params.consumerUserId)];
+ if (!entry) {
+ return Option.none<ConsumerToolRouterAuthConfigMappings>();
+ }
+ const expiresAtMs = Date.parse(entry.expiresAt);
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {
+ return Option.none<ConsumerToolRouterAuthConfigMappings>();
+ }
+
+ const mappings = normalizeAuthConfigMappings(entry.toolRouterAuthConfigs);
+ if (!mappings) {
+ return Option.none<ConsumerToolRouterAuthConfigMappings>();
+ }
+
+ if (!params.toolkits || params.toolkits.length === 0) {
+ return Option.some(mappings);
+ }
+
+ const requestedToolkits = params.toolkits.map(toolkit => toolkit.toLowerCase());
+ const requestedAuthConfigs = requestedToolkits.map(
+ toolkit => [toolkit, mappings.authConfigs?.[toolkit]] as const
+ );
+
+ if (requestedAuthConfigs.some(([, authConfigId]) => typeof authConfigId !== 'string')) {
+ return Option.none<ConsumerToolRouterAuthConfigMappings>();
+ }
+
+ const filtered = normalizeAuthConfigMappings({
+ authConfigs: Object.fromEntries(
+ requestedAuthConfigs.map(([toolkit, authConfigId]) => [toolkit, authConfigId as string])
+ ),
+ });
+
+ return filtered ? Option.some(filtered) : Option.none<ConsumerToolRouterAuthConfigMappings>();
+ });
+
export const invalidateConsumerConnectedToolkitsCache = () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -210,12 +300,34 @@ export const refreshConsumerConnectedToolkitsCache = (params?: {
return;
}
- const response = yield* getConsumerConnectedToolkits({
- baseURL: userContext.data.baseURL,
- apiKey,
- orgId: scope.orgId,
- consumerUserId: scope.consumerUserId,
- });
+ const clientSingleton = yield* ComposioClientSingleton;
+ const directToolkits = yield* Effect.gen(function* () {
+ const consumerProject = yield* resolveConsumerProject({
+ baseURL: userContext.data.baseURL,
+ apiKey,
+ orgId: scope.orgId,
+ });
+ const client = yield* clientSingleton.getFor({
+ orgId: scope.orgId,
+ projectId: consumerProject.project_id,
+ });
+ const connectionContext = yield* resolveToolRouterSessionConnections(
+ client,
+ scope.consumerUserId
+ );
+ return connectionContext;
+ }).pipe(Effect.option);
+
+ const connectedToolkits =
+ Option.isSome(directToolkits) && directToolkits.value.connectedToolkits.length > 0
+ ? directToolkits.value.connectedToolkits
+ : (yield* getConsumerConnectedToolkits({
+ baseURL: userContext.data.baseURL,
+ apiKey,
+ orgId: scope.orgId,
+ consumerUserId: scope.consumerUserId,
+ })).toolkits;
+
const noAuthToolkits = yield* getAlwaysConnectedNoAuthToolkits();
const state = yield* readCache();
const key = cacheKey(scope.orgId, scope.consumerUserId);
@@ -228,8 +340,16 @@ export const refreshConsumerConnectedToolkitsCache = (params?: {
yield* writeCache({
...state,
[key]: {
- toolkits: normalizeCachedToolkits(response.toolkits, noAuthToolkits),
+ toolkits: normalizeCachedToolkits(connectedToolkits, noAuthToolkits),
expiresAt: new Date(Date.now() + CACHE_TTL_MS).toISOString(),
+ toolRouterAuthConfigs: mergeAuthConfigMappings({
+ current: currentEntry?.toolRouterAuthConfigs,
+ next: Option.isSome(directToolkits)
+ ? {
+ authConfigs: directToolkits.value.authConfigs,
+ }
+ : undefined,
+ }),
...searchSessionFields,
},
});
@@ -239,6 +359,7 @@ export const writeConsumerConnectedToolkitsCache = (params: {
readonly orgId: string;
readonly consumerUserId: string;
readonly toolkits: ReadonlyArray<string>;
+ readonly toolRouterAuthConfigs?: ConsumerToolRouterAuthConfigMappings;
}) =>
Effect.gen(function* () {
const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;
@@ -258,6 +379,10 @@ export const writeConsumerConnectedToolkitsCache = (params: {
[key]: {
toolkits: normalizeCachedToolkits(params.toolkits, noAuthToolkits),
expiresAt: new Date(Date.now() + CACHE_TTL_MS).toISOString(),
+ toolRouterAuthConfigs: mergeAuthConfigMappings({
+ current: currentEntry?.toolRouterAuthConfigs,
+ next: params.toolRouterAuthConfigs,
+ }),
...searchSessionFields,
},
});
diff --git a/ts/packages/cli/src/services/tool-router-session-connections.ts b/ts/packages/cli/src/services/tool-router-session-connections.ts
new file mode 100644
index 000000000..1b53539ee
--- /dev/null
+++ b/ts/packages/cli/src/services/tool-router-session-connections.ts
@@ -0,0 +1,98 @@
+import { Effect } from 'effect';
+import type { Composio } from '@composio/client';
+
+type RawConnectedAccount = {
+ readonly id: string;
+ readonly toolkit?: {
+ readonly slug?: string | null;
+ } | null;
+ readonly auth_config?: {
+ readonly id?: string | null;
+ readonly is_composio_managed?: boolean | null;
+ } | null;
+ readonly updated_at?: string | null;
+ readonly created_at?: string | null;
+};
+
+export type ToolRouterSessionConnectionContext = {
+ readonly connectedToolkits: ReadonlyArray<string>;
+ readonly authConfigs?: Record<string, string>;
+};
+
+const parseTimestamp = (value?: string | null): number => {
+ if (!value) return 0;
+ const parsed = Date.parse(value);
+ return Number.isFinite(parsed) ? parsed : 0;
+};
+
+const isNewerAccount = (candidate: RawConnectedAccount, current: RawConnectedAccount): boolean => {
+ const candidateTimestamp = Math.max(
+ parseTimestamp(candidate.updated_at),
+ parseTimestamp(candidate.created_at)
+ );
+ const currentTimestamp = Math.max(
+ parseTimestamp(current.updated_at),
+ parseTimestamp(current.created_at)
+ );
+ return candidateTimestamp > currentTimestamp;
+};
+
+export const resolveToolRouterSessionConnections = (
+ client: Composio,
+ userId: string,
+ options?: {
+ readonly toolkits?: ReadonlyArray<string>;
+ }
+) =>
+ Effect.tryPromise(() =>
+ client.connectedAccounts.list({
+ user_ids: [userId],
+ statuses: ['ACTIVE'],
+ toolkit_slugs:
+ options?.toolkits && options.toolkits.length > 0 ? [...options.toolkits] : undefined,
+ limit: 1000,
+ })
+ ).pipe(
+ Effect.map(response => {
+ const items = (response.items ?? []) as ReadonlyArray<RawConnectedAccount>;
+ const connectedToolkits = new Set<string>();
+ const explicitAccountsByToolkit = new Map<string, RawConnectedAccount>();
+
+ for (const item of items) {
+ const toolkit = item.toolkit?.slug?.toLowerCase().trim();
+ if (!toolkit) continue;
+
+ connectedToolkits.add(toolkit);
+
+ // Tool Router already handles Composio-managed auth well.
+ // Explicitly pin non-managed auth configs/accounts so consumer sessions
+ // can execute against custom-auth toolkits like PostHog.
+ if (item.auth_config?.is_composio_managed !== false) {
+ continue;
+ }
+
+ const current = explicitAccountsByToolkit.get(toolkit);
+ if (!current || isNewerAccount(item, current)) {
+ explicitAccountsByToolkit.set(toolkit, item);
+ }
+ }
+
+ const authConfigs: Record<string, string> = {};
+ for (const [toolkit, item] of explicitAccountsByToolkit) {
+ const authConfigId = item.auth_config?.id?.trim();
+ if (!authConfigId) continue;
+ authConfigs[toolkit] = authConfigId;
+ }
+
+ return {
+ connectedToolkits: [...connectedToolkits],
+ authConfigs: Object.keys(authConfigs).length > 0 ? authConfigs : undefined,
+ } satisfies ToolRouterSessionConnectionContext;
+ }),
+ Effect.catchAll(() =>
+ Effect.succeed({
+ connectedToolkits: [],
+ authConfigs: undefined,
+ } satisfies ToolRouterSessionConnectionContext)
+ )
+ );
diff --git a/ts/packages/cli/src/services/tools-executor.ts b/ts/packages/cli/src/services/tools-executor.ts
index 0f736e0e1..1b1e133fc 100644
--- a/ts/packages/cli/src/services/tools-executor.ts
+++ b/ts/packages/cli/src/services/tools-executor.ts
@@ -1,3 +1,4 @@
+import { FileSystem } from '@effect/platform';
import { Context, Effect, Layer } from 'effect';
import type { Composio } from '@composio/client';
import type {
@@ -5,7 +6,6 @@ import type {
SessionExecuteMetaResponse,
SessionExecuteMetaParams,
} from '@composio/client/resources/tool-router';
-import type { FileSystem } from '@effect/platform';
import { ComposioClientSingleton } from 'src/services/composio-clients';
import { createToolRouterSession } from 'src/effects/create-tool-router-session';
import {
@@ -15,6 +15,7 @@ import {
import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
import { uploadToolInputFiles } from 'src/services/tool-file-uploads';
import type { NodeOs } from 'src/services/node-os';
+import type { NodeProcess } from 'src/services/node-process';
import type { ComposioUserContext } from 'src/services/user-context';
import type { ComposioToolkitsRepository } from 'src/services/composio-clients';
@@ -25,6 +26,10 @@ export interface ToolExecuteParams {
readonly userId: string;
readonly arguments: Record<string, unknown>;
readonly client?: Composio;
+ readonly cacheScope?: {
+ readonly orgId: string;
+ readonly consumerUserId: string;
+ };
}
/**
@@ -44,7 +49,7 @@ export interface ToolsExecutor {
) => Effect.Effect<
ToolExecuteResponse,
unknown,
- FileSystem.FileSystem | NodeOs | ComposioUserContext | ComposioToolkitsRepository
+ FileSystem.FileSystem | NodeOs | NodeProcess | ComposioUserContext | ComposioToolkitsRepository
>;
}
@@ -132,6 +137,7 @@ export const ToolsExecutorLive = Layer.effect(
// One session per invocation — CLI runs one tool per process.
const sessionId = yield* createToolRouterSession(resolvedClient, params.userId, {
manageConnections: true,
+ cacheScope: params.cacheScope,
});
const normalizedArguments = isMetaToolSlug(slug)
? params.arguments
diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.ts
index 3a75dfe78..8bcd81f9e 100644
--- a/ts/packages/cli/test/__utils__/services/test-layer.ts
+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts
@@ -939,6 +939,38 @@ export const TestLayer = (input?: TestLiveInput) =>
},
},
connectedAccounts: {
+ list: async (params?: {
+ toolkit_slugs?: string[];
+ user_ids?: string[];
+ statuses?: string[];
+ limit?: number;
+ }) => {
+ let results = [...connectedAccountsData.items];
+
+ if (params?.toolkit_slugs && params.toolkit_slugs.length > 0) {
+ const slugs = new Set(params.toolkit_slugs.map(slug => slug.toLowerCase()));
+ results = results.filter(item => slugs.has(item.toolkit.slug.toLowerCase()));
+ }
+
+ if (params?.user_ids && params.user_ids.length > 0) {
+ const userIds = new Set(params.user_ids);
+ results = results.filter(item => userIds.has(item.user_id));
+ }
+
+ if (params?.statuses && params.statuses.length > 0) {
+ const statuses = new Set(params.statuses);
+ results = results.filter(item => statuses.has(item.status));
+ }
+
+ const limit = params?.limit ?? 30;
+ return {
+ items: results.slice(0, limit),
+ total_items: results.length,
+ total_pages: Math.ceil(results.length / limit),
+ current_page: 1,
+ next_cursor: null,
+ };
+ },
retrieve: async (nanoid: string) => {
const found = connectedAccountsData.items.find(item => item.id === nanoid);
if (!found) {
diff --git a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
index 100653fcf..47d2c4619 100644
--- a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
@@ -60,6 +60,11 @@ describe('CLI: composio execute', () => {
if (savedCI !== undefined) process.env.CI = savedCI;
});
+ let recordedSessionCreateParams: Array<Record<string, unknown>> = [];
+ beforeEach(() => {
+ recordedSessionCreateParams = [];
+ });
+
layer(
TestLive({
baseConfigProvider: testConfigProvider,
@@ -92,6 +97,131 @@ describe('CLI: composio execute', () => {
TestLive({
baseConfigProvider: testConfigProvider,
fixture: 'global-test-user-id',
+ stdin: { isTTY: true, data: '' },
+ connectedAccountsData: {
+ items: [
+ {
+ id: 'con_posthog_active',
+ status: 'ACTIVE',
+ status_reason: null,
+ is_disabled: false,
+ user_id: 'consumer-user-org_test',
+ toolkit: { slug: 'posthog' },
+ auth_config: {
+ id: 'ac_posthog_custom',
+ auth_scheme: 'BEARER_TOKEN',
+ is_composio_managed: false,
+ is_disabled: false,
+ },
+ created_at: '2026-01-01T00:00:00.000Z',
+ updated_at: '2026-01-02T00:00:00.000Z',
+ test_request_endpoint: '',
+ },
+ ],
+ },
+ toolRouter: {
+ create: async params => {
+ recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
+ return {
+ session_id: 'trs_posthog_test_session',
+ config: { user_id: params.user_id },
+ mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
+ tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
+ };
+ },
+ execute: async (_sessionId, params) => ({
+ data: { tool_slug: params.tool_slug, arguments: params.arguments },
+ error: null,
+ log_id: 'log_posthog_test',
+ }),
+ },
+ })
+ )(
+ '[Given] a non-managed connected account [Then] execute preloads auth configs into the Tool Router session',
+ it => {
+ it.scoped('passes explicit auth_configs for custom auth toolkits', () =>
+ Effect.gen(function* () {
+ yield* cli([
+ 'execute',
+ 'POSTHOG_RUN_ENDPOINT',
+ '--skip-checks',
+ '-d',
+ '{"project_id":"196278","name":"test"}',
+ ]);
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const output = parseLastJson(lines);
+
+ expect(output.successful).toBe(true);
+ expect(recordedSessionCreateParams).toHaveLength(1);
+ expect(recordedSessionCreateParams[0]?.user_id).toEqual(expect.any(String));
+ expect(recordedSessionCreateParams[0]?.auth_configs).toEqual({
+ posthog: 'ac_posthog_custom',
+ });
+ expect(recordedSessionCreateParams[0]?.connected_accounts).toBeUndefined();
+ })
+ );
+ }
+ );
+
+ layer(
+ TestLive({
+ baseConfigProvider: testConfigProvider,
+ fixture: 'global-test-user-id',
+ stdin: { isTTY: true, data: '' },
+ toolRouter: {
+ create: async params => {
+ recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
+ return {
+ session_id: 'trs_posthog_cached_session',
+ config: { user_id: params.user_id },
+ mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
+ tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
+ };
+ },
+ execute: async (_sessionId, params) => ({
+ data: { tool_slug: params.tool_slug, arguments: params.arguments },
+ error: null,
+ log_id: 'log_posthog_cached',
+ }),
+ },
+ })
+ )('[Given] cached auth configs [Then] execute seeds the session from cache', it => {
+ it.scoped('uses cached auth_configs for consumer execute sessions', () =>
+ Effect.gen(function* () {
+ vi.spyOn(
+ consumerShortTermCache,
+ 'getFreshConsumerToolRouterAuthConfigsFromCache'
+ ).mockReturnValue(
+ Effect.succeed(
+ Option.some({
+ authConfigs: {
+ posthog: 'ac_posthog_cached',
+ },
+ })
+ )
+ );
+
+ yield* cli([
+ 'execute',
+ 'POSTHOG_RUN_ENDPOINT',
+ '--skip-checks',
+ '-d',
+ '{"project_id":"196278","name":"test"}',
+ ]);
+
+ expect(recordedSessionCreateParams).toHaveLength(1);
+ expect(recordedSessionCreateParams[0]?.auth_configs).toEqual({
+ posthog: 'ac_posthog_cached',
+ });
+ })
+ );
+ });
+
+ layer(
+ TestLive({
+ baseConfigProvider: testConfigProvider,
+ fixture: 'global-test-user-id',
+ stdin: { isTTY: true, data: '' },
toolkitsData: {
tools: [
{
diff --git a/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts b/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
index ca6ab9583..30cec92ef 100644
--- a/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
+++ b/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
@@ -5,6 +5,7 @@ import { extendConfigProvider } from 'src/services/config';
import * as composioClients from 'src/services/composio-clients';
import {
getFreshConsumerConnectedToolkitsFromCache,
+ getFreshConsumerToolRouterAuthConfigsFromCache,
refreshConsumerConnectedToolkitsCache,
writeConsumerConnectedToolkitsCache,
} from 'src/services/consumer-short-term-cache';
@@ -175,4 +176,68 @@ describe('consumer short-term cache', () => {
})
);
});
+
+ layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
+ '[Given] a full auth-config cache hit [Then] cache reads are toolkit-complete',
+ it => {
+ it.scoped('returns cached auth configs when every requested toolkit is covered', () =>
+ Effect.gen(function* () {
+ yield* writeConsumerConnectedToolkitsCache({
+ orgId: 'org_test',
+ consumerUserId: 'consumer-user-test',
+ toolkits: ['posthog', 'hubspot'],
+ toolRouterAuthConfigs: {
+ authConfigs: {
+ posthog: 'ac_posthog',
+ hubspot: 'ac_hubspot',
+ },
+ },
+ });
+
+ const cached = yield* getFreshConsumerToolRouterAuthConfigsFromCache({
+ orgId: 'org_test',
+ consumerUserId: 'consumer-user-test',
+ toolkits: ['posthog', 'hubspot'],
+ });
+
+ expect(cached).toEqual(
+ Option.some({
+ authConfigs: {
+ posthog: 'ac_posthog',
+ hubspot: 'ac_hubspot',
+ },
+ })
+ );
+ })
+ );
+ }
+ );
+
+ layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
+ '[Given] a partial auth-config cache hit [Then] cache read fails closed',
+ it => {
+ it.scoped('returns none unless every requested toolkit has a cached auth config', () =>
+ Effect.gen(function* () {
+ yield* writeConsumerConnectedToolkitsCache({
+ orgId: 'org_test',
+ consumerUserId: 'consumer-user-test',
+ toolkits: ['posthog', 'hubspot'],
+ toolRouterAuthConfigs: {
+ authConfigs: {
+ posthog: 'ac_posthog',
+ },
+ },
+ });
+
+ const cached = yield* getFreshConsumerToolRouterAuthConfigsFromCache({
+ orgId: 'org_test',
+ consumerUserId: 'consumer-user-test',
+ toolkits: ['posthog', 'hubspot'],
+ });
+
+ expect(cached).toEqual(Option.none());
+ })
+ );
+ }
+ );
});