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

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

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

Synced Nov 22, 00:45 UTC

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

## Summary - Preloads active connected accounts into CLI Tool Router sessions so custom-auth toolkits can execute without missing auth context. - Resolves connected toolkits from the consumer cache path when available, falling back to the standard connected-toolkit lookup. - Adds a new session-connection resolver that selects the newest non-Composio-managed account per toolkit and passes explicit `auth_configs` and `connected_accounts` into session creation. - Expands test coverage for custom auth session creation and connected-account lookup filtering. ## Testing - Added/updated CLI tests covering `POSTHOG_RUN_ENDPOINT` session creation with explicit `auth_configs` and `connected_accounts`. - Added test-layer support for filtering connected accounts by `toolkit_slugs`, `user_ids`, `statuses`, and `limit`. - Not run locally.

Rahul Tarak committed Mar 31, 2026 at 15:44 UTC e7b5a44fb3fce1c3affa86a831f5c362564e0a91
12 files changed +742 -20
.claude/skills/cli-release/SKILL.md new
+194
@@ -0,0 +1,194 @@
1 +---
2 +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.
3 +---
4 +
5 +# CLI Release
6 +
7 +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.
8 +
9 +## Overview
10 +
11 +Two workstreams run **in parallel**:
12 +
13 +1. **Testing** — Run `/full-cli-test` to validate the CLI binary (types/lint CI, local build, bundled build).
14 +2. **Changeset PR** — Identify changes since the last release, create a changeset file, open a PR.
15 +
16 +Once testing completes, update the PR description with test results.
17 +
18 +## Step 1: Identify Changes Since Last Release
19 +
20 +Find the last release tag or version bump commit for `@composio/cli`:
21 +
22 +```bash
23 +# Find the last release commit (look for "Release: update version" commits that touched the CLI)
24 +git log --oneline --all -- ts/packages/cli/package.json | head -20
25 +```
26 +
27 +Look for the most recent commit where the CLI version was bumped (typically a "Release: update version" commit). Use that as the base.
28 +
29 +Then collect all commits between that base and HEAD that touch the CLI:
30 +
31 +```bash
32 +git log <base_commit>..HEAD --oneline -- ts/packages/cli/
33 +```
34 +
35 +For each commit, read the commit message and understand what it does. Categorize changes as:
36 +- **Features** — new commands, new flags, new capabilities
37 +- **Fixes** — bug fixes, error handling improvements
38 +- **Improvements** — refactors, performance, DX improvements
39 +
40 +Also run a full diff to understand the scope:
41 +
42 +```bash
43 +git diff <base_commit>..HEAD -- ts/packages/cli/src/
44 +```
45 +
46 +## Step 2: Run /full-cli-test (Parallel Track 1)
47 +
48 +Run the `/full-cli-test` skill. This executes:
49 +
50 +1. **Phase 1:** Monitor CI for types/lint passing
51 +2. **Phase 2:** Local binary build and test (including Slack integration test)
52 +3. **Phase 3:** Bundled binary build and test via CI (including Slack integration test)
53 +
54 +Track the results of each phase — you'll need them for the PR description.
55 +
56 +## Step 3: Create Changeset PR (Parallel Track 2)
57 +
58 +While testing runs, create the changeset and PR. Do this **in parallel** with Step 2.
59 +
60 +### 3a. Create a new branch
61 +
62 +```bash
63 +git checkout -b cli-release/patch-<short-description>
64 +```
65 +
66 +### 3b. Write the changeset file
67 +
68 +Create a changeset file at `.changeset/<descriptive-name>.md`. The format is:
69 +
70 +```markdown
71 +---
72 +"@composio/cli": patch
73 +---
74 +
75 +<summary of all changes since last release>
76 +```
77 +
78 +The summary should be a concise but complete description of all changes. Use the categorized changes from Step 1. Example:
79 +
80 +```markdown
81 +---
82 +"@composio/cli": patch
83 +---
84 +
85 +feat: add `composio manage triggers` command for listing and inspecting trigger types
86 +fix: bundle MCP server into subagent helper for standalone binaries
87 +fix: harden run subAgent structured output and logfile path propagation
88 +improve: better error messages for missing auth configs
89 +```
90 +
91 +Use `patch` by default. Only use `minor` if explicitly requested by the user.
92 +
93 +### 3c. Commit and push
94 +
95 +```bash
96 +git add .changeset/<name>.md
97 +git commit -m "chore: add changeset for CLI patch release"
98 +git push -u origin cli-release/patch-<short-description>
99 +```
100 +
101 +### 3d. Open the PR
102 +
103 +Create a PR against `next` with a clear description. Use a placeholder for test results that will be filled in once testing completes:
104 +
105 +```bash
106 +gh pr create --base next --title "chore: CLI patch release" --body "$(cat <<'EOF'
107 +## Changes
108 +
109 +<list of changes from Step 1, categorized>
110 +
111 +## Changeset
112 +
113 +- Bump: `@composio/cli` patch
114 +- File: `.changeset/<name>.md`
115 +
116 +## Testing
117 +
118 +⏳ Full CLI test pipeline in progress...
119 +
120 +_Test results will be updated once `/full-cli-test` completes._
121 +
122 +🤖 Generated with [Claude Code](https://claude.com/claude-code)
123 +EOF
124 +)"
125 +```
126 +
127 +## Step 4: Update PR with Test Results
128 +
129 +Once `/full-cli-test` completes (all 3 phases), update the PR description with the actual test results:
130 +
131 +```bash
132 +gh pr edit <PR_NUMBER> --body "$(cat <<'EOF'
133 +## Changes
134 +
135 +<same list of changes>
136 +
137 +## Changeset
138 +
139 +- Bump: `@composio/cli` patch
140 +- File: `.changeset/<name>.md`
141 +
142 +## Testing
143 +
144 +✅ Full CLI test pipeline passed
145 +
146 +### Phase 1: CI Types/Lint
147 +- Status: ✅ Passed
148 +- <link to CI run if available>
149 +
150 +### Phase 2: Local Binary Test
151 +- `composio version`: ✅
152 +- `composio whoami`: ✅
153 +- `composio --help`: ✅
154 +- Slack integration test: ✅
155 +
156 +### Phase 3: Bundled Binary Test
157 +- Binary version: <version>
158 +- `composio version`: ✅
159 +- `composio whoami`: ✅
160 +- `composio --help`: ✅
161 +- `composio run`: ✅
162 +- `experimental_subAgent()`: ✅
163 +- Slack integration test: ✅
164 +
165 +### Features Tested
166 +<for each new feature/fix identified in Step 1, describe how it was tested>
167 +
168 +🤖 Generated with [Claude Code](https://claude.com/claude-code)
169 +EOF
170 +)"
171 +```
172 +
173 +If any phase fails, update the PR description with the failure details and mark the PR as draft:
174 +
175 +```bash
176 +gh pr ready <PR_NUMBER> --undo # Convert to draft
177 +```
178 +
179 +## Important Notes
180 +
181 +- **Default to patch.** Only use `minor` or `major` if the user explicitly requests it.
182 +- **Don't use `pnpm changeset` CLI** — create the `.changeset/*.md` file manually.
183 +- **The changeset file format is strict:** YAML frontmatter with package name in quotes and bump type, then a blank line, then the description.
184 +- **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.
185 +- **The PR targets `next`** — this is the main development branch.
186 +
187 +## Reference Files
188 +
189 +| File | Purpose |
190 +|---|---|
191 +| `ts/packages/cli/package.json` | Current CLI version |
192 +| `.changeset/config.json` | Changeset configuration |
193 +| `.github/workflows/build-cli-binaries.yml` | CI binary build workflow |
194 +| `ts/packages/cli/src/commands/` | CLI command implementations |
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+13
@@ -186,6 +186,18 @@ const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string) =>
186 yield* ui.output(dashboardUrl);
187 });
188
189 +const getConsumerCacheScope = (resolvedProject: {
190 + readonly orgId: string;
191 + readonly projectType: 'CONSUMER' | 'DEVELOPER';
192 + readonly consumerUserId?: string;
193 +}) =>
194 + resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
195 + ? {
196 + orgId: resolvedProject.orgId,
197 + consumerUserId: resolvedProject.consumerUserId,
198 + }
199 + : undefined;
200 +
201 const runConnectedAccountsLink = (params: {
202 toolkit: Option.Option<string>;
203 authConfig: Option.Option<string>;
@@ -352,6 +364,7 @@ const runConnectedAccountsLink = (params: {
364 Effect.gen(function* () {
365 const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
366 manageConnections: true,
367 + cacheScope: getConsumerCacheScope(resolvedProject),
368 });
369 return yield* Effect.tryPromise(() =>
370 client.toolRouter.session.link(sessionId, { toolkit: toolkitSlug })
ts/packages/cli/src/commands/proxy.cmd.ts
+4
@@ -314,6 +314,10 @@ export const proxyCmd = Command.make('proxy', {
314 });
315 const { sessionId } = yield* resolveToolRouterSession(client, consumerUserId, {
316 toolkits: [normalizedToolkit],
317 + cacheScope: {
318 + orgId: resolvedProject.orgId,
319 + consumerUserId,
320 + },
321 });
322
323 const resultEither = yield* Effect.tryPromise(() =>
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+7
@@ -978,6 +978,13 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
978 userId: resolvedUserId.value,
979 arguments: args,
980 client,
981 + cacheScope:
982 + resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
983 + ? {
984 + orgId: resolvedProject.orgId,
985 + consumerUserId: resolvedProject.consumerUserId,
986 + }
987 + : undefined,
988 },
989 } satisfies ResolvedExecuteContext;
990 });
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+7
@@ -354,6 +354,13 @@ const runToolsSearch = (params: {
354 }
355 const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value, {
356 toolkits: toolkitList,
357 + cacheScope:
358 + resolvedProject.projectType === 'CONSUMER' && resolvedProject.consumerUserId
359 + ? {
360 + orgId: resolvedProject.orgId,
361 + consumerUserId: resolvedProject.consumerUserId,
362 + }
363 + : undefined,
364 });
365 const searchResponse = yield* Effect.tryPromise(() =>
366 client.toolRouter.session.search(sessionId, {
ts/packages/cli/src/effects/create-tool-router-session.ts
+52 -11
@@ -1,11 +1,21 @@
1 -import { Effect } from 'effect';
1 +import { Effect, Option } from 'effect';
2 import type { Composio } from '@composio/client';
3 +import {
4 + getFreshConsumerToolRouterAuthConfigsFromCache,
5 + writeConsumerConnectedToolkitsCache,
6 +} from 'src/services/consumer-short-term-cache';
7 +import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';
8
9 export interface CreateToolRouterSessionOptions {
10 /** Enable auto connection management. Default: false. */
11 readonly manageConnections?: boolean;
12 /** Restrict session to these toolkit slugs. */
13 readonly toolkits?: ReadonlyArray<string>;
14 + /** Consumer-only cache scope for rolling auth-config reuse. */
15 + readonly cacheScope?: {
16 + readonly orgId: string;
17 + readonly consumerUserId: string;
18 + };
19 }
20
21 /**
@@ -21,16 +31,47 @@ export const createToolRouterSession = (
31 userId: string,
32 options?: CreateToolRouterSessionOptions
33 ) =>
24 - Effect.tryPromise(() =>
25 - client.toolRouter.session.create({
26 - user_id: userId,
27 - manage_connections: { enable: options?.manageConnections ?? false },
28 - toolkits:
29 - options?.toolkits && options.toolkits.length > 0
30 - ? { enable: [...options.toolkits] }
31 - : undefined,
32 - })
33 - ).pipe(Effect.map(session => session.session_id));
34 + Effect.gen(function* () {
35 + const cachedAuthConfigs = options?.cacheScope
36 + ? yield* getFreshConsumerToolRouterAuthConfigsFromCache({
37 + orgId: options.cacheScope.orgId,
38 + consumerUserId: options.cacheScope.consumerUserId,
39 + toolkits: options.toolkits,
40 + })
41 + : Option.none();
42 +
43 + const connectionContext = Option.isSome(cachedAuthConfigs)
44 + ? {
45 + connectedToolkits: options?.toolkits ?? [],
46 + authConfigs: cachedAuthConfigs.value.authConfigs,
47 + }
48 + : yield* resolveToolRouterSessionConnections(client, userId, {
49 + toolkits: options?.toolkits,
50 + });
51 +
52 + if (options?.cacheScope && Option.isNone(cachedAuthConfigs)) {
53 + yield* writeConsumerConnectedToolkitsCache({
54 + orgId: options.cacheScope.orgId,
55 + consumerUserId: options.cacheScope.consumerUserId,
56 + toolkits: connectionContext.connectedToolkits,
57 + toolRouterAuthConfigs: {
58 + authConfigs: connectionContext.authConfigs,
59 + },
60 + }).pipe(Effect.catchAll(() => Effect.void));
61 + }
62 +
63 + return yield* Effect.tryPromise(() =>
64 + client.toolRouter.session.create({
65 + user_id: userId,
66 + auth_configs: connectionContext.authConfigs,
67 + manage_connections: { enable: options?.manageConnections ?? false },
68 + toolkits:
69 + options?.toolkits && options.toolkits.length > 0
70 + ? { enable: [...options.toolkits] }
71 + : undefined,
72 + })
73 + ).pipe(Effect.map(session => session.session_id));
74 + });
75
76 /**
77 * Resolve the Composio client and create a Tool Router session in one step.
ts/packages/cli/src/services/consumer-short-term-cache.ts
+132 -7
@@ -6,19 +6,26 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
6 import { NodeProcess } from 'src/services/node-process';
7 import {
8 ComposioToolkitsRepository,
9 + ComposioClientSingleton,
10 getConsumerConnectedToolkits,
11 resolveConsumerProject,
12 } from 'src/services/composio-clients';
13 import { resolveCommandProject } from 'src/services/command-project';
14 +import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';
15 import { ComposioUserContext } from 'src/services/user-context';
16
17 const CACHE_FILE = 'consumer-short-term-cache.json';
18 const CACHE_TTL_MS = 15 * 60 * 1000;
19 const SEARCH_SESSION_EXTENSION_MS = 5 * 60 * 1000;
20
21 +export type ConsumerToolRouterAuthConfigMappings = {
22 + readonly authConfigs?: Record<string, string>;
23 +};
24 +
25 type CacheEntry = {
26 readonly toolkits: ReadonlyArray<string>;
27 readonly expiresAt: string;
28 + readonly toolRouterAuthConfigs?: ConsumerToolRouterAuthConfigMappings;
29 readonly probablyMyCliSessionsByCwdHash?: Record<
30 string,
31 {
@@ -121,6 +128,42 @@ const normalizeCachedToolkits = (
128 noAuthToolkits: ReadonlyArray<string>
129 ) => [...new Set([...toolkits, ...noAuthToolkits].map(toolkit => toolkit.toLowerCase()))];
130
131 +const normalizeAuthConfigMappings = (
132 + mappings?: ConsumerToolRouterAuthConfigMappings
133 +): ConsumerToolRouterAuthConfigMappings | undefined => {
134 + if (!mappings) return undefined;
135 +
136 + const authConfigs = Object.fromEntries(
137 + Object.entries(mappings.authConfigs ?? {})
138 + .map(([toolkit, authConfigId]) => [toolkit.toLowerCase(), authConfigId])
139 + .filter(([, authConfigId]) => typeof authConfigId === 'string' && authConfigId.length > 0)
140 + );
141 + if (Object.keys(authConfigs).length === 0) {
142 + return undefined;
143 + }
144 +
145 + return {
146 + authConfigs,
147 + };
148 +};
149 +
150 +const mergeAuthConfigMappings = (params: {
151 + readonly current?: ConsumerToolRouterAuthConfigMappings;
152 + readonly next?: ConsumerToolRouterAuthConfigMappings;
153 +}) => {
154 + const current = normalizeAuthConfigMappings(params.current);
155 + const next = normalizeAuthConfigMappings(params.next);
156 + if (!current) return next;
157 + if (!next) return current;
158 +
159 + return normalizeAuthConfigMappings({
160 + authConfigs: {
161 + ...(current.authConfigs ?? {}),
162 + ...(next.authConfigs ?? {}),
163 + },
164 + });
165 +};
166 +
167 export const getFreshConsumerConnectedToolkitsFromCache = (params: {
168 orgId: string;
169 consumerUserId: string;
@@ -142,6 +185,53 @@ export const getFreshConsumerConnectedToolkitsFromCache = (params: {
185 return Option.some(entry.toolkits);
186 });
187
188 +export const getFreshConsumerToolRouterAuthConfigsFromCache = (params: {
189 + orgId: string;
190 + consumerUserId: string;
191 + toolkits?: ReadonlyArray<string>;
192 +}) =>
193 + Effect.gen(function* () {
194 + const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;
195 + if (disabled) {
196 + return Option.none<ConsumerToolRouterAuthConfigMappings>();
197 + }
198 + const state = yield* readCache();
199 + const entry = state[cacheKey(params.orgId, params.consumerUserId)];
200 + if (!entry) {
201 + return Option.none<ConsumerToolRouterAuthConfigMappings>();
202 + }
203 + const expiresAtMs = Date.parse(entry.expiresAt);
204 + if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) {
205 + return Option.none<ConsumerToolRouterAuthConfigMappings>();
206 + }
207 +
208 + const mappings = normalizeAuthConfigMappings(entry.toolRouterAuthConfigs);
209 + if (!mappings) {
210 + return Option.none<ConsumerToolRouterAuthConfigMappings>();
211 + }
212 +
213 + if (!params.toolkits || params.toolkits.length === 0) {
214 + return Option.some(mappings);
215 + }
216 +
217 + const requestedToolkits = params.toolkits.map(toolkit => toolkit.toLowerCase());
218 + const requestedAuthConfigs = requestedToolkits.map(
219 + toolkit => [toolkit, mappings.authConfigs?.[toolkit]] as const
220 + );
221 +
222 + if (requestedAuthConfigs.some(([, authConfigId]) => typeof authConfigId !== 'string')) {
223 + return Option.none<ConsumerToolRouterAuthConfigMappings>();
224 + }
225 +
226 + const filtered = normalizeAuthConfigMappings({
227 + authConfigs: Object.fromEntries(
228 + requestedAuthConfigs.map(([toolkit, authConfigId]) => [toolkit, authConfigId as string])
229 + ),
230 + });
231 +
232 + return filtered ? Option.some(filtered) : Option.none<ConsumerToolRouterAuthConfigMappings>();
233 + });
234 +
235 export const invalidateConsumerConnectedToolkitsCache = () =>
236 Effect.gen(function* () {
237 const fs = yield* FileSystem.FileSystem;
@@ -210,12 +300,34 @@ export const refreshConsumerConnectedToolkitsCache = (params?: {
300 return;
301 }
302
213 - const response = yield* getConsumerConnectedToolkits({
214 - baseURL: userContext.data.baseURL,
215 - apiKey,
216 - orgId: scope.orgId,
217 - consumerUserId: scope.consumerUserId,
218 - });
303 + const clientSingleton = yield* ComposioClientSingleton;
304 + const directToolkits = yield* Effect.gen(function* () {
305 + const consumerProject = yield* resolveConsumerProject({
306 + baseURL: userContext.data.baseURL,
307 + apiKey,
308 + orgId: scope.orgId,
309 + });
310 + const client = yield* clientSingleton.getFor({
311 + orgId: scope.orgId,
312 + projectId: consumerProject.project_id,
313 + });
314 + const connectionContext = yield* resolveToolRouterSessionConnections(
315 + client,
316 + scope.consumerUserId
317 + );
318 + return connectionContext;
319 + }).pipe(Effect.option);
320 +
321 + const connectedToolkits =
322 + Option.isSome(directToolkits) && directToolkits.value.connectedToolkits.length > 0
323 + ? directToolkits.value.connectedToolkits
324 + : (yield* getConsumerConnectedToolkits({
325 + baseURL: userContext.data.baseURL,
326 + apiKey,
327 + orgId: scope.orgId,
328 + consumerUserId: scope.consumerUserId,
329 + })).toolkits;
330 +
331 const noAuthToolkits = yield* getAlwaysConnectedNoAuthToolkits();
332 const state = yield* readCache();
333 const key = cacheKey(scope.orgId, scope.consumerUserId);
@@ -228,8 +340,16 @@ export const refreshConsumerConnectedToolkitsCache = (params?: {
340 yield* writeCache({
341 ...state,
342 [key]: {
231 - toolkits: normalizeCachedToolkits(response.toolkits, noAuthToolkits),
343 + toolkits: normalizeCachedToolkits(connectedToolkits, noAuthToolkits),
344 expiresAt: new Date(Date.now() + CACHE_TTL_MS).toISOString(),
345 + toolRouterAuthConfigs: mergeAuthConfigMappings({
346 + current: currentEntry?.toolRouterAuthConfigs,
347 + next: Option.isSome(directToolkits)
348 + ? {
349 + authConfigs: directToolkits.value.authConfigs,
350 + }
351 + : undefined,
352 + }),
353 ...searchSessionFields,
354 },
355 });
@@ -239,6 +359,7 @@ export const writeConsumerConnectedToolkitsCache = (params: {
359 readonly orgId: string;
360 readonly consumerUserId: string;
361 readonly toolkits: ReadonlyArray<string>;
362 + readonly toolRouterAuthConfigs?: ConsumerToolRouterAuthConfigMappings;
363 }) =>
364 Effect.gen(function* () {
365 const disabled = yield* APP_CONFIG.DISABLE_CONNECTED_ACCOUNT_CACHE;
@@ -258,6 +379,10 @@ export const writeConsumerConnectedToolkitsCache = (params: {
379 [key]: {
380 toolkits: normalizeCachedToolkits(params.toolkits, noAuthToolkits),
381 expiresAt: new Date(Date.now() + CACHE_TTL_MS).toISOString(),
382 + toolRouterAuthConfigs: mergeAuthConfigMappings({
383 + current: currentEntry?.toolRouterAuthConfigs,
384 + next: params.toolRouterAuthConfigs,
385 + }),
386 ...searchSessionFields,
387 },
388 });
ts/packages/cli/src/services/tool-router-session-connections.ts new
+98
@@ -0,0 +1,98 @@
1 +import { Effect } from 'effect';
2 +import type { Composio } from '@composio/client';
3 +
4 +type RawConnectedAccount = {
5 + readonly id: string;
6 + readonly toolkit?: {
7 + readonly slug?: string | null;
8 + } | null;
9 + readonly auth_config?: {
10 + readonly id?: string | null;
11 + readonly is_composio_managed?: boolean | null;
12 + } | null;
13 + readonly updated_at?: string | null;
14 + readonly created_at?: string | null;
15 +};
16 +
17 +export type ToolRouterSessionConnectionContext = {
18 + readonly connectedToolkits: ReadonlyArray<string>;
19 + readonly authConfigs?: Record<string, string>;
20 +};
21 +
22 +const parseTimestamp = (value?: string | null): number => {
23 + if (!value) return 0;
24 + const parsed = Date.parse(value);
25 + return Number.isFinite(parsed) ? parsed : 0;
26 +};
27 +
28 +const isNewerAccount = (candidate: RawConnectedAccount, current: RawConnectedAccount): boolean => {
29 + const candidateTimestamp = Math.max(
30 + parseTimestamp(candidate.updated_at),
31 + parseTimestamp(candidate.created_at)
32 + );
33 + const currentTimestamp = Math.max(
34 + parseTimestamp(current.updated_at),
35 + parseTimestamp(current.created_at)
36 + );
37 + return candidateTimestamp > currentTimestamp;
38 +};
39 +
40 +export const resolveToolRouterSessionConnections = (
41 + client: Composio,
42 + userId: string,
43 + options?: {
44 + readonly toolkits?: ReadonlyArray<string>;
45 + }
46 +) =>
47 + Effect.tryPromise(() =>
48 + client.connectedAccounts.list({
49 + user_ids: [userId],
50 + statuses: ['ACTIVE'],
51 + toolkit_slugs:
52 + options?.toolkits && options.toolkits.length > 0 ? [...options.toolkits] : undefined,
53 + limit: 1000,
54 + })
55 + ).pipe(
56 + Effect.map(response => {
57 + const items = (response.items ?? []) as ReadonlyArray<RawConnectedAccount>;
58 + const connectedToolkits = new Set<string>();
59 + const explicitAccountsByToolkit = new Map<string, RawConnectedAccount>();
60 +
61 + for (const item of items) {
62 + const toolkit = item.toolkit?.slug?.toLowerCase().trim();
63 + if (!toolkit) continue;
64 +
65 + connectedToolkits.add(toolkit);
66 +
67 + // Tool Router already handles Composio-managed auth well.
68 + // Explicitly pin non-managed auth configs/accounts so consumer sessions
69 + // can execute against custom-auth toolkits like PostHog.
70 + if (item.auth_config?.is_composio_managed !== false) {
71 + continue;
72 + }
73 +
74 + const current = explicitAccountsByToolkit.get(toolkit);
75 + if (!current || isNewerAccount(item, current)) {
76 + explicitAccountsByToolkit.set(toolkit, item);
77 + }
78 + }
79 +
80 + const authConfigs: Record<string, string> = {};
81 + for (const [toolkit, item] of explicitAccountsByToolkit) {
82 + const authConfigId = item.auth_config?.id?.trim();
83 + if (!authConfigId) continue;
84 + authConfigs[toolkit] = authConfigId;
85 + }
86 +
87 + return {
88 + connectedToolkits: [...connectedToolkits],
89 + authConfigs: Object.keys(authConfigs).length > 0 ? authConfigs : undefined,
90 + } satisfies ToolRouterSessionConnectionContext;
91 + }),
92 + Effect.catchAll(() =>
93 + Effect.succeed({
94 + connectedToolkits: [],
95 + authConfigs: undefined,
96 + } satisfies ToolRouterSessionConnectionContext)
97 + )
98 + );
ts/packages/cli/src/services/tools-executor.ts
+8 -2
@@ -1,3 +1,4 @@
1 +import { FileSystem } from '@effect/platform';
2 import { Context, Effect, Layer } from 'effect';
3 import type { Composio } from '@composio/client';
4 import type {
@@ -5,7 +6,6 @@ import type {
6 SessionExecuteMetaResponse,
7 SessionExecuteMetaParams,
8 } from '@composio/client/resources/tool-router';
8 -import type { FileSystem } from '@effect/platform';
9 import { ComposioClientSingleton } from 'src/services/composio-clients';
10 import { createToolRouterSession } from 'src/effects/create-tool-router-session';
11 import {
@@ -15,6 +15,7 @@ import {
15 import { getOrFetchToolInputDefinition } from 'src/services/tool-input-validation';
16 import { uploadToolInputFiles } from 'src/services/tool-file-uploads';
17 import type { NodeOs } from 'src/services/node-os';
18 +import type { NodeProcess } from 'src/services/node-process';
19 import type { ComposioUserContext } from 'src/services/user-context';
20 import type { ComposioToolkitsRepository } from 'src/services/composio-clients';
21
@@ -25,6 +26,10 @@ export interface ToolExecuteParams {
26 readonly userId: string;
27 readonly arguments: Record<string, unknown>;
28 readonly client?: Composio;
29 + readonly cacheScope?: {
30 + readonly orgId: string;
31 + readonly consumerUserId: string;
32 + };
33 }
34
35 /**
@@ -44,7 +49,7 @@ export interface ToolsExecutor {
49 ) => Effect.Effect<
50 ToolExecuteResponse,
51 unknown,
47 - FileSystem.FileSystem | NodeOs | ComposioUserContext | ComposioToolkitsRepository
52 + FileSystem.FileSystem | NodeOs | NodeProcess | ComposioUserContext | ComposioToolkitsRepository
53 >;
54 }
55
@@ -132,6 +137,7 @@ export const ToolsExecutorLive = Layer.effect(
137 // One session per invocation — CLI runs one tool per process.
138 const sessionId = yield* createToolRouterSession(resolvedClient, params.userId, {
139 manageConnections: true,
140 + cacheScope: params.cacheScope,
141 });
142 const normalizedArguments = isMetaToolSlug(slug)
143 ? params.arguments
ts/packages/cli/test/__utils__/services/test-layer.ts
+32
@@ -939,6 +939,38 @@ export const TestLayer = (input?: TestLiveInput) =>
939 },
940 },
941 connectedAccounts: {
942 + list: async (params?: {
943 + toolkit_slugs?: string[];
944 + user_ids?: string[];
945 + statuses?: string[];
946 + limit?: number;
947 + }) => {
948 + let results = [...connectedAccountsData.items];
949 +
950 + if (params?.toolkit_slugs && params.toolkit_slugs.length > 0) {
951 + const slugs = new Set(params.toolkit_slugs.map(slug => slug.toLowerCase()));
952 + results = results.filter(item => slugs.has(item.toolkit.slug.toLowerCase()));
953 + }
954 +
955 + if (params?.user_ids && params.user_ids.length > 0) {
956 + const userIds = new Set(params.user_ids);
957 + results = results.filter(item => userIds.has(item.user_id));
958 + }
959 +
960 + if (params?.statuses && params.statuses.length > 0) {
961 + const statuses = new Set(params.statuses);
962 + results = results.filter(item => statuses.has(item.status));
963 + }
964 +
965 + const limit = params?.limit ?? 30;
966 + return {
967 + items: results.slice(0, limit),
968 + total_items: results.length,
969 + total_pages: Math.ceil(results.length / limit),
970 + current_page: 1,
971 + next_cursor: null,
972 + };
973 + },
974 retrieve: async (nanoid: string) => {
975 const found = connectedAccountsData.items.find(item => item.id === nanoid);
976 if (!found) {
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+130
@@ -60,6 +60,11 @@ describe('CLI: composio execute', () => {
60 if (savedCI !== undefined) process.env.CI = savedCI;
61 });
62
63 + let recordedSessionCreateParams: Array<Record<string, unknown>> = [];
64 + beforeEach(() => {
65 + recordedSessionCreateParams = [];
66 + });
67 +
68 layer(
69 TestLive({
70 baseConfigProvider: testConfigProvider,
@@ -92,6 +97,131 @@ describe('CLI: composio execute', () => {
97 TestLive({
98 baseConfigProvider: testConfigProvider,
99 fixture: 'global-test-user-id',
100 + stdin: { isTTY: true, data: '' },
101 + connectedAccountsData: {
102 + items: [
103 + {
104 + id: 'con_posthog_active',
105 + status: 'ACTIVE',
106 + status_reason: null,
107 + is_disabled: false,
108 + user_id: 'consumer-user-org_test',
109 + toolkit: { slug: 'posthog' },
110 + auth_config: {
111 + id: 'ac_posthog_custom',
112 + auth_scheme: 'BEARER_TOKEN',
113 + is_composio_managed: false,
114 + is_disabled: false,
115 + },
116 + created_at: '2026-01-01T00:00:00.000Z',
117 + updated_at: '2026-01-02T00:00:00.000Z',
118 + test_request_endpoint: '',
119 + },
120 + ],
121 + },
122 + toolRouter: {
123 + create: async params => {
124 + recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
125 + return {
126 + session_id: 'trs_posthog_test_session',
127 + config: { user_id: params.user_id },
128 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
129 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
130 + };
131 + },
132 + execute: async (_sessionId, params) => ({
133 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
134 + error: null,
135 + log_id: 'log_posthog_test',
136 + }),
137 + },
138 + })
139 + )(
140 + '[Given] a non-managed connected account [Then] execute preloads auth configs into the Tool Router session',
141 + it => {
142 + it.scoped('passes explicit auth_configs for custom auth toolkits', () =>
143 + Effect.gen(function* () {
144 + yield* cli([
145 + 'execute',
146 + 'POSTHOG_RUN_ENDPOINT',
147 + '--skip-checks',
148 + '-d',
149 + '{"project_id":"196278","name":"test"}',
150 + ]);
151 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
152 + const output = parseLastJson(lines);
153 +
154 + expect(output.successful).toBe(true);
155 + expect(recordedSessionCreateParams).toHaveLength(1);
156 + expect(recordedSessionCreateParams[0]?.user_id).toEqual(expect.any(String));
157 + expect(recordedSessionCreateParams[0]?.auth_configs).toEqual({
158 + posthog: 'ac_posthog_custom',
159 + });
160 + expect(recordedSessionCreateParams[0]?.connected_accounts).toBeUndefined();
161 + })
162 + );
163 + }
164 + );
165 +
166 + layer(
167 + TestLive({
168 + baseConfigProvider: testConfigProvider,
169 + fixture: 'global-test-user-id',
170 + stdin: { isTTY: true, data: '' },
171 + toolRouter: {
172 + create: async params => {
173 + recordedSessionCreateParams.push(params as unknown as Record<string, unknown>);
174 + return {
175 + session_id: 'trs_posthog_cached_session',
176 + config: { user_id: params.user_id },
177 + mcp: { type: 'http' as const, url: 'https://mcp.test.composio.dev' },
178 + tool_router_tools: ['COMPOSIO_SEARCH_TOOLS', 'COMPOSIO_MANAGE_CONNECTIONS'],
179 + };
180 + },
181 + execute: async (_sessionId, params) => ({
182 + data: { tool_slug: params.tool_slug, arguments: params.arguments },
183 + error: null,
184 + log_id: 'log_posthog_cached',
185 + }),
186 + },
187 + })
188 + )('[Given] cached auth configs [Then] execute seeds the session from cache', it => {
189 + it.scoped('uses cached auth_configs for consumer execute sessions', () =>
190 + Effect.gen(function* () {
191 + vi.spyOn(
192 + consumerShortTermCache,
193 + 'getFreshConsumerToolRouterAuthConfigsFromCache'
194 + ).mockReturnValue(
195 + Effect.succeed(
196 + Option.some({
197 + authConfigs: {
198 + posthog: 'ac_posthog_cached',
199 + },
200 + })
201 + )
202 + );
203 +
204 + yield* cli([
205 + 'execute',
206 + 'POSTHOG_RUN_ENDPOINT',
207 + '--skip-checks',
208 + '-d',
209 + '{"project_id":"196278","name":"test"}',
210 + ]);
211 +
212 + expect(recordedSessionCreateParams).toHaveLength(1);
213 + expect(recordedSessionCreateParams[0]?.auth_configs).toEqual({
214 + posthog: 'ac_posthog_cached',
215 + });
216 + })
217 + );
218 + });
219 +
220 + layer(
221 + TestLive({
222 + baseConfigProvider: testConfigProvider,
223 + fixture: 'global-test-user-id',
224 + stdin: { isTTY: true, data: '' },
225 toolkitsData: {
226 tools: [
227 {
ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
+65
@@ -5,6 +5,7 @@ import { extendConfigProvider } from 'src/services/config';
5 import * as composioClients from 'src/services/composio-clients';
6 import {
7 getFreshConsumerConnectedToolkitsFromCache,
8 + getFreshConsumerToolRouterAuthConfigsFromCache,
9 refreshConsumerConnectedToolkitsCache,
10 writeConsumerConnectedToolkitsCache,
11 } from 'src/services/consumer-short-term-cache';
@@ -175,4 +176,68 @@ describe('consumer short-term cache', () => {
176 })
177 );
178 });
179 +
180 + layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
181 + '[Given] a full auth-config cache hit [Then] cache reads are toolkit-complete',
182 + it => {
183 + it.scoped('returns cached auth configs when every requested toolkit is covered', () =>
184 + Effect.gen(function* () {
185 + yield* writeConsumerConnectedToolkitsCache({
186 + orgId: 'org_test',
187 + consumerUserId: 'consumer-user-test',
188 + toolkits: ['posthog', 'hubspot'],
189 + toolRouterAuthConfigs: {
190 + authConfigs: {
191 + posthog: 'ac_posthog',
192 + hubspot: 'ac_hubspot',
193 + },
194 + },
195 + });
196 +
197 + const cached = yield* getFreshConsumerToolRouterAuthConfigsFromCache({
198 + orgId: 'org_test',
199 + consumerUserId: 'consumer-user-test',
200 + toolkits: ['posthog', 'hubspot'],
201 + });
202 +
203 + expect(cached).toEqual(
204 + Option.some({
205 + authConfigs: {
206 + posthog: 'ac_posthog',
207 + hubspot: 'ac_hubspot',
208 + },
209 + })
210 + );
211 + })
212 + );
213 + }
214 + );
215 +
216 + layer(TestLive({ baseConfigProvider: cacheEnabledTestConfigProvider }))(
217 + '[Given] a partial auth-config cache hit [Then] cache read fails closed',
218 + it => {
219 + it.scoped('returns none unless every requested toolkit has a cached auth config', () =>
220 + Effect.gen(function* () {
221 + yield* writeConsumerConnectedToolkitsCache({
222 + orgId: 'org_test',
223 + consumerUserId: 'consumer-user-test',
224 + toolkits: ['posthog', 'hubspot'],
225 + toolRouterAuthConfigs: {
226 + authConfigs: {
227 + posthog: 'ac_posthog',
228 + },
229 + },
230 + });
231 +
232 + const cached = yield* getFreshConsumerToolRouterAuthConfigsFromCache({
233 + orgId: 'org_test',
234 + consumerUserId: 'consumer-user-test',
235 + toolkits: ['posthog', 'hubspot'],
236 + });
237 +
238 + expect(cached).toEqual(Option.none());
239 + })
240 + );
241 + }
242 + );
243 });