@devries-cameron20 / composio Mirror · read-only / commits / 4b5920bf7
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 21, 12:15 UTC

feat(sdk): add session.ensureConnected to reconcile connection state (#4536)

This PR: - addresses the connection-readiness finding from the Sept 2026 SDK + client hackathon (area 8): `session.authorize()` always starts a new link flow, even when the session already resolves an ACTIVE connection for the toolkit — callers ended up with a pending connected account while `session.toolkits()` reported a different, active one, and nothing in the SDK reconciled the two - adds `session.ensureConnected(toolkit, options?)`: it checks the session's connection state first — an ACTIVE connection (or a no-auth toolkit) returns immediately with `wasConnected: true` and no link is created; otherwise it starts the authorization flow and waits for the new connection to become active (`timeout` option, default 60s) - keeps `authorize()` unchanged as the primitive for interactive flows that should surface the redirect URL instead of blocking - documents the `session.execute()` `account` option's runtime contract: accepted on every project, and on single-account projects the identifier must match one of the session's active connections for the toolkit (matching the API behavior after the Apollo side-fix) - adds 5 unit tests for `ensureConnected` (already-connected no-op, no-auth short-circuit, link-and-wait, pending-account relink, option validation) and a changeset Verification: `pnpm exec vitest run` in `ts/packages/core` — 1320 passed; `pnpm typecheck` (tsc + type tests) clean; `pnpm lint` clean at repo root.

Alberto Schiabel committed Sep 18, 2026 at 18:56 UTC 4b5920bf7aa55c8a44657b060d4bd25ce7b13a9a
4 files changed +223 -2
.changeset/session-ensure-connected.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Add `session.ensureConnected(toolkit, options?)`: it returns immediately when the session already resolves an active connection (or the toolkit is no-auth), and only when needed starts the authorization flow via `session.authorize()` and waits for the new connection to become active. This prevents `authorize()` from spawning duplicate pending connections for toolkits that are already connected. The `session.execute()` `account` option is now documented as accepted on every project — on single-account projects the identifier must match one of the session's active connections for the toolkit (matching the API behavior).
ts/packages/core/src/models/ToolRouterSession.ts
+81 -1
@@ -23,6 +23,9 @@ import {
23 ToolRouterSessionWarning,
24 ToolRouterUpdateSessionConfig,
25 ToolRouterUpdateSessionConfigSchema,
26 + ToolRouterSessionEnsureConnectedOptions,
27 + ToolRouterSessionEnsureConnectedOptionsSchema,
28 + ToolRouterSessionEnsureConnectedResult,
29 type ToolRouterSessionDeleteResponse,
30 } from '../types/toolRouter.types';
31 import {
@@ -484,6 +487,83 @@ export class ToolRouterSession<
487 );
488 }
489
490 + /**
491 + * Ensure a toolkit has an active connection in this session, reconciling
492 + * `authorize()`/`session.link` with the session's active connection state.
493 + *
494 + * If the session already resolves an ACTIVE connection (or the toolkit is
495 + * no-auth), this returns immediately without creating a link — unlike
496 + * `authorize()`, which always starts a new link flow, even when one is
497 + * already connected. Otherwise it starts the authorization flow and waits
498 + * for the new connection to become ACTIVE.
499 + *
500 + * For interactive flows that should surface the redirect URL instead of
501 + * blocking, use `authorize()` and its `waitForConnection()` directly.
502 + *
503 + * @param toolkit - The toolkit slug to ensure a connection for (e.g. 'github')
504 + * @param options - Optional authorization options plus `timeout` (ms to wait
505 + * for a newly-initiated connection, default 60000)
506 + * @returns The toolkit's canonical slug, whether it was already connected,
507 + * and the active connected account (omitted for no-auth toolkits)
508 + * @throws {ValidationError} If the options fail validation
509 + * @throws {ConnectionRequestTimeoutError} If a newly-initiated connection does
510 + * not become active within `timeout`
511 + * @throws {ConnectionRequestFailedError} If the new connection enters a failed,
512 + * expired, or revoked state
513 + *
514 + * @example
515 + * ```typescript
516 + * const session = await composio.sessions.create({ toolkits: ['github'] });
517 + * const { wasConnected, connectedAccount } = await session.ensureConnected('github');
518 + * if (!wasConnected) console.log('Newly linked:', connectedAccount?.id);
519 + * ```
520 + */
521 + async ensureConnected(
522 + toolkit: string,
523 + options?: ToolRouterSessionEnsureConnectedOptions,
524 + requestOptions?: ComposioRequestOptions
525 + ): Promise<ToolRouterSessionEnsureConnectedResult> {
526 + const parsedOptions = ToolRouterSessionEnsureConnectedOptionsSchema.safeParse(options ?? {});
527 + if (!parsedOptions.success) {
528 + throw new ValidationError('Failed to parse tool router ensureConnected options', {
529 + cause: parsedOptions.error,
530 + });
531 + }
532 + const { callbackUrl, alias, experimental, timeout } = parsedOptions.data;
533 +
534 + const state = await this.toolkits({ toolkits: [toolkit] }, requestOptions);
535 + const existing = state.items.find(item => item.slug.toLowerCase() === toolkit.toLowerCase());
536 +
537 + if (existing?.isNoAuth) {
538 + return { toolkit: existing.slug, wasConnected: true };
539 + }
540 + const activeAccount = existing?.connection?.connectedAccount;
541 + if (existing?.connection?.isActive && activeAccount) {
542 + return {
543 + toolkit: existing.slug,
544 + wasConnected: true,
545 + connectedAccount: { id: activeAccount.id, status: activeAccount.status },
546 + };
547 + }
548 +
549 + const request = await this.authorize(
550 + toolkit,
551 + {
552 + ...(callbackUrl !== undefined && { callbackUrl }),
553 + ...(alias !== undefined && { alias }),
554 + ...(experimental !== undefined && { experimental }),
555 + },
556 + requestOptions
557 + );
558 + const account = await request.waitForConnection(timeout);
559 +
560 + return {
561 + toolkit: existing?.slug ?? toolkit,
562 + wasConnected: false,
563 + connectedAccount: { id: account.id, status: account.status },
564 + };
565 + }
566 +
567 /**
568 * Query the connection state of toolkits in the session.
569 * Supports pagination and filtering by toolkit slugs.
@@ -581,7 +661,7 @@ export class ToolRouterSession<
661 * @param toolSlug - The tool slug to execute
662 * @param arguments_ - Optional tool arguments
663 * @param options - Optional execution options
584 - * @param options.account - Account identifier for direct app tool execution in multi-account sessions. Helper/meta tools either ignore this top-level field or define their own account-selection fields.
664 + * @param options.account - Account identifier for direct app tool execution. Accepted on every project: in multi-account sessions it picks the account; on single-account projects it must match one of the session's active connections for the toolkit. Helper/meta tools either ignore this top-level field or define their own account-selection fields.
665 * @returns The tool execution result
666 */
667 async execute(
ts/packages/core/src/types/toolRouter.types.ts
+35 -1
@@ -5,6 +5,7 @@ import { ConnectionRequest } from './connectionRequest.types';
5 import type { ComposioRequestOptions } from './requestOptions.types';
6 import type { ToolRouterSessionFilesMount } from '../models/ToolRouterSessionFileMount';
7 import type { SessionCreateResponse } from '@composio/client/resources/tool-router/session/session.mjs';
8 +import { ConnectedAccountExperimentalSchema } from './connectedAccounts.types';
9 import type {
10 CustomTool,
11 CustomToolkit,
@@ -591,7 +592,9 @@ export type ToolRouterSessionExecuteFn = (
592
593 export interface ToolRouterSessionExecuteOptions {
594 /**
594 - * Account identifier for direct app tool execution in multi-account sessions.
595 + * Account identifier for direct app tool execution. Accepted on every project:
596 + * in multi-account sessions it picks the account; on single-account projects it
597 + * must match one of the session's active connections for the toolkit.
598 * Meta/helper tools either ignore this top-level field or define
599 * their own account-selection fields, for example
600 * COMPOSIO_MULTI_EXECUTE_TOOL.tools[].account.
@@ -722,6 +725,35 @@ export type ToolRouterSessionDeleteFn = (
725 requestOptions?: ComposioRequestOptions
726 ) => Promise<ToolRouterSessionDeleteResponse>;
727
728 +export const ToolRouterSessionEnsureConnectedOptionsSchema = z.object({
729 + callbackUrl: z.string().optional(),
730 + alias: z.string().optional(),
731 + experimental: ConnectedAccountExperimentalSchema.optional(),
732 + /** Max time to wait for a newly-initiated connection to become active, in milliseconds. Defaults to 60000. */
733 + timeout: z.number().int().positive().optional(),
734 +});
735 +export type ToolRouterSessionEnsureConnectedOptions = z.infer<
736 + typeof ToolRouterSessionEnsureConnectedOptionsSchema
737 +>;
738 +
739 +export type ToolRouterSessionEnsureConnectedResult = {
740 + /** Canonical slug of the toolkit this call ensured. */
741 + toolkit: string;
742 + /** True when the session already had an active connection (or a no-auth toolkit) — no link was created. */
743 + wasConnected: boolean;
744 + /** The active connected account backing the toolkit. Omitted for no-auth toolkits. */
745 + connectedAccount?: {
746 + id: string;
747 + status: string;
748 + };
749 +};
750 +
751 +export type ToolRouterSessionEnsureConnectedFn = (
752 + toolkit: string,
753 + options?: ToolRouterSessionEnsureConnectedOptions,
754 + requestOptions?: ComposioRequestOptions
755 +) => Promise<ToolRouterSessionEnsureConnectedResult>;
756 +
757 /** Session type returned by ToolRouter.create() and ToolRouter.use() */
758 export interface Session<
759 TToolCollection,
@@ -756,6 +788,8 @@ export interface Session<
788 warnings: ToolRouterSessionWarning[];
789 tools: ToolRouterToolsFn<TToolCollection, TTool, TProvider>;
790 authorize: ToolRouterAuthorizeFn;
791 + /** Ensure a toolkit has an active connection, linking and waiting only when needed. */
792 + ensureConnected: ToolRouterSessionEnsureConnectedFn;
793 toolkits: ToolRouterToolkitsFn;
794 /** Search for tools by semantic use case */
795 search: ToolRouterSessionSearchFn;
ts/packages/core/test/models/toolRouter.test.ts
+102
@@ -12,6 +12,7 @@ import {
12 SessionPreset,
13 type ToolRouterSessionConfig,
14 } from '../../src/types/toolRouter.types';
15 +import type { ConnectionRequest } from '../../src/types/connectionRequest.types';
16 import { createCustomTool } from '../../src/models/CustomTool';
17 import { DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX } from '../../src/models/ToolRouterSession';
18
@@ -2090,6 +2091,107 @@ describe('ToolRouter', () => {
2091 });
2092 });
2093
2094 + describe('ensureConnected function', () => {
2095 + const userId = 'user_123';
2096 + const sessionId = 'session_123';
2097 +
2098 + beforeEach(async () => {
2099 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
2100 + });
2101 +
2102 + it('returns the active connection without linking when the toolkit is already connected', async () => {
2103 + mockClient.toolRouter.session.toolkits.mockResolvedValueOnce(mockToolkitsResponse);
2104 +
2105 + const session = await toolRouter.create(userId);
2106 + const result = await session.ensureConnected('gmail');
2107 +
2108 + expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(
2109 + sessionId,
2110 + expect.objectContaining({ toolkits: ['gmail'] }),
2111 + undefined
2112 + );
2113 + expect(mockClient.toolRouter.session.link).not.toHaveBeenCalled();
2114 + expect(result).toEqual({
2115 + toolkit: 'gmail',
2116 + wasConnected: true,
2117 + connectedAccount: { id: 'conn_123', status: 'ACTIVE' },
2118 + });
2119 + });
2120 +
2121 + it('treats a no-auth toolkit as connected without linking', async () => {
2122 + mockClient.toolRouter.session.toolkits.mockResolvedValueOnce({
2123 + items: [{ slug: 'search', name: 'Search', is_no_auth: true, connected_account: null }],
2124 + next_cursor: null,
2125 + total_pages: 1,
2126 + });
2127 +
2128 + const session = await toolRouter.create(userId);
2129 + const result = await session.ensureConnected('search');
2130 +
2131 + expect(mockClient.toolRouter.session.link).not.toHaveBeenCalled();
2132 + expect(result).toEqual({ toolkit: 'search', wasConnected: true });
2133 + });
2134 +
2135 + it('links and waits for a connection when the toolkit has none', async () => {
2136 + // github has connected_account: null in the shared mock response.
2137 + mockClient.toolRouter.session.toolkits.mockResolvedValueOnce(mockToolkitsResponse);
2138 +
2139 + const session = await toolRouter.create(userId);
2140 + const waitForConnection = vi.fn().mockResolvedValue({ id: 'conn_456', status: 'ACTIVE' });
2141 + const authorizeSpy = vi.spyOn(session, 'authorize').mockResolvedValue({
2142 + id: 'conn_456',
2143 + status: ConnectedAccountStatuses.INITIATED,
2144 + redirectUrl: 'https://composio.dev/auth/redirect',
2145 + waitForConnection,
2146 + } as unknown as ConnectionRequest);
2147 +
2148 + const result = await session.ensureConnected('github', { timeout: 5000 });
2149 +
2150 + expect(authorizeSpy).toHaveBeenCalledWith('github', {}, undefined);
2151 + expect(waitForConnection).toHaveBeenCalledWith(5000);
2152 + expect(result).toEqual({
2153 + toolkit: 'github',
2154 + wasConnected: false,
2155 + connectedAccount: { id: 'conn_456', status: 'ACTIVE' },
2156 + });
2157 + });
2158 +
2159 + it('links a new connection when the only linked account is still pending', async () => {
2160 + // slack has an INITIATED (non-active) connected_account in the shared mock.
2161 + mockClient.toolRouter.session.toolkits.mockResolvedValueOnce(mockToolkitsResponse);
2162 +
2163 + const session = await toolRouter.create(userId);
2164 + const waitForConnection = vi.fn().mockResolvedValue({ id: 'conn_789', status: 'ACTIVE' });
2165 + const authorizeSpy = vi.spyOn(session, 'authorize').mockResolvedValue({
2166 + id: 'conn_789',
2167 + status: ConnectedAccountStatuses.INITIATED,
2168 + redirectUrl: null,
2169 + waitForConnection,
2170 + } as unknown as ConnectionRequest);
2171 +
2172 + const result = await session.ensureConnected('slack');
2173 +
2174 + expect(authorizeSpy).toHaveBeenCalledWith('slack', {}, undefined);
2175 + expect(waitForConnection).toHaveBeenCalledWith(undefined);
2176 + expect(result).toEqual({
2177 + toolkit: 'slack',
2178 + wasConnected: false,
2179 + connectedAccount: { id: 'conn_789', status: 'ACTIVE' },
2180 + });
2181 + });
2182 +
2183 + it('rejects invalid timeout options without calling the API', async () => {
2184 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
2185 + const session = await toolRouter.create(userId);
2186 +
2187 + await expect(session.ensureConnected('github', { timeout: -1 })).rejects.toMatchObject({
2188 + name: 'ValidationError',
2189 + });
2190 + expect(mockClient.toolRouter.session.toolkits).not.toHaveBeenCalled();
2191 + expect(mockClient.toolRouter.session.link).not.toHaveBeenCalled();
2192 + });
2193 + });
2194 +
2195 describe('toolkits function', () => {
2196 const userId = 'user_123';
2197 const sessionId = 'session_123';