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

feat(core): add AbortSignal cancellation to public SDK methods + ComposioRequestCancelledError (#3463)

# Description Add per-request cancellation to every public SDK method via `AbortSignal`, and surface caller-initiated aborts as a typed `ComposioRequestCancelledError`. ## API For `tools.get` and `tools.execute`, pass `signal` directly in the options bag (3rd arg) alongside modifiers — no placeholder needed: ```typescript // Timeout a slow search const tools = await composio.tools.get('user_1', { search: 'send email', }, { signal: AbortSignal.timeout(5_000) }); // Cancel an execution, with modifiers const result = await composio.tools.execute('TOOL', body, { signal: AbortSignal.timeout(10_000), beforeExecute: ({ params }) => params, }); // Detect cancellation try { await composio.tools.execute(slug, body, { signal: AbortSignal.timeout(5_000) }); } catch (err) { if (err instanceof ComposioRequestCancelledError) return; throw err; } ``` For other methods, pass as a trailing argument: ```typescript await composio.authConfigs.list(query, { signal: AbortSignal.timeout(5_000) }); await composio.connectedAccounts.get(id, { signal: AbortSignal.timeout(5_000) }); ``` ## Cancellation contract - `withCancellation()` normalizes any abort error into `ComposioRequestCancelledError` (code `TS-SDK::REQUEST_CANCELLED`) - `isRequestAbortError()` detects `APIUserAbortError` via `instanceof` (required because `.name === "Error"` at runtime), with fallbacks for dual-package hazard and generic `AbortError` - Catch-and-wrap paths in `execute` / `getRawComposioToolBySlug` / `toolkits.get` re-throw cancellation before domain error wrapping - **Post-execute safety**: if the signal fires after the remote tool already executed, the result is returned (not thrown) — prevents callers from retrying non-idempotent operations - Custom-tool cancellation is cooperative: signal is exposed via the `ctx` arg so user code can wire it into `fetch` ## Coverage Tools, Toolkits, AuthConfigs, ConnectedAccounts, Triggers, MCP, ToolRouter, ToolRouterSession — every public method that does HTTP I/O. # How did I test this PR - `pnpm exec vitest run` — 666 tests pass (25 pre-existing fileModifiers failures unchanged) - `pnpm typecheck` — 11/11 clean - CI: Typecheck, Build, Audit, Test, all 5 E2E runtimes (Node 20.18/20.19/22.12, Deno, Cloudflare), secrets scan — all green 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com> Co-authored-by: jkomyno <alberto@composio.dev>

Zen committed Jun 24, 2026 at 21:56 UTC dfd7a0846d0a6b75f4c379b1f6c4d30d49c6c0e7
34 files changed +3589 -1686
.changeset/core-request-options-signal-timeout.md new
+57
@@ -0,0 +1,57 @@
1 +---
2 +"@composio/core": minor
3 +---
4 +
5 +Add per-request cancellation to public SDK methods via a new `ComposioRequestOptions` (`{ signal?: AbortSignal }`) trailing argument, plus a typed `ComposioRequestCancelledError` for detecting caller-initiated aborts.
6 +
7 +Without this, a slow `tools.get` or `tools.execute` had no way to be cancelled — a 100s search would block the calling agent indefinitely. The new shape:
8 +
9 +```typescript
10 +try {
11 + const tools = await composio.tools.get(
12 + 'user_1',
13 + { search: 'send email', limit: 50 },
14 + { signal: AbortSignal.timeout(5_000) }
15 + );
16 +} catch (err) {
17 + if (err instanceof ComposioRequestCancelledError) {
18 + return;
19 + }
20 + throw err;
21 +}
22 +```
23 +
24 +The signal is forwarded to the underlying `@composio/client` fetch. Any abort error (`APIUserAbortError`, `AbortError`, or `DOMException(name='AbortError')`) coming back is normalized to `ComposioRequestCancelledError` so callers can `instanceof`-detect cancellation without unwrapping nested causes. Catch-and-wrap paths in `tools.execute` / `tools.getRawComposioToolBySlug` / `toolkits.get` re-throw the cancellation error rather than remapping it to `ComposioToolExecutionError` / `ComposioToolNotFoundError` / `ComposioToolkitFetchError`.
25 +
26 +Wired through on:
27 +- **Tools**: `get`, `getRawComposioTools`, `getRawComposioToolBySlug`, `getRawToolRouterSessionTools`, `execute`, `executeSessionTool`, `getToolsEnum`, `getInput`, `proxyExecute`
28 +- **Toolkits**: `get`, `listCategories`
29 +- **AuthConfigs**: `list`, `create`, `get`, `update`, `delete`, `updateStatus`, `enable`, `disable`
30 +- **ConnectedAccounts**: `list`, `get`, `delete`, `refresh`, `updateStatus`, `enable`, `disable`, `update`
31 +- **Triggers**: `listActive`, `create`, `update`, `delete`, `enable`, `disable`, `listTypes`, `getType`, `listEnum`
32 +- **MCP**: `create`, `list`, `get`, `delete`, `update`, `generate`
33 +- **ToolRouter** (`composio.create` / `composio.use`, `composio.toolRouter.create` / `.use`) — long-running session-creation paths
34 +- **ToolRouterSession**: `authorize`, `toolkits`, `search`, `execute`, `proxyExecute`, `update`
35 +
36 +### Custom-tool cooperative cancellation
37 +
38 +Native tool execution is cancelled by the SDK (the underlying `fetch` is aborted). Custom tools are different — the SDK can't preempt user-supplied JavaScript. Two affordances are added so callers get sensible behavior anyway:
39 +
40 +1. **Pre-execute signal check**: if `signal.aborted` is true before the user's `execute` runs, the SDK throws `ComposioRequestCancelledError` and never invokes user code.
41 +2. **Cooperative signal forwarding**: the same `AbortSignal` is exposed via `SessionContext.signal` for Tool Router custom tools. Long-running implementations can wire `ctx.signal` into their own `fetch` (or any abortable IO) to abort mid-execution; the resulting `AbortError` is normalized to `ComposioRequestCancelledError` by the SDK.
42 +
43 +```typescript
44 +import { experimental_createTool } from '@composio/core';
45 +
46 +const longRunningFetch = experimental_createTool('LONG_RUNNING_FETCH', {
47 + name: 'Long-running fetch',
48 + description: 'Fetches a URL with cooperative cancellation',
49 + inputParams: z.object({ url: z.string() }),
50 + execute: async (input, ctx) => {
51 + // Pass ctx.signal into fetch so a session.execute(...) abort cancels
52 + // the in-flight HTTP request mid-flight.
53 + const resp = await fetch(input.url, { signal: ctx.signal });
54 + return { result: await resp.json() };
55 + },
56 +});
57 +```
ts/packages/core/src/composio.ts
+10 -2
@@ -15,6 +15,7 @@ import { checkForLatestVersionFromNPM } from './utils/version';
15 import { OpenAIProvider } from './provider/OpenAIProvider';
16 import { version } from '../package.json';
17 import type { ComposioRequestHeaders } from './types/composio.types';
18 +import type { ComposioRequestOptions } from './types/requestOptions.types';
19 import { Files } from '#files';
20 import { getDefaultHeaders } from './utils/session';
21 import { ToolkitVersionParam } from './types/tool.types';
@@ -237,18 +238,25 @@ export class Composio<
238 */
239 create: (
240 userId: string,
240 - routerConfig?: ToolRouterCreateSessionConfig
241 + routerConfig?: ToolRouterCreateSessionConfig,
242 + requestOptions?: ComposioRequestOptions
243 ) => Promise<Session<unknown, unknown, TProvider>>;
244
245 /**
246 * Use an existing tool router session
247 *
248 * @param id {string} The id of the session to use
249 + * @param options {object} Custom tools / toolkits to attach to the session
250 + * @param requestOptions {ComposioRequestOptions} Per-request cancellation
251 + * options. The supplied AbortSignal aborts the underlying session
252 + * retrieve/attach call only. Subsequent session method calls accept
253 + * their own per-call requestOptions.
254 * @returns {Promise<Session<TToolCollection, TTool, TProvider>>} The tool router session
255 */
256 use: (
257 id: string,
251 - options?: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[] }
258 + options?: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[] },
259 + requestOptions?: ComposioRequestOptions
260 ) => Promise<Session<unknown, unknown, TProvider>>;
261
262 /**
ts/packages/core/src/errors/SDKErrors.ts
+64
@@ -1,7 +1,9 @@
1 +import { APIUserAbortError } from '@composio/client';
2 import { ComposioError, ComposioErrorOptions } from './ComposioError';
3
4 export const SDKErrorCodes = {
5 NO_API_KEY_PROVIDED: 'NO_API_KEY_PROVIDED',
6 + REQUEST_CANCELLED: 'REQUEST_CANCELLED',
7 };
8
9 export class ComposioNoAPIKeyError extends ComposioError {
@@ -26,3 +28,65 @@ export class ComposioNoAPIKeyError extends ComposioError {
28 this.name = 'ComposioNoAPIKeyError';
29 }
30 }
31 +
32 +/**
33 + * Thrown when an SDK call is cancelled via the caller-supplied `AbortSignal`.
34 + *
35 + * @example
36 + * ```typescript
37 + * try {
38 + * await composio.tools.execute(slug, body, { signal: AbortSignal.timeout(5_000) });
39 + * } catch (err) {
40 + * if (err instanceof ComposioRequestCancelledError) return;
41 + * throw err;
42 + * }
43 + * ```
44 + */
45 +export class ComposioRequestCancelledError extends ComposioError {
46 + constructor(
47 + message: string = 'Request was cancelled by the caller',
48 + options: Omit<ComposioErrorOptions, 'code'> = {}
49 + ) {
50 + super(message, {
51 + ...options,
52 + code: SDKErrorCodes.REQUEST_CANCELLED,
53 + possibleFixes: options.possibleFixes ?? [
54 + 'This error is expected when you abort the request via AbortController. Handle it in your catch block to distinguish caller-initiated cancellation from other failures.',
55 + ],
56 + });
57 + this.name = 'ComposioRequestCancelledError';
58 + }
59 +}
60 +
61 +/**
62 + * `APIUserAbortError` has `.name === "Error"` at runtime (doesn't override it),
63 + * so we fall back to `constructor.name` for dual-package-hazard cases.
64 + * @internal
65 + */
66 +export function isRequestAbortError(error: unknown): boolean {
67 + return _isRequestAbortErrorAt(error, /* depth= */ 0);
68 +}
69 +
70 +function _isRequestAbortErrorAt(error: unknown, depth: number): boolean {
71 + if (depth > 5) return false;
72 + if (error instanceof APIUserAbortError) return true;
73 + if (
74 + typeof DOMException !== 'undefined' &&
75 + error instanceof DOMException &&
76 + error.name === 'AbortError'
77 + ) {
78 + return true;
79 + }
80 + if (!(error instanceof Error)) return false;
81 + if (
82 + error.constructor.name === 'APIUserAbortError' ||
83 + error.name === 'AbortError' ||
84 + error.name === 'APIUserAbortError'
85 + ) {
86 + return true;
87 + }
88 + if ('cause' in error && error.cause !== undefined && error.cause !== null) {
89 + return _isRequestAbortErrorAt(error.cause, depth + 1);
90 + }
91 + return false;
92 +}
ts/packages/core/src/index.ts
+1
@@ -36,6 +36,7 @@ export * from './types/files.types';
36 export * from './types/connectionRequest.types';
37 export * from './types/toolRouter.types';
38 export * from './types/ToolRouterSessionFilesMount.types';
39 +export * from './types/requestOptions.types';
40 export * as constants from './utils/constants';
41
42 export { default as logger } from './utils/logger';
ts/packages/core/src/models/AuthConfigs.ts
+70 -22
@@ -29,6 +29,8 @@ import {
29 transformAuthConfigRetrieveResponse,
30 transformCreateAuthConfigResponse,
31 } from '../utils/transformers/authConfigs';
32 +import { ComposioRequestOptions } from '../types/requestOptions.types';
33 +import { withCancellation } from '../utils/cancellation';
34 /**
35 * AuthConfigs class
36 *
@@ -84,16 +86,23 @@ export class AuthConfigs {
86 * });
87 * ```
88 */
87 - async list(query?: AuthConfigListParams): Promise<AuthConfigListResponse> {
89 + async list(
90 + query?: AuthConfigListParams,
91 + requestOptions?: ComposioRequestOptions
92 + ): Promise<AuthConfigListResponse> {
93 const parsedQuery = query ? AuthConfigListParamsSchema.parse(query) : undefined;
89 - const result = await this.client.authConfigs.list({
94 + const listParams = {
95 cursor: parsedQuery?.cursor,
96 is_composio_managed: parsedQuery?.isComposioManaged,
97 limit: parsedQuery?.limit,
98 search: parsedQuery?.search,
99 show_disabled: parsedQuery?.showDisabled,
100 toolkit_slug: parsedQuery?.toolkit,
96 - });
101 + };
102 + const result = await withCancellation(
103 + () => this.client.authConfigs.list(listParams, requestOptions),
104 + requestOptions?.signal
105 + );
106 return transformAuthConfigListResponse(result);
107 }
108
@@ -117,7 +126,8 @@ export class AuthConfigs {
126 */
127 async create(
128 toolkit: string,
120 - options: CreateAuthConfigParams = { type: 'use_composio_managed_auth' }
129 + options: CreateAuthConfigParams = { type: 'use_composio_managed_auth' },
130 + requestOptions?: ComposioRequestOptions
131 ): Promise<CreateAuthConfigResponse> {
132 const parsedOptions = CreateAuthConfigParamsSchema.safeParse(options);
133 if (parsedOptions.error) {
@@ -125,7 +135,7 @@ export class AuthConfigs {
135 cause: parsedOptions.error,
136 });
137 }
128 - const result = await this.client.authConfigs.create({
138 + const createBody = {
139 toolkit: {
140 slug: toolkit,
141 },
@@ -162,7 +172,11 @@ export class AuthConfigs {
172 }
173 : undefined,
174 },
165 - });
175 + };
176 + const result = await withCancellation(
177 + () => this.client.authConfigs.create(createBody, requestOptions),
178 + requestOptions?.signal
179 + );
180 return transformCreateAuthConfigResponse(result);
181 }
182
@@ -185,8 +199,14 @@ export class AuthConfigs {
199 * console.log(authConfig.toolkit.slug); // e.g., 'github'
200 * ```
201 */
188 - async get(nanoid: string): Promise<AuthConfigRetrieveResponse> {
189 - const result = await this.client.authConfigs.retrieve(nanoid);
202 + async get(
203 + nanoid: string,
204 + requestOptions?: ComposioRequestOptions
205 + ): Promise<AuthConfigRetrieveResponse> {
206 + const result = await withCancellation(
207 + () => this.client.authConfigs.retrieve(nanoid, requestOptions),
208 + requestOptions?.signal
209 + );
210 return transformAuthConfigRetrieveResponse(result);
211 }
212
@@ -220,18 +240,21 @@ export class AuthConfigs {
240 * });
241 * ```
242 */
223 - async update(nanoid: string, data: AuthConfigUpdateParams): Promise<AuthConfigUpdateResponse> {
243 + async update(
244 + nanoid: string,
245 + data: AuthConfigUpdateParams,
246 + requestOptions?: ComposioRequestOptions
247 + ): Promise<AuthConfigUpdateResponse> {
248 const parsedData = AuthConfigUpdateParamsSchema.safeParse(data);
249 if (parsedData.error) {
250 throw new ValidationError('Failed to parse auth config update data', {
251 cause: parsedData.error,
252 });
253 }
230 - return this.client.authConfigs.update(
231 - nanoid,
254 + const updateBody =
255 parsedData.data.type === 'custom'
256 ? {
234 - type: 'custom',
257 + type: 'custom' as const,
258 credentials: parsedData.data.credentials,
259 is_enabled_for_tool_router: parsedData.data.isEnabledForToolRouter,
260 tool_access_config: {
@@ -243,7 +266,7 @@ export class AuthConfigs {
266 },
267 }
268 : {
246 - type: 'default',
269 + type: 'default' as const,
270 scopes: parsedData.data.scopes,
271 is_enabled_for_tool_router: parsedData.data.isEnabledForToolRouter,
272 tool_access_config: {
@@ -253,7 +276,10 @@ export class AuthConfigs {
276 parsedData.data.toolAccessConfig?.toolsAvailableForExecution ??
277 parsedData.data.restrictToFollowingTools,
278 },
256 - }
279 + };
280 + return withCancellation(
281 + () => this.client.authConfigs.update(nanoid, updateBody, requestOptions),
282 + requestOptions?.signal
283 );
284 }
285
@@ -274,8 +300,14 @@ export class AuthConfigs {
300 * await composio.authConfigs.delete('auth_abc123');
301 * ```
302 */
277 - async delete(nanoid: string): Promise<AuthConfigDeleteResponse> {
278 - return this.client.authConfigs.delete(nanoid);
303 + async delete(
304 + nanoid: string,
305 + requestOptions?: ComposioRequestOptions
306 + ): Promise<AuthConfigDeleteResponse> {
307 + return withCancellation(
308 + () => this.client.authConfigs.delete(nanoid, undefined, requestOptions),
309 + requestOptions?.signal
310 + );
311 }
312
313 /**
@@ -301,9 +333,13 @@ export class AuthConfigs {
333 */
334 async updateStatus(
335 status: 'ENABLED' | 'DISABLED',
304 - nanoid: string
336 + nanoid: string,
337 + requestOptions?: ComposioRequestOptions
338 ): Promise<AuthConfigUpdateStatusResponse> {
306 - return this.client.authConfigs.updateStatus(status, { nanoid });
339 + return withCancellation(
340 + () => this.client.authConfigs.updateStatus(status, { nanoid }, requestOptions),
341 + requestOptions?.signal
342 + );
343 }
344
345 /**
@@ -323,8 +359,14 @@ export class AuthConfigs {
359 * await composio.authConfigs.enable('auth_abc123');
360 * ```
361 */
326 - async enable(nanoid: string): Promise<AuthConfigUpdateStatusResponse> {
327 - return this.client.authConfigs.updateStatus('ENABLED', { nanoid });
362 + async enable(
363 + nanoid: string,
364 + requestOptions?: ComposioRequestOptions
365 + ): Promise<AuthConfigUpdateStatusResponse> {
366 + return withCancellation(
367 + () => this.client.authConfigs.updateStatus('ENABLED', { nanoid }, requestOptions),
368 + requestOptions?.signal
369 + );
370 }
371
372 /**
@@ -344,7 +386,13 @@ export class AuthConfigs {
386 * await composio.authConfigs.disable('auth_abc123');
387 * ```
388 */
347 - async disable(nanoid: string): Promise<AuthConfigUpdateStatusResponse> {
348 - return this.client.authConfigs.updateStatus('DISABLED', { nanoid });
389 + async disable(
390 + nanoid: string,
391 + requestOptions?: ComposioRequestOptions
392 + ): Promise<AuthConfigUpdateStatusResponse> {
393 + return withCancellation(
394 + () => this.client.authConfigs.updateStatus('DISABLED', { nanoid }, requestOptions),
395 + requestOptions?.signal
396 + );
397 }
398 }
ts/packages/core/src/models/ConnectedAccounts.ts
+117 -45
@@ -48,6 +48,9 @@ import {
48 } from '../errors';
49 import logger from '../utils/logger';
50 import { ConnectionData } from '../types/connectedAccountAuthStates.types';
51 +import { ComposioRequestOptions } from '../types/requestOptions.types';
52 +import { withCancellation } from '../utils/cancellation';
53 +import { ComposioRequestCancelledError } from '../errors/SDKErrors';
54
55 // One-time-per-process guard so long-running services don't spam the deprecation
56 // warning on every initiate() call.
@@ -91,7 +94,10 @@ export class ConnectedAccounts {
94 * });
95 * ```
96 */
94 - async list(query?: ConnectedAccountListParams): Promise<ConnectedAccountListResponse> {
97 + async list(
98 + query?: ConnectedAccountListParams,
99 + requestOptions?: ComposioRequestOptions
100 + ): Promise<ConnectedAccountListResponse> {
101 let rawQuery: ConnectedAccountListParamsRaw | undefined = undefined;
102
103 if (query) {
@@ -119,7 +125,10 @@ export class ConnectedAccounts {
125 };
126 }
127
122 - const result = await this.client.connectedAccounts.list(rawQuery);
128 + const result = await withCancellation(
129 + () => this.client.connectedAccounts.list(rawQuery, requestOptions),
130 + requestOptions?.signal
131 + );
132 return transformConnectedAccountListResponse(result);
133 }
134
@@ -193,14 +202,18 @@ export class ConnectedAccounts {
202 async initiate(
203 userId: string,
204 authConfigId: string,
196 - options?: CreateConnectedAccountOptions
205 + options?: CreateConnectedAccountOptions,
206 + requestOptions?: ComposioRequestOptions
207 ): Promise<ConnectionRequest> {
208 // Check if there are multiple connected accounts for the authConfig of the user
199 - const connectedAccount = await this.list({
200 - userIds: [userId],
201 - authConfigIds: [authConfigId],
202 - statuses: [ConnectedAccountStatuses.ACTIVE],
203 - });
209 + const connectedAccount = await this.list(
210 + {
211 + userIds: [userId],
212 + authConfigIds: [authConfigId],
213 + statuses: [ConnectedAccountStatuses.ACTIVE],
214 + },
215 + requestOptions
216 + );
217 if (connectedAccount.items.length > 0 && !options?.allowMultiple) {
218 throw new ComposioMultipleConnectedAccountsError(
219 `Multiple connected accounts found for user ${userId} in auth config ${authConfigId}. Please use the allowMultiple option to allow multiple connected accounts.`
@@ -244,25 +257,34 @@ export class ConnectedAccounts {
257 // caller needs to migrate. Custom auth configs and non-OAuth schemes
258 // never see the header, eliminating the false-positive warning that
259 // an `auth_scheme`-only check produced for `link()`-unaffected callers.
247 - const apiCall = this.client.connectedAccounts.create(createParams);
260 + const apiCall = this.client.connectedAccounts.create(createParams, requestOptions);
261 if (typeof (apiCall as { withResponse?: unknown }).withResponse === 'function') {
249 - const resolved = await (
250 - apiCall as unknown as {
251 - withResponse: () => Promise<{
252 - data: ConnectedAccountCreateResponse;
253 - response: Response;
254 - }>;
255 - }
256 - ).withResponse();
262 + const resolved = await withCancellation(
263 + () =>
264 + (
265 + apiCall as unknown as {
266 + withResponse: () => Promise<{
267 + data: ConnectedAccountCreateResponse;
268 + response: Response;
269 + }>;
270 + }
271 + ).withResponse(),
272 + requestOptions?.signal
273 + );
274 response = resolved.data;
275 httpResponse = resolved.response;
276 } else {
277 // Test mocks may return a plain Promise without `withResponse`.
278 // Fall back to a naked await; the deprecation gate below stays
279 // off in that case (no header to read).
263 - response = await apiCall;
280 + response = await withCancellation(() => apiCall, requestOptions?.signal);
281 }
282 } catch (error) {
283 + // Caller-initiated cancellation must surface as the typed error,
284 + // not get remapped to the legacy-endpoint error below.
285 + if (error instanceof ComposioRequestCancelledError) {
286 + throw error;
287 + }
288 // When the server has flipped this org to the retired path, the legacy
289 // endpoint returns 400 with a stable migration message. Surface it as
290 // a typed error so callers get an actionable hint instead of a generic
@@ -346,23 +368,29 @@ export class ConnectedAccounts {
368 async link(
369 userId: string,
370 authConfigId: string,
349 - options?: CreateConnectedAccountLinkOptions
371 + options?: CreateConnectedAccountLinkOptions,
372 + requestOptions?: ComposioRequestOptions
373 ): Promise<ConnectionRequest> {
351 - const requestOptions = await CreateConnectedAccountLinkOptionsSchema.safeParse(options || {});
352 - if (!requestOptions.success) {
374 + const parsedLinkOptions = CreateConnectedAccountLinkOptionsSchema.safeParse(options || {});
375 + if (!parsedLinkOptions.success) {
376 throw new ValidationError('Failed to parse create connected account link options', {
354 - cause: requestOptions.error,
377 + cause: parsedLinkOptions.error,
378 });
379 }
380
381 // Mirror initiate(): guard against silently creating extra connections on
359 - // the same auth config unless the caller explicitly opts in.
360 - const existing = await this.list({
361 - userIds: [userId],
362 - authConfigIds: [authConfigId],
363 - statuses: [ConnectedAccountStatuses.ACTIVE],
364 - });
365 - if (existing.items.length > 0 && !requestOptions.data.allowMultiple) {
382 + // the same auth config unless the caller explicitly opts in. The preflight
383 + // list call honors the caller's signal too — the whole composite is
384 + // cancellable as a single unit.
385 + const existing = await this.list(
386 + {
387 + userIds: [userId],
388 + authConfigIds: [authConfigId],
389 + statuses: [ConnectedAccountStatuses.ACTIVE],
390 + },
391 + requestOptions
392 + );
393 + if (existing.items.length > 0 && !parsedLinkOptions.data.allowMultiple) {
394 throw new ComposioMultipleConnectedAccountsError(
395 `Multiple connected accounts found for user ${userId} in auth config ${authConfigId}. Please use the allowMultiple option to allow multiple connected accounts.`
396 );
@@ -372,7 +400,7 @@ export class ConnectedAccounts {
400 );
401 }
402
375 - const opts = requestOptions.data;
403 + const opts = parsedLinkOptions.data;
404 const experimentalWire = serializeExperimentalForWire(opts.experimental);
405 const body: LinkCreateParams = {
406 auth_config_id: authConfigId,
@@ -383,7 +411,10 @@ export class ConnectedAccounts {
411 };
412
413 try {
386 - const response = await this.client.link.create(body);
414 + const response = await withCancellation(
415 + () => this.client.link.create(body, requestOptions),
416 + requestOptions?.signal
417 + );
418
419 const connectionRequest = createConnectionRequest(
420 this.client,
@@ -393,6 +424,11 @@ export class ConnectedAccounts {
424 );
425 return connectionRequest;
426 } catch (error) {
427 + // Caller-initiated cancellation must surface as the typed error,
428 + // not get remapped to ComposioFailedToCreateConnectedAccountLink below.
429 + if (error instanceof ComposioRequestCancelledError) {
430 + throw error;
431 + }
432 // The server rejects ACL on PRIVATE connections — surface that as a
433 // typed error so callers can `instanceof` instead of grepping messages.
434 if (
@@ -459,8 +495,14 @@ export class ConnectedAccounts {
495 * console.log(account.toolkit.slug); // e.g., 'github'
496 * ```
497 */
462 - async get(nanoid: string): Promise<ConnectedAccountRetrieveResponse> {
463 - const response = await this.client.connectedAccounts.retrieve(nanoid);
498 + async get(
499 + nanoid: string,
500 + requestOptions?: ComposioRequestOptions
501 + ): Promise<ConnectedAccountRetrieveResponse> {
502 + const response = await withCancellation(
503 + () => this.client.connectedAccounts.retrieve(nanoid, requestOptions),
504 + requestOptions?.signal
505 + );
506 return transformConnectedAccountResponse(response);
507 }
508
@@ -480,8 +522,14 @@ export class ConnectedAccounts {
522 * await composio.connectedAccounts.delete('conn_abc123');
523 * ```
524 */
483 - async delete(nanoid: string): Promise<ConnectedAccountDeleteResponse> {
484 - return this.client.connectedAccounts.delete(nanoid);
525 + async delete(
526 + nanoid: string,
527 + requestOptions?: ComposioRequestOptions
528 + ): Promise<ConnectedAccountDeleteResponse> {
529 + return withCancellation(
530 + () => this.client.connectedAccounts.delete(nanoid, undefined, requestOptions),
531 + requestOptions?.signal
532 + );
533 }
534
535 /**
@@ -502,7 +550,8 @@ export class ConnectedAccounts {
550 */
551 async refresh(
552 nanoid: string,
505 - options?: ConnectedAccountRefreshOptions
553 + options?: ConnectedAccountRefreshOptions,
554 + requestOptions?: ComposioRequestOptions
555 ): Promise<ConnectedAccountRefreshResponse> {
556 let params: ConnectedAccountRefreshParams | undefined = undefined;
557
@@ -520,7 +569,10 @@ export class ConnectedAccounts {
569 };
570 }
571
523 - return this.client.connectedAccounts.refresh(nanoid, params);
572 + return withCancellation(
573 + () => this.client.connectedAccounts.refresh(nanoid, params, requestOptions),
574 + requestOptions?.signal
575 + );
576 }
577
578 /**
@@ -545,9 +597,13 @@ export class ConnectedAccounts {
597 */
598 async updateStatus(
599 nanoid: string,
548 - params: ConnectedAccountUpdateStatusParams
600 + params: ConnectedAccountUpdateStatusParams,
601 + requestOptions?: ComposioRequestOptions
602 ): Promise<ConnectedAccountUpdateStatusResponse> {
550 - return this.client.connectedAccounts.updateStatus(nanoid, params);
603 + return withCancellation(
604 + () => this.client.connectedAccounts.updateStatus(nanoid, params, requestOptions),
605 + requestOptions?.signal
606 + );
607 }
608
609 /**
@@ -562,8 +618,14 @@ export class ConnectedAccounts {
618 * console.log(enabledAccount.isDisabled); // false
619 * ```
620 */
565 - async enable(nanoid: string): Promise<ConnectedAccountUpdateStatusResponse> {
566 - return this.client.connectedAccounts.updateStatus(nanoid, { enabled: true });
621 + async enable(
622 + nanoid: string,
623 + requestOptions?: ComposioRequestOptions
624 + ): Promise<ConnectedAccountUpdateStatusResponse> {
625 + return withCancellation(
626 + () => this.client.connectedAccounts.updateStatus(nanoid, { enabled: true }, requestOptions),
627 + requestOptions?.signal
628 + );
629 }
630
631 /**
@@ -584,8 +646,14 @@ export class ConnectedAccounts {
646 * // });
647 * ```
648 */
587 - async disable(nanoid: string): Promise<ConnectedAccountUpdateStatusResponse> {
588 - return this.client.connectedAccounts.updateStatus(nanoid, { enabled: false });
649 + async disable(
650 + nanoid: string,
651 + requestOptions?: ComposioRequestOptions
652 + ): Promise<ConnectedAccountUpdateStatusResponse> {
653 + return withCancellation(
654 + () => this.client.connectedAccounts.updateStatus(nanoid, { enabled: false }, requestOptions),
655 + requestOptions?.signal
656 + );
657 }
658
659 /**
@@ -606,7 +674,8 @@ export class ConnectedAccounts {
674 */
675 async update(
676 nanoid: string,
609 - params: UpdateConnectedAccountParams
677 + params: UpdateConnectedAccountParams,
678 + requestOptions?: ComposioRequestOptions
679 ): Promise<ConnectedAccountUpdateStatusResponse> {
680 const parsedParams = UpdateConnectedAccountParamsSchema.safeParse(params);
681 if (!parsedParams.success) {
@@ -615,6 +684,9 @@ export class ConnectedAccounts {
684 });
685 }
686
618 - return this.client.connectedAccounts.updateStatus(nanoid, parsedParams.data);
687 + return withCancellation(
688 + () => this.client.connectedAccounts.updateStatus(nanoid, parsedParams.data, requestOptions),
689 + requestOptions?.signal
690 + );
691 }
692 }
ts/packages/core/src/models/MCP.ts
+59 -17
@@ -22,6 +22,8 @@ import { ValidationError } from '../errors/ValidationErrors';
22 import { transform } from '../utils/transform';
23 import { McpUpdateResponse } from '@composio/client/resources.js';
24 import { McpRetrieveResponse } from '@composio/client/resources';
25 +import { ComposioRequestOptions } from '../types/requestOptions.types';
26 +import { withCancellation } from '../utils/cancellation';
27
28 function transformMCPItemResponse(response: McpUpdateResponse | McpRetrieveResponse): MCPItem {
29 return transform(response)
@@ -77,7 +79,11 @@ export class MCP {
79 * });
80 * ```
81 */
80 - async create(name: string, mcpConfig: MCPConfigCreationParams): Promise<MCPConfigCreateResponse> {
82 + async create(
83 + name: string,
84 + mcpConfig: MCPConfigCreationParams,
85 + requestOptions?: ComposioRequestOptions
86 + ): Promise<MCPConfigCreateResponse> {
87 const config = MCPConfigCreationParamsSchema.safeParse(mcpConfig);
88 if (config.error) {
89 throw new ValidationError('Invalid parameters passed to create mcp config', {
@@ -100,14 +106,18 @@ export class MCP {
106 }
107 });
108
103 - const server = await this.client.mcp.custom.create({
109 + const createBody = {
110 name,
111 toolkits,
112 auth_config_ids,
113 custom_tools,
114 // if manually manage account is set to true, disable composio account management tools
115 managed_auth_via_composio: config.data.manuallyManageConnections ? false : true,
110 - });
116 + };
117 + const server = await withCancellation(
118 + () => this.client.mcp.custom.create(createBody, requestOptions),
119 + requestOptions?.signal
120 + );
121
122 const camelCaseServer = transform(server)
123 .with(MCPConfigResponseSchema)
@@ -162,7 +172,10 @@ export class MCP {
172 * });
173 * ```
174 */
165 - async list(options: MCPListParams): Promise<MCPListResponse> {
175 + async list(
176 + options: MCPListParams,
177 + requestOptions?: ComposioRequestOptions
178 + ): Promise<MCPListResponse> {
179 const { data: params, error } = MCPListParamsSchema.safeParse(options);
180 if (error) {
181 throw new ValidationError('Failed to validate list options', {
@@ -170,13 +183,17 @@ export class MCP {
183 });
184 }
185
173 - const listResponse = await this.client.mcp.list({
186 + const listParams = {
187 page_no: params.page,
188 limit: params.limit,
189 toolkits: params.toolkits?.length > 0 ? params.toolkits.join(',') : undefined,
190 auth_config_ids: params.authConfigs?.length > 0 ? params.authConfigs.join(',') : undefined,
191 name: params.name,
179 - });
192 + };
193 + const listResponse = await withCancellation(
194 + () => this.client.mcp.list(listParams, requestOptions),
195 + requestOptions?.signal
196 + );
197
198 const transformedListResponse = transform(listResponse)
199 .with(MCPListResponseSchema)
@@ -225,8 +242,11 @@ export class MCP {
242 *
243 * @throws {ValidationError} When the server ID is invalid or server not found
244 */
228 - async get(serverId: string): Promise<MCPItem> {
229 - const response = await this.client.mcp.retrieve(serverId);
245 + async get(serverId: string, requestOptions?: ComposioRequestOptions): Promise<MCPItem> {
246 + const response = await withCancellation(
247 + () => this.client.mcp.retrieve(serverId, requestOptions),
248 + requestOptions?.signal
249 + );
250 return transformMCPItemResponse(response);
251 }
252
@@ -266,8 +286,14 @@ export class MCP {
286 *
287 * @warning This operation is irreversible. Once deleted, the MCP server configuration and all its associated data will be permanently removed.
288 */
269 - async delete(serverId: string): Promise<{ id: string; deleted: boolean }> {
270 - return await this.client.mcp.delete(serverId);
289 + async delete(
290 + serverId: string,
291 + requestOptions?: ComposioRequestOptions
292 + ): Promise<{ id: string; deleted: boolean }> {
293 + return withCancellation(
294 + () => this.client.mcp.delete(serverId, requestOptions),
295 + requestOptions?.signal
296 + );
297 }
298
299 /**
@@ -334,7 +360,11 @@ export class MCP {
360 * @note Only provided fields will be updated. Omitted fields will retain their current values.
361 * @note When updating toolkits, the entire toolkit configuration is replaced, not merged.
362 */
337 - async update(serverId: string, config: MCPUpdateParams): Promise<MCPItem> {
363 + async update(
364 + serverId: string,
365 + config: MCPUpdateParams,
366 + requestOptions?: ComposioRequestOptions
367 + ): Promise<MCPItem> {
368 const { data: params, error } = MCPUpdateParamsSchema.safeParse(config);
369 if (error) {
370 throw new ValidationError('Failed to validate update params', {
@@ -356,7 +386,7 @@ export class MCP {
386 auth_config_ids.push(toolkit.authConfigId);
387 }
388 });
359 - const response = await this.client.mcp.update(serverId, {
389 + const updateBody = {
390 ...{ name: params.name ?? undefined },
391 ...(params.toolkits
392 ? {
@@ -366,7 +396,11 @@ export class MCP {
396 }
397 : {}),
398 ...{ managed_auth_via_composio: params.manuallyManageConnections ?? undefined },
369 - });
399 + };
400 + const response = await withCancellation(
401 + () => this.client.mcp.update(serverId, updateBody, requestOptions),
402 + requestOptions?.signal
403 + );
404 return transformMCPItemResponse(response);
405 }
406
@@ -390,9 +424,13 @@ export class MCP {
424 async generate(
425 userId: string,
426 mcpConfigId: string,
393 - options?: MCPGetInstanceParams
427 + options?: MCPGetInstanceParams,
428 + requestOptions?: ComposioRequestOptions
429 ): Promise<MCPServerInstance> {
395 - const server = await this.client.mcp.retrieve(mcpConfigId);
430 + const server = await withCancellation(
431 + () => this.client.mcp.retrieve(mcpConfigId, requestOptions),
432 + requestOptions?.signal
433 + );
434 const params = MCPGetInstanceParamsSchema.safeParse(
435 options ?? { manuallyManageConnections: false }
436 );
@@ -402,11 +440,15 @@ export class MCP {
440 });
441 }
442
405 - const urlResponse = await this.client.mcp.generate.url({
443 + const urlBody = {
444 mcp_server_id: mcpConfigId,
445 user_ids: [userId],
446 managed_auth_by_composio: options?.manuallyManageConnections ? false : true,
409 - });
447 + };
448 + const urlResponse = await withCancellation(
449 + () => this.client.mcp.generate.url(urlBody, requestOptions),
450 + requestOptions?.signal
451 + );
452
453 const userIdsURL = urlResponse.user_ids_url[0];
454 const serverInstance = MCPServerInstanceSchema.safeParse({
ts/packages/core/src/models/SessionContext.ts
+24 -7
@@ -26,6 +26,7 @@ import {
26 import { transformExecuteResponse } from '../utils/transformers/toolRouterResponseTransform';
27 import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
28 import { inlineCustomToolsExperimental } from './inlineCustomToolsPayload';
29 +import { withCancellation } from '../utils/cancellation';
30
31 /**
32 * Concrete implementation of SessionContext.
@@ -39,6 +40,14 @@ import { inlineCustomToolsExperimental } from './inlineCustomToolsPayload';
40 export class SessionContextImpl implements SessionContext {
41 public readonly userId: string;
42
43 + /**
44 + * Per-execution AbortSignal. Never set on the base instance; `executeCustomTool`
45 + * grafts it onto a per-call `Object.create` child so concurrent executions
46 + * sharing this context don't observe each other's signal. Declared here (rather
47 + * than read via a cast) so the contract is explicit.
48 + */
49 + public readonly signal?: AbortSignal;
50 +
51 constructor(
52 private readonly client: ComposioClient,
53 userId: string,
@@ -60,10 +69,12 @@ export class SessionContextImpl implements SessionContext {
69 toolSlug: string,
70 arguments_: Record<string, unknown>
71 ): Promise<ToolRouterSessionExecuteResponse> {
63 - // Try local tool first (sibling routing)
72 + const signal = this.signal;
73 + const requestOptions = signal ? { signal } : undefined;
74 +
75 const entry = findCustomTool(this.customToolsMap, toolSlug);
76 if (entry) {
66 - const result = await executeCustomTool(entry, arguments_, this);
77 + const result = await executeCustomTool(entry, arguments_, this, { signal });
78 return ToolRouterSessionExecuteResponseSchema.parse({
79 data: result.data,
80 error: result.error,
@@ -72,7 +83,6 @@ export class SessionContextImpl implements SessionContext {
83 }
84 assertUnambiguousCustomToolSlug(this.customToolsMap, toolSlug);
85
75 - // Fall back to remote execution
86 const executeParams: SessionExecuteParams = {
87 tool_slug: toolSlug,
88 arguments: arguments_,
@@ -84,7 +94,10 @@ export class SessionContextImpl implements SessionContext {
94 executeParams.experimental = experimental;
95 }
96
87 - const response = await this.client.toolRouter.session.execute(this.sessionId, executeParams);
97 + const response = await withCancellation(
98 + () => this.client.toolRouter.session.execute(this.sessionId, executeParams, requestOptions),
99 + requestOptions?.signal
100 + );
101 return ToolRouterSessionExecuteResponseSchema.parse(transformExecuteResponse(response));
102 }
103
@@ -100,10 +113,14 @@ export class SessionContextImpl implements SessionContext {
113 throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });
114 }
115
116 + const signal = this.signal;
117 + const requestOptions = signal ? { signal } : undefined;
118 +
119 const clientParams = transformProxyParams(validated.data);
104 - const response = await this.client.toolRouter.session.proxyExecute(
105 - this.sessionId,
106 - clientParams
120 + const response = await withCancellation(
121 + () =>
122 + this.client.toolRouter.session.proxyExecute(this.sessionId, clientParams, requestOptions),
123 + requestOptions?.signal
124 );
125
126 return {
ts/packages/core/src/models/ToolRouter.ts
+19 -7
@@ -52,6 +52,8 @@ import {
52 } from '../lib/toolRouterParams';
53 import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
54 import { ToolRouterSession } from './ToolRouterSession';
55 +import { ComposioRequestOptions } from '../types/requestOptions.types';
56 +import { withCancellation } from '../utils/cancellation';
57 import {
58 assertNoCustomToolSlugsInPreload,
59 buildCustomToolsMap,
@@ -167,7 +169,8 @@ export class ToolRouter<
169 */
170 async create(
171 userId: string,
170 - config?: ToolRouterCreateSessionConfig
172 + config?: ToolRouterCreateSessionConfig,
173 + requestOptions?: ComposioRequestOptions
174 ): Promise<Session<TToolCollection, TTool, TProvider>> {
175 const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});
176 const isDirectToolsPreset = routerConfig.sessionPreset === SessionPreset.DIRECT_TOOLS;
@@ -231,7 +234,10 @@ export class ToolRouter<
234 experimental: Object.keys(experimentalPayload).length > 0 ? experimentalPayload : undefined,
235 };
236
234 - const session = await this.client.toolRouter.session.create(payload);
237 + const session = await withCancellation(
238 + () => this.client.toolRouter.session.create(payload, requestOptions),
239 + requestOptions?.signal
240 + );
241
242 // Build custom tools map from the response's slug/original_slug mapping
243 // instead of computing LOCAL_ prefix client-side
@@ -282,7 +288,8 @@ export class ToolRouter<
288 */
289 async use(
290 id: string,
285 - options?: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[] }
291 + options?: { customTools?: CustomTool[]; customToolkits?: CustomToolkit[] },
292 + requestOptions?: ComposioRequestOptions
293 ): Promise<Session<TToolCollection, TTool, TProvider>> {
294 const customTools = options?.customTools;
295 const customToolkits = options?.customToolkits;
@@ -296,11 +303,16 @@ export class ToolRouter<
303 let inlineCustomToolsPayload = attachInlineCustomToolsPayload;
304
305 if (hasCustoms) {
299 - session = await this.client.toolRouter.session.attach(id, {
300 - experimental: attachInlineCustomToolsPayload,
301 - });
306 + const attachBody = { experimental: attachInlineCustomToolsPayload };
307 + session = await withCancellation(
308 + () => this.client.toolRouter.session.attach(id, attachBody, requestOptions),
309 + requestOptions?.signal
310 + );
311 } else {
303 - session = await this.client.toolRouter.session.retrieve(id);
312 + session = await withCancellation(
313 + () => this.client.toolRouter.session.retrieve(id, requestOptions),
314 + requestOptions?.signal
315 + );
316 }
317
318 const defaultCustomPreload = preloadsAllCustomTools(session.config.preload);
ts/packages/core/src/models/ToolRouterSession.ts
+73 -25
@@ -2,6 +2,9 @@ import { telemetry } from '../telemetry/Telemetry';
2 import { Composio as ComposioClient, BadRequestError } from '@composio/client';
3 import { BaseComposioProvider } from '../provider/BaseProvider';
4 import { ComposioConfig } from '../composio';
5 +import { ComposioRequestOptions } from '../types/requestOptions.types';
6 +import { withCancellation } from '../utils/cancellation';
7 +import { ComposioRequestCancelledError } from '../errors/SDKErrors';
8 import {
9 ToolRouterMCPServerConfig,
10 SessionExperimental,
@@ -149,11 +152,15 @@ export class ToolRouterSession<
152 * When custom tools are bound to the session, execution of COMPOSIO_MULTI_EXECUTE_TOOL
153 * is intercepted: local tools are executed in-process, remote tools are sent to the backend.
154 */
152 - async tools(modifiers?: SessionMetaToolOptions): Promise<ReturnType<TProvider['wrapTools']>> {
155 + async tools(
156 + modifiers?: SessionMetaToolOptions,
157 + requestOptions?: ComposioRequestOptions
158 + ): Promise<ReturnType<TProvider['wrapTools']>> {
159 const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
160 const tools = await ToolsModel.getRawToolRouterSessionTools(
161 this.sessionId,
156 - modifiers?.modifySchema ? { modifySchema: modifiers.modifySchema } : undefined
162 + modifiers?.modifySchema ? { modifySchema: modifiers.modifySchema } : undefined,
163 + requestOptions
164 );
165 const sessionTools = await this.addPreloadedCustomTools(tools, modifiers);
166 const toolBySlug = new Map(sessionTools.map(tool => [tool.slug.toUpperCase(), tool]));
@@ -346,15 +353,16 @@ export class ToolRouterSession<
353 accountType?: ConnectedAccountType;
354 aclConfigForShared?: ConnectedAccountAclConfig;
355 };
349 - }
356 + },
357 + requestOptions?: ComposioRequestOptions
358 ): Promise<ConnectionRequest> {
351 - const requestOptions = AuthorizeOptionsSchema.safeParse(options ?? {});
352 - if (!requestOptions.success) {
359 + const parsedAuthorizeOptions = AuthorizeOptionsSchema.safeParse(options ?? {});
360 + if (!parsedAuthorizeOptions.success) {
361 throw new ValidationError('Failed to parse tool router authorize options', {
354 - cause: requestOptions.error,
362 + cause: parsedAuthorizeOptions.error,
363 });
364 }
357 - const opts = requestOptions.data;
365 + const opts = parsedAuthorizeOptions.data;
366 const experimentalWire = serializeExperimentalForWire(opts.experimental);
367 const body: SessionLinkParams = {
368 toolkit,
@@ -367,8 +375,16 @@ export class ToolRouterSession<
375
376 let response;
377 try {
370 - response = await this.client.toolRouter.session.link(this.sessionId, body);
378 + response = await withCancellation(
379 + () => this.client.toolRouter.session.link(this.sessionId, body, requestOptions),
380 + requestOptions?.signal
381 + );
382 } catch (error) {
383 + // Caller-initiated cancellation must surface as the typed error,
384 + // not get remapped to a domain error below.
385 + if (error instanceof ComposioRequestCancelledError) {
386 + throw error;
387 + }
388 // The server rejects ACL on PRIVATE connections — surface that as a
389 // typed error mirroring `composio.connectedAccounts.link()`.
390 if (
@@ -393,7 +409,7 @@ export class ToolRouterSession<
409 * Query the connection state of toolkits in the session.
410 * Supports pagination and filtering by toolkit slugs.
411 */
396 - async toolkits(options?: ToolRouterToolkitsOptions) {
412 + async toolkits(options?: ToolRouterToolkitsOptions, requestOptions?: ComposioRequestOptions) {
413 const toolkitOptions = ToolRouterToolkitsOptionsSchema.safeParse(options ?? {});
414 if (!toolkitOptions.success) {
415 throw new ValidationError('Failed to parse toolkits options', {
@@ -401,13 +417,17 @@ export class ToolRouterSession<
417 });
418 }
419
404 - const result = await this.client.toolRouter.session.toolkits(this.sessionId, {
420 + const toolkitsParams = {
421 cursor: toolkitOptions.data.cursor,
422 limit: toolkitOptions.data.limit,
423 toolkits: toolkitOptions.data.toolkits,
424 is_connected: toolkitOptions.data.isConnected,
425 search: toolkitOptions.data.search,
410 - });
426 + };
427 + const result = await withCancellation(
428 + () => this.client.toolRouter.session.toolkits(this.sessionId, toolkitsParams, requestOptions),
429 + requestOptions?.signal
430 + );
431
432 const toolkitConnectedStates = result.items.map(item => {
433 const connectedState = transform(item)
@@ -448,10 +468,13 @@ export class ToolRouterSession<
468 * Search for tools by semantic use case.
469 * Returns relevant tools for the given query with schemas and guidance.
470 */
451 - async search(params: {
452 - query: string;
453 - toolkits?: string[];
454 - }): Promise<ToolRouterSessionSearchResponse> {
471 + async search(
472 + params: {
473 + query: string;
474 + toolkits?: string[];
475 + },
476 + requestOptions?: ComposioRequestOptions
477 + ): Promise<ToolRouterSessionSearchResponse> {
478 const experimental = inlineCustomToolsExperimental<SessionSearchParams.Experimental>(
479 this.inlineCustomToolsPayload
480 );
@@ -460,7 +483,10 @@ export class ToolRouterSession<
483 ...(params.toolkits?.length ? { toolkits: params.toolkits } : {}),
484 ...(experimental ? { experimental } : {}),
485 };
463 - const response = await this.client.toolRouter.session.search(this.sessionId, searchParams);
486 + const response = await withCancellation(
487 + () => this.client.toolRouter.session.search(this.sessionId, searchParams, requestOptions),
488 + requestOptions?.signal
489 + );
490 const transformed = transformSearchResponse(response);
491 return ToolRouterSessionSearchResponseSchema.parse(transformed);
492 }
@@ -481,12 +507,23 @@ export class ToolRouterSession<
507 async execute(
508 toolSlug: string,
509 arguments_?: Record<string, unknown>,
484 - options?: ToolRouterSessionExecuteOptions
510 + options?: ToolRouterSessionExecuteOptions,
511 + requestOptions?: ComposioRequestOptions
512 ): Promise<ToolRouterSessionExecuteResponse> {
513 // Check if this is a local tool (by original or final slug)
514 const entry = findCustomTool(this.customToolsMap, toolSlug);
515 if (entry) {
489 - const result = await executeCustomTool(entry, arguments_ ?? {}, this.sessionContext!);
516 + // Bail before invoking user code if the caller has already aborted.
517 + // Custom-tool execution is *cooperative*: long-running user code
518 + // won't observe later aborts unless the user wires the signal into
519 + // their own fetch/work — we pass it through via the executeCustomTool
520 + // session context so they can.
521 + if (requestOptions?.signal?.aborted) {
522 + throw new ComposioRequestCancelledError();
523 + }
524 + const result = await executeCustomTool(entry, arguments_ ?? {}, this.sessionContext!, {
525 + signal: requestOptions?.signal,
526 + });
527 return {
528 data: result.data,
529 error: result.error,
@@ -510,7 +547,10 @@ export class ToolRouterSession<
547 executeParams.experimental = experimental;
548 }
549
513 - const response = await this.client.toolRouter.session.execute(this.sessionId, executeParams);
550 + const response = await withCancellation(
551 + () => this.client.toolRouter.session.execute(this.sessionId, executeParams, requestOptions),
552 + requestOptions?.signal
553 + );
554 const transformed = transformExecuteResponse(response);
555 return ToolRouterSessionExecuteResponseSchema.parse(transformed);
556 }
@@ -523,7 +563,8 @@ export class ToolRouterSession<
563 * @returns The proxied API response with status, data, headers
564 */
565 async proxyExecute(
526 - params: SessionProxyExecuteParams
566 + params: SessionProxyExecuteParams,
567 + requestOptions?: ComposioRequestOptions
568 ): Promise<ToolRouterSessionProxyExecuteResponse> {
569 const validated = SessionProxyExecuteParamsSchema.safeParse(params);
570 if (!validated.success) {
@@ -531,9 +572,10 @@ export class ToolRouterSession<
572 }
573
574 const clientParams = transformProxyParams(validated.data);
534 - const response = await this.client.toolRouter.session.proxyExecute(
535 - this.sessionId,
536 - clientParams
575 + const response = await withCancellation(
576 + () =>
577 + this.client.toolRouter.session.proxyExecute(this.sessionId, clientParams, requestOptions),
578 + requestOptions?.signal
579 );
580
581 return {
@@ -558,10 +600,16 @@ export class ToolRouterSession<
600 * Only the fields provided will be changed; omitted fields are preserved.
601 * Mutates this session's `configVersion`, `preload`, and `warnings` in-place.
602 */
561 - async update(config: ToolRouterUpdateSessionConfig): Promise<void> {
603 + async update(
604 + config: ToolRouterUpdateSessionConfig,
605 + requestOptions?: ComposioRequestOptions
606 + ): Promise<void> {
607 const parsed = ToolRouterUpdateSessionConfigSchema.parse(config);
608 const params = transformToolRouterUpdateParams(parsed);
564 - const response = await this.client.toolRouter.session.patch(this.sessionId, params);
609 + const response = await withCancellation(
610 + () => this.client.toolRouter.session.patch(this.sessionId, params, requestOptions),
611 + requestOptions?.signal
612 + );
613 this.configVersion = response.config_version;
614 this.preload = response.config.preload;
615 this.warnings = response.warnings ?? [];
ts/packages/core/src/models/Toolkits.ts
+77 -25
@@ -22,6 +22,9 @@ import {
22 transformToolkitRetrieveCategoriesResponse,
23 transformToolkitRetrieveResponse,
24 } from '../utils/transformers/toolkits';
25 +import { ComposioRequestOptions } from '../types/requestOptions.types';
26 +import { withCancellation } from '../utils/cancellation';
27 +import { ComposioRequestCancelledError } from '../errors/SDKErrors';
28 /**
29 * Toolkits class
30 *
@@ -47,7 +50,10 @@ export class Toolkits {
50 *
51 * @private
52 */
50 - private async getToolkits(query: ToolkitListParams): Promise<ToolKitListResponse> {
53 + private async getToolkits(
54 + query: ToolkitListParams,
55 + requestOptions?: ComposioRequestOptions
56 + ): Promise<ToolKitListResponse> {
57 try {
58 const parsedQuery = ToolkitsListParamsSchema.safeParse(query);
59 if (!parsedQuery.success) {
@@ -55,16 +61,23 @@ export class Toolkits {
61 cause: parsedQuery.error,
62 });
63 }
58 - const result = await this.client.toolkits.list({
64 + const listParams = {
65 category: parsedQuery.data.category,
66 managed_by: parsedQuery.data.managedBy,
67 sort_by: parsedQuery.data.sortBy,
68 cursor: parsedQuery.data.cursor,
69 limit: parsedQuery.data.limit,
64 - });
70 + };
71 + const result = await withCancellation(
72 + () => this.client.toolkits.list(listParams, requestOptions),
73 + requestOptions?.signal
74 + );
75
76 return transformToolkitListResponse(result);
77 } catch (error) {
78 + if (error instanceof ComposioRequestCancelledError) {
79 + throw error;
80 + }
81 throw new ComposioToolkitFetchError('Failed to fetch toolkits', {
82 cause: error,
83 });
@@ -83,11 +96,20 @@ export class Toolkits {
96 *
97 * @private
98 */
86 - protected async getToolkitBySlug(slug: string): Promise<ToolkitRetrieveResponse> {
99 + protected async getToolkitBySlug(
100 + slug: string,
101 + requestOptions?: ComposioRequestOptions
102 + ): Promise<ToolkitRetrieveResponse> {
103 try {
88 - const result = await this.client.toolkits.retrieve(slug);
104 + const result = await withCancellation(
105 + () => this.client.toolkits.retrieve(slug, undefined, requestOptions),
106 + requestOptions?.signal
107 + );
108 return transformToolkitRetrieveResponse(result);
109 } catch (error) {
110 + if (error instanceof ComposioRequestCancelledError) {
111 + throw error;
112 + }
113 if (error instanceof APIError && (error.status === 404 || error.status === 400)) {
114 throw new ComposioToolkitNotFoundError(`Toolkit with slug ${slug} not found`, {
115 meta: {
@@ -120,7 +142,10 @@ export class Toolkits {
142 * console.log(githubToolkit.authConfigDetails); // Authentication configuration details
143 * ```
144 */
123 - async get(slug: string): Promise<ToolkitRetrieveResponse>;
145 + async get(
146 + slug: string,
147 + requestOptions?: ComposioRequestOptions
148 + ): Promise<ToolkitRetrieveResponse>;
149
150 /**
151 * Retrieves a list of toolkits based on the provided query parameters.
@@ -144,21 +169,26 @@ export class Toolkits {
169 * });
170 * ```
171 */
147 - async get(query?: ToolkitListParams): Promise<ToolKitListResponse>;
172 + async get(
173 + query?: ToolkitListParams,
174 + requestOptions?: ComposioRequestOptions
175 + ): Promise<ToolKitListResponse>;
176
177 /**
178 * Implementation method that handles both overloads for retrieving toolkits.
179 *
180 * @param {string | ToolkitListParams} arg - Either a toolkit slug or query parameters
181 + * @param {ComposioRequestOptions} [requestOptions] - Per-request cancellation/timeout options
182 * @returns {Promise<ToolkitRetrieveResponse | ToolKitListResponse>} The toolkit or list of toolkits
183 */
184 async get(
156 - arg?: string | ToolkitListParams
185 + arg?: string | ToolkitListParams,
186 + requestOptions?: ComposioRequestOptions
187 ): Promise<ToolkitRetrieveResponse | ToolKitListResponse> {
188 if (typeof arg === 'string') {
159 - return this.getToolkitBySlug(arg);
189 + return this.getToolkitBySlug(arg, requestOptions);
190 }
161 - return this.getToolkits(arg ?? {});
191 + return this.getToolkits(arg ?? {}, requestOptions);
192 }
193
194 private async getAuthConfigFields(
@@ -277,8 +307,13 @@ export class Toolkits {
307 * console.log(categories.items); // Array of category objects
308 * ```
309 */
280 - async listCategories(): Promise<ToolkitRetrieveCategoriesResponse> {
281 - const result = await this.client.toolkits.retrieveCategories();
310 + async listCategories(
311 + requestOptions?: ComposioRequestOptions
312 + ): Promise<ToolkitRetrieveCategoriesResponse> {
313 + const result = await withCancellation(
314 + () => this.client.toolkits.retrieveCategories(requestOptions),
315 + requestOptions?.signal
316 + );
317 return transformToolkitRetrieveCategoriesResponse(result);
318 }
319
@@ -298,16 +333,24 @@ export class Toolkits {
333 async authorize(
334 userId: string,
335 toolkitSlug: string,
301 - authConfigId?: string
336 + authConfigId?: string,
337 + requestOptions?: ComposioRequestOptions
338 ): Promise<ConnectionRequest> {
303 - const toolkit = await this.getToolkitBySlug(toolkitSlug);
339 + // High-level helper that fans out to 3-4 network calls (toolkit retrieve,
340 + // optional authConfigs list, optional authConfigs create, then
341 + // connectedAccounts.initiate). Forward the caller's signal to every
342 + // underlying call so the whole composite is cancellable as a single unit.
343 + const toolkit = await this.getToolkitBySlug(toolkitSlug, requestOptions);
344 const composioAuthConfig = new AuthConfigs(this.client);
345 let authConfigIdToUse: string | undefined = authConfigId;
346
347 if (!authConfigIdToUse) {
308 - const authConfig = await composioAuthConfig.list({
309 - toolkit: toolkitSlug,
310 - });
348 + const authConfig = await composioAuthConfig.list(
349 + {
350 + toolkit: toolkitSlug,
351 + },
352 + requestOptions
353 + );
354 // pick the first auth config if none is passed
355 authConfigIdToUse = authConfig.items[0]?.id;
356 }
@@ -317,10 +360,14 @@ export class Toolkits {
360 // create authConfig using composioManagedAuthSchemes
361 if (toolkit.authConfigDetails && toolkit.authConfigDetails.length > 0) {
362 try {
320 - const authConfig = await composioAuthConfig.create(toolkitSlug, {
321 - type: 'use_composio_managed_auth',
322 - name: `${toolkit.name} Auth Config`,
323 - });
363 + const authConfig = await composioAuthConfig.create(
364 + toolkitSlug,
365 + {
366 + type: 'use_composio_managed_auth',
367 + name: `${toolkit.name} Auth Config`,
368 + },
369 + requestOptions
370 + );
371 authConfigIdToUse = authConfig.id;
372 } catch (error) {
373 if (error instanceof ComposioClient.APIError && error.status === 400) {
@@ -352,9 +399,14 @@ export class Toolkits {
399 }
400 // create the auth config
401 const composioConnectedAccount = new ConnectedAccounts(this.client);
355 - return await composioConnectedAccount.initiate(userId, authConfigIdToUse, {
356 - // in this magic function we allow multiple connected accounts per user for an auth config
357 - allowMultiple: true,
358 - });
402 + return await composioConnectedAccount.initiate(
403 + userId,
404 + authConfigIdToUse,
405 + {
406 + // in this magic function we allow multiple connected accounts per user for an auth config
407 + allowMultiple: true,
408 + },
409 + requestOptions
410 + );
411 }
412 }
ts/packages/core/src/models/Tools.ts
+155 -71
@@ -55,6 +55,9 @@ import type { SessionExecuteParams } from '@composio/client/resources/tool-route
55 import { CONFIG_DEFAULTS } from '../utils/config-defaults';
56 import { resolveEffectiveUploadAllowlist } from '../utils/fileDirs';
57 import { schemaHasFileUploadable } from '../utils/modifiers/FileToolModifier.utils.neutral';
58 +import { ComposioRequestOptions } from '../types/requestOptions.types';
59 +import { withCancellation } from '../utils/cancellation';
60 +import { ComposioRequestCancelledError } from '../errors/SDKErrors';
61
62 const TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT = 500;
63
@@ -233,8 +236,12 @@ export class Tools<
236 toolkitSlug: string;
237 params: ToolExecuteParams;
238 },
236 - modifiers?: ExecuteToolModifiers
239 + modifiers?: ExecuteToolModifiers,
240 + requestOptions?: ComposioRequestOptions
241 ): Promise<ToolExecuteParams> {
242 + if (requestOptions?.signal?.aborted) {
243 + throw new ComposioRequestCancelledError();
244 + }
245 let modifiedParams = params;
246 // if auto upload download files is enabled, upload the files to the Composio API
247 if (this.autoUploadDownloadFiles) {
@@ -246,7 +253,11 @@ export class Tools<
253 toolSlug,
254 toolkitSlug,
255 params: modifiedParams,
256 + signal: requestOptions?.signal,
257 });
258 + if (requestOptions?.signal?.aborted) {
259 + throw new ComposioRequestCancelledError();
260 + }
261 } else if (
262 schemaHasFileUploadable(tool.inputParameters) &&
263 !this.warnedAutoUploadDisabledForTool.has(toolSlug)
@@ -276,6 +287,9 @@ export class Tools<
287 toolkitSlug,
288 params: modifiedParams,
289 });
290 + if (requestOptions?.signal?.aborted) {
291 + throw new ComposioRequestCancelledError();
292 + }
293 } else {
294 throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
295 }
@@ -302,8 +316,17 @@ export class Tools<
316 toolkitSlug: string;
317 result: ToolExecuteResponse;
318 },
305 - modifier?: afterExecuteModifier
319 + modifier?: afterExecuteModifier,
320 + requestOptions?: ComposioRequestOptions
321 ): Promise<ToolExecuteResponse> {
322 + // The tool already executed and may have mutated external state, so a late
323 + // abort does NOT short-circuit post-processing: skipping the caller's
324 + // afterExecute modifier here would leave a half-finished pipeline that
325 + // still looks like success-shaped data. Once the remote call has committed
326 + // we run file download + afterExecute to completion. The signal is still
327 + // forwarded to the download so a stuck transfer degrades gracefully
328 + // (file_downloaded: false) rather than blocking, but it never skips
329 + // afterExecute.
330 let modifiedResult = result;
331 // if auto upload download files is enabled, download the files from the Composio API
332 if (this.autoUploadDownloadFiles) {
@@ -312,6 +335,7 @@ export class Tools<
335 toolSlug,
336 toolkitSlug,
337 result: modifiedResult,
338 + signal: requestOptions?.signal,
339 });
340 }
341 // apply the after execute modifiers
@@ -391,7 +415,8 @@ export class Tools<
415 */
416 async getRawComposioTools(
417 query: ToolListParams,
394 - options?: SchemaModifierOptions
418 + options?: SchemaModifierOptions,
419 + requestOptions?: ComposioRequestOptions
420 ): Promise<ToolList> {
421 if ('tools' in query && 'toolkits' in query) {
422 throw new ValidationError(
@@ -456,7 +481,10 @@ export class Tools<
481
482 logger.debug(`Fetching tools with filters: ${JSON.stringify(filters, null, 2)}`);
483
459 - const tools = await this.client.tools.list(filters);
484 + const tools = await withCancellation(
485 + () => this.client.tools.list(filters, requestOptions),
486 + requestOptions?.signal
487 + );
488
489 if (!tools) {
490 return [];
@@ -503,16 +531,21 @@ export class Tools<
531 */
532 async getRawToolRouterSessionTools(
533 sessionId: string,
506 - options?: SchemaModifierOptions
534 + options?: SchemaModifierOptions,
535 + requestOptions?: ComposioRequestOptions
536 ): Promise<ToolList> {
537 const tools: ToolList = [];
538 let cursor: string | null | undefined;
539
540 do {
512 - const response = await this.client.toolRouter.session.tools(sessionId, {
541 + const sessionToolsParams = {
542 limit: TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT,
543 ...(cursor ? { cursor } : {}),
515 - });
544 + };
545 + const response = await withCancellation(
546 + () => this.client.toolRouter.session.tools(sessionId, sessionToolsParams, requestOptions),
547 + requestOptions?.signal
548 + );
549 tools.push(...response.items.map(tool => this.transformToolCases(tool)));
550 cursor = response.next_cursor;
551 } while (cursor);
@@ -588,7 +621,11 @@ export class Tools<
621 * });
622 * ```
623 */
591 - async getRawComposioToolBySlug(slug: string, options?: ToolRetrievalOptions): Promise<Tool> {
624 + async getRawComposioToolBySlug(
625 + slug: string,
626 + options?: ToolRetrievalOptions,
627 + requestOptions?: ComposioRequestOptions
628 + ): Promise<Tool> {
629 let tool: ToolRetrieveResponse;
630 try {
631 // Build API call parameters based on version source
@@ -596,8 +633,14 @@ export class Tools<
633 ? { version: options.version } // Explicit version → use 'version' param
634 : { toolkit_versions: this.toolkitVersions }; // SDK config → use 'toolkit_versions' param
635
599 - tool = await this.client.tools.retrieve(slug, retrieveParams);
636 + tool = await withCancellation(
637 + () => this.client.tools.retrieve(slug, retrieveParams, requestOptions),
638 + requestOptions?.signal
639 + );
640 } catch (error) {
641 + if (error instanceof ComposioRequestCancelledError) {
642 + throw error;
643 + }
644 throw new ComposioToolNotFoundError(`Unable to retrieve tool with slug ${slug}`, {
645 cause: error,
646 });
@@ -627,7 +670,7 @@ export class Tools<
670 *
671 * @param {string} userId - The user id to get the tools for
672 * @param {ToolListParams} filters - The filters to apply when fetching tools
630 - * @param {ProviderOptions<TProvider>} [options] - Optional provider options including modifiers
673 + * @param {ProviderOptions<TProvider> & ComposioRequestOptions} [options] - Provider options, modifiers, and/or AbortSignal
674 * @returns {Promise<ReturnType<T['wrapTools']>>} The wrapped tools collection
675 *
676 * @example
@@ -638,28 +681,16 @@ export class Tools<
681 * limit: 10
682 * });
683 *
641 - * // Get tools with search
642 - * const searchTools = await composio.tools.get('default', {
643 - * search: 'user',
644 - * limit: 10
645 - * });
646 - *
647 - * // Get a specific tool by slug
648 - * const hackerNewsUserTool = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
649 - *
650 - * // Get a tool with schema modifications
651 - * const tool = await composio.tools.get('default', 'GITHUB_GET_REPOS', {
652 - * modifySchema: (toolSlug, toolkitSlug, schema) => {
653 - * // Customize the tool schema
654 - * return {...schema, description: 'Custom description'};
655 - * }
656 - * });
684 + * // Timeout a slow search after 5s
685 + * const tools = await composio.tools.get('default', {
686 + * search: 'send email',
687 + * }, { signal: AbortSignal.timeout(5_000) });
688 * ```
689 */
690 async get<T extends TProvider>(
691 userId: string,
692 filters: ToolListParams,
662 - options?: ProviderOptions<TProvider>
693 + options?: ProviderOptions<TProvider> & ComposioRequestOptions
694 ): Promise<ReturnType<T['wrapTools']>>;
695
696 /**
@@ -668,7 +699,7 @@ export class Tools<
699 *
700 * @param {string} userId - The user id to get the tool for
701 * @param {string} slug - The slug of the tool to fetch
671 - * @param {ProviderOptions<TProvider>} [options] - Optional provider options including modifiers
702 + * @param {ProviderOptions<TProvider> & ComposioRequestOptions} [options] - Optional provider options including modifiers and signal
703 * @returns {Promise<ReturnType<T['wrapTools']>>} The wrapped tool
704 *
705 * @example
@@ -683,51 +714,56 @@ export class Tools<
714 * return {...schema, description: 'Custom description'};
715 * }
716 * });
717 + *
718 + * // Timeout after 5s
719 + * const tools = await composio.tools.get('user_1', { search: 'email' }, {
720 + * signal: AbortSignal.timeout(5_000)
721 + * });
722 * ```
723 */
724 async get<T extends TProvider>(
725 userId: string,
726 slug: string,
691 - options?: ProviderOptions<TProvider>
727 + options?: ProviderOptions<TProvider> & ComposioRequestOptions
728 ): Promise<ReturnType<T['wrapTools']>>;
729
694 - /**
695 - * Get a tool or list of tools based on the provided arguments.
696 - * This is an implementation method that handles all overloads.
697 - *
698 - * @param {string} userId - The user id to get the tool(s) for
699 - * @param {ToolListParams | string} arg2 - Either a slug string or filters object
700 - * @param {ProviderOptions<TProvider> | ToolkitVersion} [arg3] - Optional provider options or version string
701 - * @param {ProviderOptions<TProvider>} [arg4] - Optional provider options (when arg3 is version)
702 - * @returns {Promise<TToolCollection>} The tool collection
703 - */
730 async get(
731 userId: string,
732 arg2: ToolListParams | string,
707 - arg3?: ProviderOptions<TProvider>
733 + arg3?: ProviderOptions<TProvider> & ComposioRequestOptions
734 ): Promise<TToolCollection> {
709 - // Handle the two-parameter overloads
710 - const options = arg3 as ProviderOptions<TProvider>;
735 + const options = arg3;
736 + const requestOptions: ComposioRequestOptions | undefined =
737 + options?.signal != null ? { signal: options.signal } : undefined;
738 + // Strip signal so it isn't captured in the provider execution closure —
739 + // an expired AbortSignal.timeout() would poison every future tool call.
740 + const { signal: _, ...modifiers } = options ?? {};
741
712 - // if the second argument is a string, get a single tool
742 if (typeof arg2 === 'string') {
714 - const tool = await this.getRawComposioToolBySlug(arg2, {
715 - modifySchema: options?.modifySchema as TransformToolSchemaModifier,
716 - });
743 + const tool = await this.getRawComposioToolBySlug(
744 + arg2,
745 + {
746 + modifySchema: options?.modifySchema as TransformToolSchemaModifier,
747 + },
748 + requestOptions
749 + );
750 return this.wrapToolsForProvider(
751 userId,
752 [tool],
720 - options as ExecuteToolModifiers
753 + modifiers as ExecuteToolModifiers
754 ) as TToolCollection;
755 } else {
723 - // if the second argument is an object, get a list of tools
724 - const tools = await this.getRawComposioTools(arg2, {
725 - modifySchema: options?.modifySchema as TransformToolSchemaModifier,
726 - });
756 + const tools = await this.getRawComposioTools(
757 + arg2,
758 + {
759 + modifySchema: options?.modifySchema as TransformToolSchemaModifier,
760 + },
761 + requestOptions
762 + );
763 return this.wrapToolsForProvider(
764 userId,
765 tools,
730 - options as ExecuteToolModifiers
766 + modifiers as ExecuteToolModifiers
767 ) as TToolCollection;
768 }
769 }
@@ -851,7 +887,8 @@ export class Tools<
887 */
888 private async executeComposioTool(
889 tool: Tool,
854 - body: ToolExecuteParams
890 + body: ToolExecuteParams,
891 + requestOptions?: ComposioRequestOptions
892 ): Promise<ToolExecuteResponse> {
893 const toolkitVersion =
894 body.version ?? getToolkitVersion(tool.toolkit?.slug ?? 'unknown', this.toolkitVersions);
@@ -860,7 +897,7 @@ export class Tools<
897 throw new ComposioToolVersionRequiredError();
898 }
899 try {
863 - const result = await this.client.tools.execute(tool.slug, {
900 + const executeBody: ComposioToolExecuteParams = {
901 allow_tracing: body.allowTracing,
902 connected_account_id: body.connectedAccountId,
903 custom_auth_params: body.customAuthParams
@@ -883,10 +920,17 @@ export class Tools<
920 user_id: body.userId,
921 version: toolkitVersion,
922 text: body.text,
886 - });
923 + };
924 + const result = await withCancellation(
925 + () => this.client.tools.execute(tool.slug, executeBody, requestOptions),
926 + requestOptions?.signal
927 + );
928 // transform the response to the ToolExecuteResponse format
929 return this.transformToolExecuteResponse(result);
930 } catch (error) {
931 + if (error instanceof ComposioRequestCancelledError) {
932 + throw error;
933 + }
934 const toolError = handleToolExecutionError(tool.slug, error as Error);
935 throw toolError;
936 }
@@ -962,20 +1006,37 @@ export class Tools<
1006 * }
1007 * });
1008 * ```
1009 + *
1010 + * @example Execute with timeout
1011 + * ```typescript
1012 + * const result = await composio.tools.execute('HACKERNEWS_GET_FRONTPAGE', {
1013 + * userId: 'default',
1014 + * arguments: {},
1015 + * dangerouslySkipVersionCheck: true,
1016 + * }, { signal: AbortSignal.timeout(5_000) });
1017 + * ```
1018 */
1019 async execute(
1020 slug: string,
1021 body: ToolExecuteParams,
969 - modifiers?: ExecuteToolModifiers
1022 + options?: ExecuteToolModifiers & ComposioRequestOptions
1023 ): Promise<ToolExecuteResponse> {
1024 const executeParams = ToolExecuteParamsSchema.safeParse(body);
1025 if (!executeParams.success) {
1026 throw new ValidationError('Invalid tool execute parameters', { cause: executeParams.error });
1027 }
1028
976 - const tool = await this.getRawComposioToolBySlug(slug, {
977 - version: body.version,
978 - });
1029 + const requestOptions: ComposioRequestOptions | undefined =
1030 + options?.signal != null ? { signal: options.signal } : undefined;
1031 + const { signal: _, ...modifiers } = options ?? {};
1032 +
1033 + const tool = await this.getRawComposioToolBySlug(
1034 + slug,
1035 + {
1036 + version: body.version,
1037 + },
1038 + requestOptions
1039 + );
1040 const toolkitSlug = tool.toolkit?.slug ?? 'unknown';
1041
1042 // Apply before execute modifiers
@@ -986,10 +1047,11 @@ export class Tools<
1047 toolkitSlug,
1048 params: executeParams.data,
1049 },
989 - modifiers
1050 + modifiers as ExecuteToolModifiers,
1051 + requestOptions
1052 );
1053
992 - let result = await this.executeComposioTool(tool, params);
1054 + let result = await this.executeComposioTool(tool, params, requestOptions);
1055
1056 // Apply after execute modifiers
1057 result = await this.applyAfterExecuteModifiers(
@@ -999,7 +1061,8 @@ export class Tools<
1061 toolkitSlug,
1062 result,
1063 },
1002 - modifiers?.afterExecute
1064 + (modifiers as ExecuteToolModifiers).afterExecute,
1065 + requestOptions
1066 );
1067
1068 return result;
@@ -1021,7 +1084,8 @@ export class Tools<
1084 body: ToolExecuteMetaParams,
1085 modifiers?: SessionExecuteMetaModifiers,
1086 tool?: Tool,
1024 - options?: ToolRouterSessionExecuteOptions
1087 + options?: ToolRouterSessionExecuteOptions,
1088 + requestOptions?: ComposioRequestOptions
1089 ): Promise<ToolExecuteResponse> {
1090 const executeParams = ToolExecuteMetaParamsSchema.safeParse(body);
1091 if (!executeParams.success) {
@@ -1053,7 +1117,10 @@ export class Tools<
1117 executePayload.experimental = options.experimental;
1118 }
1119
1056 - const response = await this.client.toolRouter.session.execute(body.sessionId, executePayload);
1120 + const response = await withCancellation(
1121 + () => this.client.toolRouter.session.execute(body.sessionId, executePayload, requestOptions),
1122 + requestOptions?.signal
1123 + );
1124
1125 // Prepare the result
1126 let result: ToolExecuteResponse = {
@@ -1090,8 +1157,11 @@ export class Tools<
1157 * console.log(toolsEnum.items);
1158 * ```
1159 */
1093 - async getToolsEnum(): Promise<ToolRetrieveEnumResponse> {
1094 - return this.client.tools.retrieveEnum();
1160 + async getToolsEnum(requestOptions?: ComposioRequestOptions): Promise<ToolRetrieveEnumResponse> {
1161 + return withCancellation(
1162 + () => this.client.tools.retrieveEnum(requestOptions),
1163 + requestOptions?.signal
1164 + );
1165 }
1166
1167 /**
@@ -1112,8 +1182,15 @@ export class Tools<
1182 * console.log(inputParams.schema);
1183 * ```
1184 */
1115 - async getInput(slug: string, body: ToolGetInputParams): Promise<ToolGetInputResponse> {
1116 - return this.client.tools.getInput(slug, body);
1185 + async getInput(
1186 + slug: string,
1187 + body: ToolGetInputParams,
1188 + requestOptions?: ComposioRequestOptions
1189 + ): Promise<ToolGetInputResponse> {
1190 + return withCancellation(
1191 + () => this.client.tools.getInput(slug, body, requestOptions),
1192 + requestOptions?.signal
1193 + );
1194 }
1195
1196 /**
@@ -1139,7 +1216,10 @@ export class Tools<
1216 * console.log(response.data);
1217 * ```
1218 */
1142 - async proxyExecute(body: ToolProxyParams): Promise<ToolProxyResponse> {
1219 + async proxyExecute(
1220 + body: ToolProxyParams,
1221 + requestOptions?: ComposioRequestOptions
1222 + ): Promise<ToolProxyResponse> {
1223 const toolProxyParams = ToolProxyParamsSchema.safeParse(body);
1224 if (!toolProxyParams.success) {
1225 throw new ValidationError('Invalid tool proxy parameters', { cause: toolProxyParams.error });
@@ -1162,7 +1242,7 @@ export class Tools<
1242 );
1243 }
1244
1165 - return this.client.tools.proxy({
1245 + const proxyBody = {
1246 endpoint: toolProxyParams.data.endpoint,
1247 method: toolProxyParams.data.method,
1248 body: toolProxyParams.data.body,
@@ -1177,6 +1257,10 @@ export class Tools<
1257 */
1258 // @ts-ignore
1259 custom_connection_data: toolProxyParams.data.customConnectionData,
1180 - });
1260 + } as ComposioToolProxyParams;
1261 + return withCancellation(
1262 + () => this.client.tools.proxy(proxyBody, requestOptions),
1263 + requestOptions?.signal
1264 + );
1265 }
1266 }
ts/packages/core/src/models/Triggers.ts
+84 -39
@@ -53,6 +53,8 @@ import { ComposioConfig } from '../composio';
53 import { BaseComposioProvider } from '../provider/BaseProvider';
54 import { hmacSha256Base64, timingSafeEqual } from '../utils/crypto';
55 import { CONFIG_DEFAULTS } from '../utils/config-defaults';
56 +import { ComposioRequestOptions } from '../types/requestOptions.types';
57 +import { withCancellation } from '../utils/cancellation';
58
59 /**
60 * Safely converts a value to a string, returning the default if the value is null, undefined, or empty.
@@ -102,7 +104,8 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
104 * ```
105 */
106 async listActive(
105 - query?: TriggerInstanceListActiveParams
107 + query?: TriggerInstanceListActiveParams,
108 + requestOptions?: ComposioRequestOptions
109 ): Promise<TriggerInstanceListActiveResponse> {
110 // Validate the parameters if provided
111
@@ -114,18 +117,20 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
117 });
118 }
119
117 - const result = await this.client.triggerInstances.listActive(
118 - query
119 - ? {
120 - auth_config_ids: parsedParams.data.authConfigIds,
121 - connected_account_ids: parsedParams.data.connectedAccountIds,
122 - cursor: parsedParams.data.cursor,
123 - limit: parsedParams.data.limit,
124 - show_disabled: parsedParams.data.showDisabled,
125 - trigger_ids: parsedParams.data.triggerIds,
126 - trigger_names: parsedParams.data.triggerNames,
127 - }
128 - : undefined
120 + const listParams = query
121 + ? {
122 + auth_config_ids: parsedParams.data.authConfigIds,
123 + connected_account_ids: parsedParams.data.connectedAccountIds,
124 + cursor: parsedParams.data.cursor,
125 + limit: parsedParams.data.limit,
126 + show_disabled: parsedParams.data.showDisabled,
127 + trigger_ids: parsedParams.data.triggerIds,
128 + trigger_names: parsedParams.data.triggerNames,
129 + }
130 + : undefined;
131 + const result = await withCancellation(
132 + () => this.client.triggerInstances.listActive(listParams, requestOptions),
133 + requestOptions?.signal
134 );
135 return transformTriggerInstanceListActiveResponse(result);
136 }
@@ -142,7 +147,8 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
147 async create(
148 userId: string,
149 slug: string,
145 - body?: TriggerInstanceUpsertParams
150 + body?: TriggerInstanceUpsertParams,
151 + requestOptions?: ComposioRequestOptions
152 ): Promise<TriggerInstanceUpsertResponse> {
153 const parsedBody = TriggerInstanceUpsertParamsSchema.safeParse(body ?? {});
154
@@ -156,7 +162,7 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
162 let triggerType: TriggersTypeRetrieveResponse;
163 let toolkitSlug: string;
164 try {
159 - triggerType = await this.getType(slug);
165 + triggerType = await this.getType(slug, requestOptions);
166 toolkitSlug = triggerType.toolkit.slug;
167 } catch (error) {
168 // for some reason, the triggers types list endpoint returns 400 for invalid user ids
@@ -178,10 +184,14 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
184 let connectedAccountId: string | undefined = body?.connectedAccountId;
185
186 try {
181 - const { items: connectedAccounts } = await this.client.connectedAccounts.list({
187 + const connectedAccountListParams = {
188 user_ids: [userId],
189 toolkit_slugs: [toolkitSlug],
184 - });
190 + };
191 + const { items: connectedAccounts } = await withCancellation(
192 + () => this.client.connectedAccounts.list(connectedAccountListParams, requestOptions),
193 + requestOptions?.signal
194 + );
195
196 if (connectedAccounts.length === 0) {
197 throw new ComposioConnectedAccountNotFoundError(
@@ -242,8 +252,10 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
252 toolkit_versions: this.toolkitVersions,
253 user_id: userId,
254 };
245 -
246 - const result = await this.client.triggerInstances.upsert(slug, upsertParams);
255 + const result = await withCancellation(
256 + () => this.client.triggerInstances.upsert(slug, upsertParams, requestOptions),
257 + requestOptions?.signal
258 + );
259
260 return {
261 triggerId: result.trigger_id,
@@ -259,9 +271,13 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
271 */
272 async update(
273 triggerId: string,
262 - body: TriggerInstanceManageUpdateParams
274 + body: TriggerInstanceManageUpdateParams,
275 + requestOptions?: ComposioRequestOptions
276 ): Promise<TriggerInstanceManageUpdateResponse> {
264 - return this.client.triggerInstances.manage.update(triggerId, body);
277 + return withCancellation(
278 + () => this.client.triggerInstances.manage.update(triggerId, body, requestOptions),
279 + requestOptions?.signal
280 + );
281 }
282
283 /**
@@ -270,8 +286,14 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
286 * @param {string} triggerId - The slug of the trigger instance
287 * @returns
288 */
273 - async delete(triggerId: string): Promise<TriggerInstanceManageDeleteResponse> {
274 - const result = await this.client.triggerInstances.manage.delete(triggerId);
289 + async delete(
290 + triggerId: string,
291 + requestOptions?: ComposioRequestOptions
292 + ): Promise<TriggerInstanceManageDeleteResponse> {
293 + const result = await withCancellation(
294 + () => this.client.triggerInstances.manage.delete(triggerId, requestOptions),
295 + requestOptions?.signal
296 + );
297 return {
298 triggerId: result.trigger_id,
299 };
@@ -283,10 +305,12 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
305 * @param {string} triggerId - The id of the trigger instance
306 * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
307 */
286 - async disable(triggerId: string) {
287 - return this.client.triggerInstances.manage.update(triggerId, {
288 - status: 'disable',
289 - });
308 + async disable(triggerId: string, requestOptions?: ComposioRequestOptions) {
309 + const body = { status: 'disable' as const };
310 + return withCancellation(
311 + () => this.client.triggerInstances.manage.update(triggerId, body, requestOptions),
312 + requestOptions?.signal
313 + );
314 }
315
316 /**
@@ -295,10 +319,12 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
319 * @param {string} triggerId - The id of the trigger instance
320 * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
321 */
298 - async enable(triggerId: string) {
299 - return this.client.triggerInstances.manage.update(triggerId, {
300 - status: 'enable',
301 - });
322 + async enable(triggerId: string, requestOptions?: ComposioRequestOptions) {
323 + const body = { status: 'enable' as const };
324 + return withCancellation(
325 + () => this.client.triggerInstances.manage.update(triggerId, body, requestOptions),
326 + requestOptions?.signal
327 + );
328 }
329
330 /**
@@ -311,17 +337,24 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
337 * @param {RequestOptions} options - Request options
338 * @returns {Promise<TriggersTypeListResponse>} The list of trigger types
339 */
314 - async listTypes(query?: TriggersTypeListParams): Promise<TriggersTypeListResponse> {
340 + async listTypes(
341 + query?: TriggersTypeListParams,
342 + requestOptions?: ComposioRequestOptions
343 + ): Promise<TriggersTypeListResponse> {
344 const parsedQuery = transform(query ?? {})
345 .with(TriggersTypeListParamsSchema)
346 .using(raw => raw);
347
319 - const result = await this.client.triggersTypes.list({
348 + const listParams = {
349 cursor: parsedQuery.cursor,
350 limit: parsedQuery.limit,
351 toolkit_slugs: parsedQuery.toolkits,
352 toolkit_versions: this.toolkitVersions,
324 - });
353 + };
354 + const result = await withCancellation(
355 + () => this.client.triggersTypes.list(listParams, requestOptions),
356 + requestOptions?.signal
357 + );
358
359 return transformTriggerTypeListResponse(result);
360 }
@@ -333,11 +366,18 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
366 * @param {string} slug - The slug of the trigger type
367 * @returns {Promise<TriggersTypeRetrieveResponse>} The trigger type object
368 */
336 - async getType(slug: string): Promise<TriggersTypeRetrieveResponse> {
337 - const result = await this.client.triggersTypes.retrieve(slug, {
369 + async getType(
370 + slug: string,
371 + requestOptions?: ComposioRequestOptions
372 + ): Promise<TriggersTypeRetrieveResponse> {
373 + const retrieveParams = {
374 // if the version is provided override the global version
375 toolkit_versions: this.toolkitVersions,
340 - });
376 + };
377 + const result = await withCancellation(
378 + () => this.client.triggersTypes.retrieve(slug, retrieveParams, requestOptions),
379 + requestOptions?.signal
380 + );
381 return transformTriggerTypeRetrieveResponse(result);
382 }
383
@@ -347,8 +387,13 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
387 * This method is used by the CLI where filters are not required.
388 * @returns
389 */
350 - async listEnum(): Promise<TriggersTypeRetrieveEnumResponse> {
351 - return this.client.triggersTypes.retrieveEnum();
390 + async listEnum(
391 + requestOptions?: ComposioRequestOptions
392 + ): Promise<TriggersTypeRetrieveEnumResponse> {
393 + return withCancellation(
394 + () => this.client.triggersTypes.retrieveEnum(requestOptions),
395 + requestOptions?.signal
396 + );
397 }
398
399 /**
ts/packages/core/src/models/customToolExecution.ts
+25 -3
@@ -9,6 +9,7 @@ import type {
9 } from '../types/customTool.types';
10 import type { ToolExecuteResponse } from '../types/tool.types';
11 import { ValidationError } from '../errors';
12 +import { ComposioRequestCancelledError, isRequestAbortError } from '../errors/SDKErrors';
13
14 /**
15 * Find a custom tool entry by slug.
@@ -62,10 +63,15 @@ export function assertUnambiguousCustomToolSlug(
63 export async function executeCustomTool(
64 entry: CustomToolsMapEntry,
65 arguments_: Record<string, unknown>,
65 - sessionContext: SessionContext
66 + sessionContext: SessionContext,
67 + options?: { signal?: AbortSignal }
68 ): Promise<ToolExecuteResponse> {
69 const { handle } = entry;
70
71 + if (options?.signal?.aborted) {
72 + throw new ComposioRequestCancelledError();
73 + }
74 +
75 // Validate and transform input using the original Zod schema.
76 // This applies defaults, coercions, and transforms (e.g. z.string().default('all')).
77 const parsed = handle.inputParams.safeParse(arguments_);
@@ -76,16 +82,32 @@ export async function executeCustomTool(
82 successful: false,
83 };
84 }
85 + if (options?.signal?.aborted) {
86 + throw new ComposioRequestCancelledError();
87 + }
88
89 try {
81 - // User's execute returns data directly — we wrap into { data, error, successful }
82 - const data = await handle.execute(parsed.data, sessionContext);
90 + // Object.create preserves prototype methods (execute, proxyExecute) that spread would drop
91 + const ctxWithSignal: SessionContext = options?.signal
92 + ? Object.assign(Object.create(sessionContext as object) as SessionContext, {
93 + signal: options.signal,
94 + })
95 + : sessionContext;
96 + const data = await handle.execute(parsed.data, ctxWithSignal);
97 return {
98 data: data ?? {},
99 error: null,
100 successful: true,
101 };
102 } catch (err: unknown) {
103 + if (err instanceof ComposioRequestCancelledError) {
104 + throw err;
105 + }
106 + if (options?.signal?.aborted && isRequestAbortError(err)) {
107 + throw new ComposioRequestCancelledError(undefined, {
108 + cause: err instanceof Error ? err : undefined,
109 + });
110 + }
111 const message = err instanceof Error ? err.message : String(err);
112 return {
113 data: {},
ts/packages/core/src/types/customTool.types.ts
+8
@@ -35,6 +35,14 @@ export interface SessionContext {
35 ): Promise<ToolRouterSessionExecuteResponse>;
36 /** Proxy API calls through Composio's auth layer (resolved from session toolkit). */
37 proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse>;
38 + /**
39 + * Caller-supplied AbortSignal forwarded from `session.execute(..., { signal })`.
40 + * Custom-tool execution is cooperative: long-running user code that respects
41 + * this signal (e.g. by passing it into `fetch`) can abort mid-execution and
42 + * surface as `ComposioRequestCancelledError`. Undefined when the caller did
43 + * not pass `requestOptions`.
44 + */
45 + readonly signal?: AbortSignal;
46 }
47
48 /**
ts/packages/core/src/types/requestOptions.types.ts new
+62
@@ -0,0 +1,62 @@
1 +import type ComposioClient from '@composio/client';
2 +
3 +/**
4 + * Per-request transport options for cancelling an SDK call.
5 + *
6 + * For `tools.get` and `tools.execute`, pass `signal` directly in the
7 + * options bag (3rd argument) alongside any modifiers or provider options.
8 + * For other methods (e.g. `toolkits.get`, `authConfigs.list`), pass as a
9 + * trailing argument. Forwarded to the underlying `@composio/client` request.
10 + *
11 + * If the underlying request is aborted via this signal, the SDK throws a
12 + * {@link ComposioRequestCancelledError} so callers can `instanceof`-detect
13 + * cancellation without unwrapping nested causes.
14 + *
15 + * @example Timeout after 5 seconds
16 + * ```typescript
17 + * await composio.tools.execute(
18 + * 'HACKERNEWS_GET_FRONTPAGE',
19 + * { userId: 'default', arguments: {} },
20 + * { signal: AbortSignal.timeout(5_000) }
21 + * );
22 + * ```
23 + *
24 + * @example Combine signal with modifiers
25 + * ```typescript
26 + * await composio.tools.execute('TOOL', body, {
27 + * signal: AbortSignal.timeout(10_000),
28 + * beforeExecute: ({ params }) => params,
29 + * });
30 + * ```
31 + */
32 +export type ComposioRequestOptions = {
33 + /**
34 + * An `AbortSignal` used to cancel the in-flight HTTP request. When the
35 + * signal aborts, the underlying fetch is aborted and the SDK throws a
36 + * {@link ComposioRequestCancelledError} (subclass of {@link ComposioError}).
37 + */
38 + signal?: AbortSignal;
39 +};
40 +
41 +/**
42 + * The `@composio/client` per-request transport options, reached via a public
43 + * method whose only parameter is that type (`tools.retrieveEnum`). The
44 + * `internal/*` subpath that declares `RequestOptions` is not in the package's
45 + * `exports`, so we derive it structurally instead of deep-importing it.
46 + * @internal
47 + */
48 +type ClientRequestOptions = NonNullable<Parameters<ComposioClient['tools']['retrieveEnum']>[0]>;
49 +
50 +/**
51 + * Compile-time guards: {@link ComposioRequestOptions} is forwarded verbatim to
52 + * every `@composio/client` call, so it MUST stay a structural subset of the
53 + * client's request options. These constraints fail the build (TS2344) if a
54 + * field here is typed incompatibly with the client's same-named field, or if a
55 + * key is added that the client doesn't have — forcing the divergence to be
56 + * reconciled rather than discovered at runtime.
57 + * @internal
58 + */
59 +type AssertValuesAssignable<_T extends ClientRequestOptions> = void;
60 +type AssertKeysSubset<_K extends keyof ClientRequestOptions> = void;
61 +type _RequestOptionsValuesStayCompatible = AssertValuesAssignable<ComposioRequestOptions>;
62 +type _RequestOptionsKeysStaySubset = AssertKeysSubset<keyof ComposioRequestOptions>;
ts/packages/core/src/utils/cancellation.ts new
+22
@@ -0,0 +1,22 @@
1 +import { ComposioRequestCancelledError, isRequestAbortError } from '../errors/SDKErrors';
2 +
3 +/** @internal */
4 +export async function withCancellation<T>(
5 + call: () => Promise<T>,
6 + signal?: AbortSignal
7 +): Promise<T> {
8 + try {
9 + return await call();
10 + } catch (error) {
11 + if (signal?.aborted && isRequestAbortError(error)) {
12 + const underlyingMessage = error instanceof Error ? error.message : '';
13 + const message = underlyingMessage
14 + ? `Request was cancelled by the caller: ${underlyingMessage}`
15 + : 'Request was cancelled by the caller';
16 + throw new ComposioRequestCancelledError(message, {
17 + cause: error instanceof Error ? error : undefined,
18 + });
19 + }
20 + throw error;
21 + }
22 +}
ts/packages/core/src/utils/fileUtils.node.ts
+27 -16
@@ -36,6 +36,7 @@ export type GetFileDataAfterUploadingToS3Options = {
36 * An empty array means "no paths are allowed" (fail-closed).
37 */
38 fileUploadAllowlist?: string[];
39 + signal?: AbortSignal;
40 };
41
42 // Helper function to get file extension from MIME type
@@ -146,9 +147,10 @@ const readFileContent = async (
147 };
148
149 const readFileContentFromURL = async (
149 - path: string
150 + path: string,
151 + signal?: AbortSignal
152 ): Promise<{ fileName: string; content: string; mimeType: string }> => {
151 - const response = await fetch(path);
153 + const response = await fetch(path, { signal });
154 if (!response.ok) {
155 throw new Error(`Failed to fetch file: ${response.statusText}`);
156 }
@@ -188,16 +190,20 @@ const uploadFileToS3 = async (
190 toolSlug: string,
191 toolkitSlug: string,
192 mimeType: string,
191 - client: ComposioClient
193 + client: ComposioClient,
194 + signal?: AbortSignal
195 ): Promise<string> => {
196 const contentBytes = base64ToUint8Array(content);
194 - const response = await client.files.createPresignedURL({
195 - filename: fileName,
196 - mimetype: mimeType,
197 - md5: crypto.createHash('md5').update(contentBytes).digest('hex'),
198 - tool_slug: toolSlug,
199 - toolkit_slug: toolkitSlug,
200 - });
197 + const response = await client.files.createPresignedURL(
198 + {
199 + filename: fileName,
200 + mimetype: mimeType,
201 + md5: crypto.createHash('md5').update(contentBytes).digest('hex'),
202 + tool_slug: toolSlug,
203 + toolkit_slug: toolkitSlug,
204 + },
205 + { signal }
206 + );
207
208 const { key, new_presigned_url: signedURL } = response;
209
@@ -217,6 +223,7 @@ const uploadFileToS3 = async (
223 const uploadResponse = await fetch(signedURL, {
224 method: 'PUT',
225 body: uploadBuffer,
226 + signal,
227 headers: {
228 'Content-Type': mimeType,
229 },
@@ -230,10 +237,10 @@ const uploadFileToS3 = async (
237 };
238
239 const readFile = async (
233 - file: File | string
240 + file: File | string,
241 + signal?: AbortSignal
242 ): Promise<{ fileName: string; content: string; mimeType: string }> => {
243 if (file instanceof File) {
236 - // if file is a File, read the content from the file
244 const content = await file.arrayBuffer();
245 return {
246 fileName: file.name,
@@ -242,7 +249,7 @@ const readFile = async (
249 };
250 } else if (typeof file === 'string') {
251 if (file.startsWith('http')) {
245 - return await readFileContentFromURL(file);
252 + return await readFileContentFromURL(file, signal);
253 } else {
254 return await readFileContent(file);
255 }
@@ -259,6 +266,7 @@ export const getFileDataAfterUploadingToS3 = async (
266 sensitiveFileUploadProtection,
267 fileUploadPathDenySegments,
268 fileUploadAllowlist,
269 + signal,
270 }: GetFileDataAfterUploadingToS3Options
271 ): Promise<FileUploadData> => {
272 if (!file) {
@@ -277,7 +285,7 @@ export const getFileDataAfterUploadingToS3 = async (
285 });
286 }
287
280 - const fileData = await readFile(file);
288 + const fileData = await readFile(file, signal);
289 logger.debug(`Uploading file to S3...`);
290 const s3key = await uploadFileToS3(
291 platform.basename(fileData.fileName),
@@ -285,7 +293,8 @@ export const getFileDataAfterUploadingToS3 = async (
293 toolSlug,
294 toolkitSlug,
295 fileData.mimeType,
288 - client
296 + client,
297 + signal
298 );
299
300 logger.debug(`Done! File uploaded to S3: ${s3key}`, JSON.stringify(fileData, null, 2));
@@ -301,6 +310,7 @@ export const downloadFileFromS3 = async ({
310 s3Url,
311 mimeType,
312 fileDownloadDir,
313 + signal,
314 }: {
315 toolSlug: string;
316 s3Url: string;
@@ -310,8 +320,9 @@ export const downloadFileFromS3 = async ({
320 * back to `<home>/.composio/files` (the legacy default).
321 */
322 fileDownloadDir?: string;
323 + signal?: AbortSignal;
324 }): Promise<FileDownloadData> => {
314 - const response = await fetch(s3Url);
325 + const response = await fetch(s3Url, { signal });
326 if (!response.ok) {
327 throw new Error(`Failed to download file: ${response.statusText}`);
328 }
ts/packages/core/src/utils/modifiers/FileToolModifier.node.ts
+30 -14
@@ -13,6 +13,7 @@ import {
13 ComposioFileUploadPathNotAllowedError,
14 ComposioSensitiveFilePathBlockedError,
15 } from '../../errors/FileModifierErrors';
16 +import { ComposioRequestCancelledError } from '../../errors/SDKErrors';
17 import type { beforeFileUploadModifier } from '../../types/modifiers.types';
18 import {
19 downloadFileFromS3,
@@ -25,6 +26,7 @@ import {
26 schemaHasFileProperty,
27 } from './FileToolModifier.utils.neutral';
28 import { dereferenceJsonSchema } from '../jsonSchema';
29 +import { withCancellation } from '../cancellation';
30
31 /**
32 * Inlines internal `$ref` pointers so the file walkers below can see the
@@ -109,7 +111,10 @@ const hydrateFiles = async (
111 client: ComposioClient;
112 } & Pick<
113 GetFileDataAfterUploadingToS3Options,
112 - 'sensitiveFileUploadProtection' | 'fileUploadPathDenySegments' | 'fileUploadAllowlist'
114 + | 'sensitiveFileUploadProtection'
115 + | 'fileUploadPathDenySegments'
116 + | 'fileUploadAllowlist'
117 + | 'signal'
118 > & {
119 beforeFileUpload?: beforeFileUploadModifier;
120 }
@@ -155,6 +160,7 @@ const hydrateFiles = async (
160 sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,
161 fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,
162 fileUploadAllowlist: ctx.fileUploadAllowlist,
163 + signal: ctx.signal,
164 });
165 }
166
@@ -181,6 +187,7 @@ const hydrateFiles = async (
187 sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,
188 fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,
189 fileUploadAllowlist: ctx.fileUploadAllowlist,
190 + signal: ctx.signal,
191 });
192 }
193 }
@@ -192,6 +199,7 @@ const hydrateFiles = async (
199 client: ctx.client,
200 sensitiveFileUploadProtection: ctx.sensitiveFileUploadProtection,
201 fileUploadPathDenySegments: ctx.fileUploadPathDenySegments,
202 + signal: ctx.signal,
203 });
204 }
205
@@ -245,7 +253,7 @@ const hydrateFiles = async (
253 */
254 const downloadS3File = async (
255 value: Record<string, unknown>,
248 - ctx: { toolSlug: string; fileDownloadDir?: string }
256 + ctx: { toolSlug: string; fileDownloadDir?: string; signal?: AbortSignal }
257 ): Promise<unknown> => {
258 const { s3url, mimetype } = value as {
259 s3url: string;
@@ -260,6 +268,7 @@ const downloadS3File = async (
268 s3Url: s3url,
269 mimeType: mimetype ?? 'application/octet-stream',
270 fileDownloadDir: ctx.fileDownloadDir,
271 + signal: ctx.signal,
272 });
273
274 logger.debug(`Downloaded → ${dl.filePath}`);
@@ -297,7 +306,7 @@ const downloadS3File = async (
306 const hydrateDownloads = async (
307 value: unknown,
308 schema: JSONSchemaProperty | undefined,
300 - ctx: { toolSlug: string; fileDownloadDir?: string }
309 + ctx: { toolSlug: string; fileDownloadDir?: string; signal?: AbortSignal }
310 ): Promise<unknown> => {
311 // ──────────────────────────────────────────────────────────────────────────
312 // 1. Direct S3 reference (data-driven detection)
@@ -405,24 +414,30 @@ export class FileToolModifier {
414 toolSlug: string;
415 toolkitSlug?: string;
416 params: ToolExecuteParams;
417 + signal?: AbortSignal;
418 }
419 ): Promise<ToolExecuteParams> {
410 - const { params, toolSlug, toolkitSlug = 'unknown' } = options;
420 + const { params, toolSlug, toolkitSlug = 'unknown', signal } = options;
421 const { arguments: args } = params;
422
423 if (!args || typeof args !== 'object') return params;
424
415 - // Recursively transform the arguments tree without mutating the caller’s copy
425 try {
417 - const newArgs = await hydrateFiles(args, resolveFileSchema(tool.inputParameters), {
418 - toolSlug,
419 - toolkitSlug,
420 - client: this.client,
421 - ...this.fileUploadPathOptions,
422 - });
426 + const newArgs = await withCancellation(
427 + () =>
428 + hydrateFiles(args, resolveFileSchema(tool.inputParameters), {
429 + toolSlug,
430 + toolkitSlug,
431 + client: this.client,
432 + ...this.fileUploadPathOptions,
433 + signal,
434 + }),
435 + signal
436 + );
437 return { ...params, arguments: newArgs as ToolExecuteParams['arguments'] };
438 } catch (error) {
439 if (
440 + error instanceof ComposioRequestCancelledError ||
441 error instanceof ComposioSensitiveFilePathBlockedError ||
442 error instanceof ComposioFileUploadAbortedError ||
443 error instanceof ComposioFileUploadPathNotAllowedError ||
@@ -440,19 +455,20 @@ export class FileToolModifier {
455 tool: Tool,
456 options: {
457 toolSlug: string;
443 - toolkitSlug: string; // kept for API parity, unused here
458 + toolkitSlug: string;
459 result: ToolExecuteResponse;
460 + signal?: AbortSignal;
461 }
462 ): Promise<ToolExecuteResponse> {
447 - const { result, toolSlug } = options;
463 + const { result, toolSlug, signal } = options;
464
449 - // Walk result.data without mutating the original, using output schema for guidance
465 const dataWithDownloads = await hydrateDownloads(
466 result.data,
467 resolveFileSchema(tool.outputParameters),
468 {
469 toolSlug,
470 fileDownloadDir: this.fileUploadPathOptions.fileDownloadDir,
471 + signal,
472 }
473 );
474
ts/packages/core/src/utils/modifiers/FileToolModifier.workerd.ts
+2
@@ -31,6 +31,7 @@ export class FileToolModifier {
31 toolSlug: string;
32 toolkitSlug?: string;
33 params: ToolExecuteParams;
34 + signal?: AbortSignal;
35 }
36 ): Promise<ToolExecuteParams> {
37 throw new Error(UNSUPPORTED_MESSAGE);
@@ -42,6 +43,7 @@ export class FileToolModifier {
43 toolSlug: string;
44 toolkitSlug: string;
45 result: ToolExecuteResponse;
46 + signal?: AbortSignal;
47 }
48 ): Promise<ToolExecuteResponse> {
49 throw new Error(UNSUPPORTED_MESSAGE);
ts/packages/core/test/AuthConfigs/authConfigs.test.ts
+155 -100
@@ -158,14 +158,17 @@ describe('AuthConfigs', () => {
158
159 const result = await authConfigs.list();
160
161 - expect(mockClient.authConfigs.list).toHaveBeenCalledWith({
162 - cursor: undefined,
163 - is_composio_managed: undefined,
164 - limit: undefined,
165 - search: undefined,
166 - show_disabled: undefined,
167 - toolkit_slug: undefined,
168 - });
161 + expect(mockClient.authConfigs.list).toHaveBeenCalledWith(
162 + {
163 + cursor: undefined,
164 + is_composio_managed: undefined,
165 + limit: undefined,
166 + search: undefined,
167 + show_disabled: undefined,
168 + toolkit_slug: undefined,
169 + },
170 + undefined
171 + );
172
173 expect(result).toEqual({
174 items: [mockTransformedAuthConfigResponse],
@@ -188,14 +191,17 @@ describe('AuthConfigs', () => {
191
192 const result = await authConfigs.list(query);
193
191 - expect(mockClient.authConfigs.list).toHaveBeenCalledWith({
192 - cursor: 'cursor_123',
193 - is_composio_managed: true,
194 - limit: 10,
195 - search: 'github config',
196 - show_disabled: true,
197 - toolkit_slug: 'github',
198 - });
194 + expect(mockClient.authConfigs.list).toHaveBeenCalledWith(
195 + {
196 + cursor: 'cursor_123',
197 + is_composio_managed: true,
198 + limit: 10,
199 + search: 'github config',
200 + show_disabled: true,
201 + toolkit_slug: 'github',
202 + },
203 + undefined
204 + );
205
206 expect(result).toEqual({
207 items: [mockTransformedAuthConfigResponse],
@@ -251,17 +257,20 @@ describe('AuthConfigs', () => {
257
258 const result = await authConfigs.create('github');
259
254 - expect(mockClient.authConfigs.create).toHaveBeenCalledWith({
255 - toolkit: {
256 - slug: 'github',
257 - },
258 - auth_config: {
259 - type: 'use_composio_managed_auth',
260 - credentials: undefined,
261 - name: undefined,
262 - tool_access_config: undefined,
260 + expect(mockClient.authConfigs.create).toHaveBeenCalledWith(
261 + {
262 + toolkit: {
263 + slug: 'github',
264 + },
265 + auth_config: {
266 + type: 'use_composio_managed_auth',
267 + credentials: undefined,
268 + name: undefined,
269 + tool_access_config: undefined,
270 + },
271 },
264 - });
272 + undefined
273 + );
274
275 expect(result).toEqual({
276 id: 'auth_12345',
@@ -295,22 +304,25 @@ describe('AuthConfigs', () => {
304
305 const result = await authConfigs.create('github', options);
306
298 - expect(mockClient.authConfigs.create).toHaveBeenCalledWith({
299 - toolkit: {
300 - slug: 'github',
301 - },
302 - auth_config: {
303 - type: 'use_custom_auth',
304 - name: 'Custom GitHub Auth',
305 - authScheme: 'OAUTH2',
306 - credentials: {
307 - client_id: 'test_client_id',
308 - client_secret: 'test_client_secret',
307 + expect(mockClient.authConfigs.create).toHaveBeenCalledWith(
308 + {
309 + toolkit: {
310 + slug: 'github',
311 + },
312 + auth_config: {
313 + type: 'use_custom_auth',
314 + name: 'Custom GitHub Auth',
315 + authScheme: 'OAUTH2',
316 + credentials: {
317 + client_id: 'test_client_id',
318 + client_secret: 'test_client_secret',
319 + },
320 + proxy_config: undefined,
321 + tool_access_config: undefined,
322 },
310 - proxy_config: undefined,
311 - tool_access_config: undefined,
323 },
313 - });
324 + undefined
325 + );
326
327 expect(result).toEqual({
328 id: 'auth_12345',
@@ -336,19 +348,22 @@ describe('AuthConfigs', () => {
348
349 const result = await authConfigs.create('github', options);
350
339 - expect(mockClient.authConfigs.create).toHaveBeenCalledWith({
340 - toolkit: {
341 - slug: 'github',
342 - },
343 - auth_config: {
344 - type: 'use_composio_managed_auth',
345 - credentials: {
346 - custom_field: 'value',
351 + expect(mockClient.authConfigs.create).toHaveBeenCalledWith(
352 + {
353 + toolkit: {
354 + slug: 'github',
355 + },
356 + auth_config: {
357 + type: 'use_composio_managed_auth',
358 + credentials: {
359 + custom_field: 'value',
360 + },
361 + name: 'My GitHub Config',
362 + tool_access_config: undefined,
363 },
348 - name: 'My GitHub Config',
349 - tool_access_config: undefined,
364 },
351 - });
365 + undefined
366 + );
367
368 expect(result).toEqual({
369 id: 'auth_12345',
@@ -380,7 +395,7 @@ describe('AuthConfigs', () => {
395
396 const result = await authConfigs.get('auth_12345');
397
383 - expect(mockClient.authConfigs.retrieve).toHaveBeenCalledWith('auth_12345');
398 + expect(mockClient.authConfigs.retrieve).toHaveBeenCalledWith('auth_12345', undefined);
399 expect(result).toEqual(mockTransformedAuthConfigResponse);
400 });
401
@@ -447,16 +462,20 @@ describe('AuthConfigs', () => {
462
463 const result = await authConfigs.update('auth_12345', updateData);
464
450 - expect(mockClient.authConfigs.update).toHaveBeenCalledWith('auth_12345', {
451 - type: 'custom',
452 - credentials: {
453 - client_id: 'new_client_id',
454 - client_secret: 'new_client_secret',
455 - },
456 - tool_access_config: {
457 - tools_for_connected_account_creation: undefined,
465 + expect(mockClient.authConfigs.update).toHaveBeenCalledWith(
466 + 'auth_12345',
467 + {
468 + type: 'custom',
469 + credentials: {
470 + client_id: 'new_client_id',
471 + client_secret: 'new_client_secret',
472 + },
473 + tool_access_config: {
474 + tools_for_connected_account_creation: undefined,
475 + },
476 },
459 - });
477 + undefined
478 + );
479
480 expect(result).toEqual(mockUpdateResponse);
481 });
@@ -471,13 +490,17 @@ describe('AuthConfigs', () => {
490
491 const result = await authConfigs.update('auth_12345', updateData);
492
474 - expect(mockClient.authConfigs.update).toHaveBeenCalledWith('auth_12345', {
475 - type: 'default',
476 - scopes: 'read:user,repo',
477 - tool_access_config: {
478 - tools_for_connected_account_creation: undefined,
493 + expect(mockClient.authConfigs.update).toHaveBeenCalledWith(
494 + 'auth_12345',
495 + {
496 + type: 'default',
497 + scopes: 'read:user,repo',
498 + tool_access_config: {
499 + tools_for_connected_account_creation: undefined,
500 + },
501 },
480 - });
502 + undefined
503 + );
504
505 expect(result).toEqual(mockUpdateResponse);
506 });
@@ -494,15 +517,19 @@ describe('AuthConfigs', () => {
517
518 const result = await authConfigs.update('auth_12345', updateData);
519
497 - expect(mockClient.authConfigs.update).toHaveBeenCalledWith('auth_12345', {
498 - type: 'custom',
499 - credentials: {
500 - api_key: 'new_api_key',
501 - },
502 - tool_access_config: {
503 - tools_for_connected_account_creation: undefined,
520 + expect(mockClient.authConfigs.update).toHaveBeenCalledWith(
521 + 'auth_12345',
522 + {
523 + type: 'custom',
524 + credentials: {
525 + api_key: 'new_api_key',
526 + },
527 + tool_access_config: {
528 + tools_for_connected_account_creation: undefined,
529 + },
530 },
505 - });
531 + undefined
532 + );
533
534 expect(result).toEqual(mockUpdateResponse);
535 });
@@ -545,7 +572,11 @@ describe('AuthConfigs', () => {
572
573 const result = await authConfigs.delete('auth_12345');
574
548 - expect(mockClient.authConfigs.delete).toHaveBeenCalledWith('auth_12345');
575 + expect(mockClient.authConfigs.delete).toHaveBeenCalledWith(
576 + 'auth_12345',
577 + undefined,
578 + undefined
579 + );
580 expect(result).toEqual(mockDeleteResponse);
581 });
582
@@ -568,9 +599,13 @@ describe('AuthConfigs', () => {
599
600 const result = await authConfigs.updateStatus('ENABLED', 'auth_12345');
601
571 - expect(mockClient.authConfigs.updateStatus).toHaveBeenCalledWith('ENABLED', {
572 - nanoid: 'auth_12345',
573 - });
602 + expect(mockClient.authConfigs.updateStatus).toHaveBeenCalledWith(
603 + 'ENABLED',
604 + {
605 + nanoid: 'auth_12345',
606 + },
607 + undefined
608 + );
609 expect(result).toEqual(mockStatusUpdateResponse);
610 });
611
@@ -583,9 +618,13 @@ describe('AuthConfigs', () => {
618
619 const result = await authConfigs.updateStatus('DISABLED', 'auth_12345');
620
586 - expect(mockClient.authConfigs.updateStatus).toHaveBeenCalledWith('DISABLED', {
587 - nanoid: 'auth_12345',
588 - });
621 + expect(mockClient.authConfigs.updateStatus).toHaveBeenCalledWith(
622 + 'DISABLED',
623 + {
624 + nanoid: 'auth_12345',
625 + },
626 + undefined
627 + );
628 expect(result).toEqual(disabledResponse);
629 });
630
@@ -610,9 +649,13 @@ describe('AuthConfigs', () => {
649
650 const result = await authConfigs.enable('auth_12345');
651
613 - expect(mockClient.authConfigs.updateStatus).toHaveBeenCalledWith('ENABLED', {
614 - nanoid: 'auth_12345',
615 - });
652 + expect(mockClient.authConfigs.updateStatus).toHaveBeenCalledWith(
653 + 'ENABLED',
654 + {
655 + nanoid: 'auth_12345',
656 + },
657 + undefined
658 + );
659 expect(result).toEqual(mockStatusUpdateResponse);
660 });
661
@@ -635,9 +678,13 @@ describe('AuthConfigs', () => {
678
679 const result = await authConfigs.disable('auth_12345');
680
638 - expect(mockClient.authConfigs.updateStatus).toHaveBeenCalledWith('DISABLED', {
639 - nanoid: 'auth_12345',
640 - });
681 + expect(mockClient.authConfigs.updateStatus).toHaveBeenCalledWith(
682 + 'DISABLED',
683 + {
684 + nanoid: 'auth_12345',
685 + },
686 + undefined
687 + );
688 expect(result).toEqual(mockStatusUpdateResponse);
689 });
690
@@ -745,13 +792,17 @@ describe('AuthConfigs', () => {
792
793 const result = await authConfigs.update('auth_12345', updateData);
794
748 - expect(mockClient.authConfigs.update).toHaveBeenCalledWith('auth_12345', {
749 - type: 'custom',
750 - credentials: largeCredentials,
751 - tool_access_config: {
752 - tools_for_connected_account_creation: undefined,
795 + expect(mockClient.authConfigs.update).toHaveBeenCalledWith(
796 + 'auth_12345',
797 + {
798 + type: 'custom',
799 + credentials: largeCredentials,
800 + tool_access_config: {
801 + tools_for_connected_account_creation: undefined,
802 + },
803 },
754 - });
804 + undefined
805 + );
806
807 expect(result).toEqual(mockUpdateResponse);
808 });
@@ -773,13 +824,17 @@ describe('AuthConfigs', () => {
824
825 const result = await authConfigs.update('auth_12345', updateData);
826
776 - expect(mockClient.authConfigs.update).toHaveBeenCalledWith('auth_12345', {
777 - type: 'default',
778 - scopes: longScopes,
779 - tool_access_config: {
780 - tools_for_connected_account_creation: undefined,
827 + expect(mockClient.authConfigs.update).toHaveBeenCalledWith(
828 + 'auth_12345',
829 + {
830 + type: 'default',
831 + scopes: longScopes,
832 + tool_access_config: {
833 + tools_for_connected_account_creation: undefined,
834 + },
835 },
782 - });
836 + undefined
837 + );
838
839 expect(result).toEqual(mockUpdateResponse);
840 });
ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts
+230 -138
@@ -63,7 +63,7 @@ describe('ConnectedAccounts', () => {
63
64 const result = await connectedAccounts.list(query);
65
66 - expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(query);
66 + expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(query, undefined);
67 expect(result).toEqual({
68 items: [],
69 nextCursor: null,
@@ -78,7 +78,7 @@ describe('ConnectedAccounts', () => {
78
79 const result = await connectedAccounts.list();
80
81 - expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(undefined);
81 + expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(undefined, undefined);
82 expect(result).toEqual({
83 items: [],
84 nextCursor: null,
@@ -123,19 +123,23 @@ describe('ConnectedAccounts', () => {
123 user_ids: [userId],
124 auth_config_ids: [authConfigId],
125 statuses: [ConnectedAccountStatuses.ACTIVE],
126 - })
126 + }),
127 + undefined
128 );
129
129 - expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith({
130 - auth_config: {
131 - id: authConfigId,
132 - },
133 - connection: {
134 - user_id: userId,
135 - callback_url: options.callbackUrl,
136 - state: undefined,
130 + expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith(
131 + {
132 + auth_config: {
133 + id: authConfigId,
134 + },
135 + connection: {
136 + user_id: userId,
137 + callback_url: options.callbackUrl,
138 + state: undefined,
139 + },
140 },
138 - });
141 + undefined
142 + );
143
144 expect(connectionRequest).toHaveProperty('id', 'conn_123');
145 expect(connectionRequest).toHaveProperty('waitForConnection');
@@ -168,16 +172,19 @@ describe('ConnectedAccounts', () => {
172
173 const connectionRequest = await connectedAccounts.initiate(userId, authConfigId);
174
171 - expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith({
172 - auth_config: {
173 - id: authConfigId,
174 - },
175 - connection: {
176 - user_id: userId,
177 - callback_url: undefined,
178 - state: undefined,
175 + expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith(
176 + {
177 + auth_config: {
178 + id: authConfigId,
179 + },
180 + connection: {
181 + user_id: userId,
182 + callback_url: undefined,
183 + state: undefined,
184 + },
185 },
180 - });
186 + undefined
187 + );
188
189 expect(connectionRequest).toHaveProperty('id', 'conn_123');
190 expect(connectionRequest).toHaveProperty('waitForConnection');
@@ -215,7 +222,8 @@ describe('ConnectedAccounts', () => {
222 expect.objectContaining({
223 auth_config: { id: authConfigId },
224 connection: expect.objectContaining({ user_id: userId, alias: 'work-gmail' }),
218 - })
225 + }),
226 + undefined
227 );
228 });
229
@@ -336,7 +344,8 @@ describe('ConnectedAccounts', () => {
344 user_ids: [userId],
345 auth_config_ids: [authConfigId],
346 statuses: [ConnectedAccountStatuses.ACTIVE],
339 - })
347 + }),
348 + undefined
349 );
350 });
351
@@ -407,16 +416,19 @@ describe('ConnectedAccounts', () => {
416 allowMultiple: true,
417 });
418
410 - expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith({
411 - auth_config: {
412 - id: authConfigId,
413 - },
414 - connection: {
415 - user_id: userId,
416 - callback_url: undefined,
417 - state: undefined,
419 + expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith(
420 + {
421 + auth_config: {
422 + id: authConfigId,
423 + },
424 + connection: {
425 + user_id: userId,
426 + callback_url: undefined,
427 + state: undefined,
428 + },
429 },
419 - });
430 + undefined
431 + );
432
433 expect(connectionRequest).toHaveProperty('id', 'conn_123');
434 expect(connectionRequest).toHaveProperty('waitForConnection');
@@ -455,16 +467,19 @@ describe('ConnectedAccounts', () => {
467
468 const connectionRequest = await connectedAccounts.initiate(userId, authConfigId, options);
469
458 - expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith({
459 - auth_config: {
460 - id: authConfigId,
461 - },
462 - connection: {
463 - user_id: userId,
464 - callback_url: options.callbackUrl,
465 - state: options.config,
470 + expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith(
471 + {
472 + auth_config: {
473 + id: authConfigId,
474 + },
475 + connection: {
476 + user_id: userId,
477 + callback_url: options.callbackUrl,
478 + state: options.config,
479 + },
480 },
467 - });
481 + undefined
482 + );
483
484 expect(connectionRequest).toHaveProperty('id', 'conn_123');
485 expect(connectionRequest).toHaveProperty('status', ConnectionStatuses.ACTIVE);
@@ -652,7 +667,7 @@ describe('ConnectedAccounts', () => {
667
668 const result = await connectedAccounts.get(nanoid);
669
655 - expect(extendedMockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(nanoid);
670 + expect(extendedMockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(nanoid, undefined);
671 expect(result).toEqual({
672 id: 'nanoid',
673 status: 'ACTIVE',
@@ -750,7 +765,11 @@ describe('ConnectedAccounts', () => {
765
766 const result = await connectedAccounts.delete(nanoid);
767
753 - expect(extendedMockClient.connectedAccounts.delete).toHaveBeenCalledWith(nanoid);
768 + expect(extendedMockClient.connectedAccounts.delete).toHaveBeenCalledWith(
769 + nanoid,
770 + undefined,
771 + undefined
772 + );
773 expect(result).toEqual(mockResponse);
774 });
775 });
@@ -764,7 +783,11 @@ describe('ConnectedAccounts', () => {
783
784 const result = await connectedAccounts.refresh(nanoid);
785
767 - expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(nanoid, undefined);
786 + expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(
787 + nanoid,
788 + undefined,
789 + undefined
790 + );
791 expect(result).toEqual(mockResponse);
792 });
793
@@ -777,10 +800,14 @@ describe('ConnectedAccounts', () => {
800
801 const result = await connectedAccounts.refresh(nanoid, { redirectUrl });
802
780 - expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(nanoid, {
781 - query_redirect_url: redirectUrl,
782 - validate_credentials: undefined,
783 - });
803 + expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(
804 + nanoid,
805 + {
806 + query_redirect_url: redirectUrl,
807 + validate_credentials: undefined,
808 + },
809 + undefined
810 + );
811 expect(result).toEqual(mockResponse);
812 });
813
@@ -792,10 +819,14 @@ describe('ConnectedAccounts', () => {
819
820 const result = await connectedAccounts.refresh(nanoid, { validateCredentials: true });
821
795 - expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(nanoid, {
796 - query_redirect_url: undefined,
797 - validate_credentials: true,
798 - });
822 + expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(
823 + nanoid,
824 + {
825 + query_redirect_url: undefined,
826 + validate_credentials: true,
827 + },
828 + undefined
829 + );
830 expect(result).toEqual(mockResponse);
831 });
832
@@ -811,10 +842,14 @@ describe('ConnectedAccounts', () => {
842
843 const result = await connectedAccounts.refresh(nanoid, options);
844
814 - expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(nanoid, {
815 - query_redirect_url: options.redirectUrl,
816 - validate_credentials: options.validateCredentials,
817 - });
845 + expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(
846 + nanoid,
847 + {
848 + query_redirect_url: options.redirectUrl,
849 + validate_credentials: options.validateCredentials,
850 + },
851 + undefined
852 + );
853 expect(result).toEqual(mockResponse);
854 });
855
@@ -837,10 +872,14 @@ describe('ConnectedAccounts', () => {
872
873 const result = await connectedAccounts.refresh(nanoid, {});
874
840 - expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(nanoid, {
841 - query_redirect_url: undefined,
842 - validate_credentials: undefined,
843 - });
875 + expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(
876 + nanoid,
877 + {
878 + query_redirect_url: undefined,
879 + validate_credentials: undefined,
880 + },
881 + undefined
882 + );
883 expect(result).toEqual(mockResponse);
884 });
885 });
@@ -857,7 +896,8 @@ describe('ConnectedAccounts', () => {
896
897 expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(
898 nanoid,
860 - params
899 + params,
900 + undefined
901 );
902 expect(result).toEqual(mockResponse);
903 });
@@ -872,9 +912,13 @@ describe('ConnectedAccounts', () => {
912
913 const result = await connectedAccounts.enable(nanoid);
914
875 - expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(nanoid, {
876 - enabled: true,
877 - });
915 + expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(
916 + nanoid,
917 + {
918 + enabled: true,
919 + },
920 + undefined
921 + );
922 expect(result).toEqual(mockResponse);
923 });
924 });
@@ -888,9 +932,13 @@ describe('ConnectedAccounts', () => {
932
933 const result = await connectedAccounts.disable(nanoid);
934
891 - expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(nanoid, {
892 - enabled: false,
893 - });
935 + expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(
936 + nanoid,
937 + {
938 + enabled: false,
939 + },
940 + undefined
941 + );
942 expect(result).toEqual(mockResponse);
943 });
944 });
@@ -1089,9 +1137,13 @@ describe('ConnectedAccounts', () => {
1137
1138 const result = await connectedAccounts.update(nanoid, { enabled: true });
1139
1092 - expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(nanoid, {
1093 - enabled: true,
1094 - });
1140 + expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(
1141 + nanoid,
1142 + {
1143 + enabled: true,
1144 + },
1145 + undefined
1146 + );
1147 expect(result).toEqual({ success: true, id: nanoid, status: 'ACTIVE' });
1148 });
1149
@@ -1103,9 +1155,13 @@ describe('ConnectedAccounts', () => {
1155
1156 const result = await connectedAccounts.update(nanoid, { enabled: false });
1157
1106 - expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(nanoid, {
1107 - enabled: false,
1108 - });
1158 + expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(
1159 + nanoid,
1160 + {
1161 + enabled: false,
1162 + },
1163 + undefined
1164 + );
1165 expect(result).toEqual({ success: true });
1166 });
1167
@@ -1142,10 +1198,13 @@ describe('ConnectedAccounts', () => {
1198
1199 const connectionRequest = await connectedAccounts.link(userId, authConfigId);
1200
1145 - expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1146 - auth_config_id: authConfigId,
1147 - user_id: userId,
1148 - });
1201 + expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1202 + {
1203 + auth_config_id: authConfigId,
1204 + user_id: userId,
1205 + },
1206 + undefined
1207 + );
1208
1209 expect(connectionRequest).toHaveProperty('id', 'conn_456def');
1210 expect(connectionRequest).toHaveProperty('status', ConnectedAccountStatuses.INITIATED);
@@ -1175,11 +1234,14 @@ describe('ConnectedAccounts', () => {
1234
1235 const connectionRequest = await connectedAccounts.link(userId, authConfigId, options);
1236
1178 - expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1179 - auth_config_id: authConfigId,
1180 - user_id: userId,
1181 - callback_url: options.callbackUrl,
1182 - });
1237 + expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1238 + {
1239 + auth_config_id: authConfigId,
1240 + user_id: userId,
1241 + callback_url: options.callbackUrl,
1242 + },
1243 + undefined
1244 + );
1245
1246 expect(connectionRequest).toHaveProperty('id', 'conn_456def');
1247 expect(connectionRequest).toHaveProperty('status', ConnectedAccountStatuses.INITIATED);
@@ -1219,10 +1281,13 @@ describe('ConnectedAccounts', () => {
1281
1282 const connectionRequest = await connectedAccounts.link(userId, authConfigId, undefined);
1283
1222 - expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1223 - auth_config_id: authConfigId,
1224 - user_id: userId,
1225 - });
1284 + expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1285 + {
1286 + auth_config_id: authConfigId,
1287 + user_id: userId,
1288 + },
1289 + undefined
1290 + );
1291
1292 expect(connectionRequest).toHaveProperty('id', 'conn_456def');
1293 expect(connectionRequest).toHaveProperty('status', ConnectedAccountStatuses.INITIATED);
@@ -1248,10 +1313,13 @@ describe('ConnectedAccounts', () => {
1313
1314 const connectionRequest = await connectedAccounts.link(userId, authConfigId, options);
1315
1251 - expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1252 - auth_config_id: authConfigId,
1253 - user_id: userId,
1254 - });
1316 + expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1317 + {
1318 + auth_config_id: authConfigId,
1319 + user_id: userId,
1320 + },
1321 + undefined
1322 + );
1323
1324 expect(connectionRequest).toHaveProperty('id', 'conn_456def');
1325 expect(connectionRequest).toHaveProperty('status', ConnectedAccountStatuses.INITIATED);
@@ -1329,11 +1397,14 @@ describe('ConnectedAccounts', () => {
1397 const options = { callbackUrl };
1398 const connectionRequest = await connectedAccounts.link(userId, authConfigId, options);
1399
1332 - expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1333 - auth_config_id: authConfigId,
1334 - user_id: userId,
1335 - callback_url: callbackUrl,
1336 - });
1400 + expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1401 + {
1402 + auth_config_id: authConfigId,
1403 + user_id: userId,
1404 + callback_url: callbackUrl,
1405 + },
1406 + undefined
1407 + );
1408
1409 expect(connectionRequest).toHaveProperty('id', 'conn_456def');
1410 expect(connectionRequest).toHaveProperty('status', ConnectedAccountStatuses.INITIATED);
@@ -1407,10 +1478,13 @@ describe('ConnectedAccounts', () => {
1478 'Failed to create connected account link'
1479 );
1480
1410 - expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1411 - auth_config_id: authConfigId,
1412 - user_id: userId,
1413 - });
1481 + expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1482 + {
1483 + auth_config_id: authConfigId,
1484 + user_id: userId,
1485 + },
1486 + undefined
1487 + );
1488 });
1489
1490 it('should not include callback_url in API call when callbackUrl is not provided', async () => {
@@ -1428,10 +1502,13 @@ describe('ConnectedAccounts', () => {
1502 await connectedAccounts.link(userId, authConfigId, options);
1503
1504 // Verify that callback_url is not included in the API call
1431 - expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1432 - auth_config_id: authConfigId,
1433 - user_id: userId,
1434 - });
1505 + expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1506 + {
1507 + auth_config_id: authConfigId,
1508 + user_id: userId,
1509 + },
1510 + undefined
1511 + );
1512
1513 // Ensure callback_url key is not present at all
1514 const callArgs = extendedMockClient.link.create.mock.calls[0][0];
@@ -1454,11 +1531,14 @@ describe('ConnectedAccounts', () => {
1531
1532 await connectedAccounts.link(userId, authConfigId, options);
1533
1457 - expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1458 - auth_config_id: authConfigId,
1459 - user_id: userId,
1460 - callback_url: 'https://example.com/callback',
1461 - });
1534 + expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1535 + {
1536 + auth_config_id: authConfigId,
1537 + user_id: userId,
1538 + callback_url: 'https://example.com/callback',
1539 + },
1540 + undefined
1541 + );
1542 });
1543
1544 it('throws ComposioMultipleConnectedAccountsError when an active connection exists and allowMultiple is false', async () => {
@@ -1513,11 +1593,14 @@ describe('ConnectedAccounts', () => {
1593 alias: 'work-gmail',
1594 });
1595
1516 - expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1517 - auth_config_id: authConfigId,
1518 - user_id: userId,
1519 - alias: 'work-gmail',
1520 - });
1596 + expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1597 + {
1598 + auth_config_id: authConfigId,
1599 + user_id: userId,
1600 + alias: 'work-gmail',
1601 + },
1602 + undefined
1603 + );
1604 expect(connectionRequest).toHaveProperty('id', 'conn_new');
1605 });
1606 });
@@ -1546,17 +1629,20 @@ describe('ConnectedAccounts', () => {
1629 },
1630 });
1631
1549 - expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1550 - auth_config_id: 'auth_config_123',
1551 - user_id: 'user_123',
1552 - experimental: {
1553 - account_type: 'SHARED',
1554 - acl_config_for_shared: {
1555 - allow_all_users: true,
1556 - not_allowed_user_ids: ['user_bob'],
1632 + expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1633 + {
1634 + auth_config_id: 'auth_config_123',
1635 + user_id: 'user_123',
1636 + experimental: {
1637 + account_type: 'SHARED',
1638 + acl_config_for_shared: {
1639 + allow_all_users: true,
1640 + not_allowed_user_ids: ['user_bob'],
1641 + },
1642 },
1643 },
1559 - });
1644 + undefined
1645 + );
1646 });
1647
1648 it('omits the inner acl block when aclConfigForShared is undefined', async () => {
@@ -1584,14 +1670,17 @@ describe('ConnectedAccounts', () => {
1670 },
1671 });
1672
1587 - expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1588 - auth_config_id: 'auth_config_123',
1589 - user_id: 'user_123',
1590 - experimental: {
1591 - account_type: 'SHARED',
1592 - acl_config_for_shared: { allowed_user_ids: ['user_alice'] },
1673 + expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1674 + {
1675 + auth_config_id: 'auth_config_123',
1676 + user_id: 'user_123',
1677 + experimental: {
1678 + account_type: 'SHARED',
1679 + acl_config_for_shared: { allowed_user_ids: ['user_alice'] },
1680 + },
1681 },
1594 - });
1682 + undefined
1683 + );
1684 });
1685
1686 it('preserves explicit empty arrays in the serialized body', async () => {
@@ -1602,17 +1691,20 @@ describe('ConnectedAccounts', () => {
1691 },
1692 });
1693
1605 - expect(extendedMockClient.link.create).toHaveBeenCalledWith({
1606 - auth_config_id: 'auth_config_123',
1607 - user_id: 'user_123',
1608 - experimental: {
1609 - account_type: 'SHARED',
1610 - acl_config_for_shared: {
1611 - allowed_user_ids: [],
1612 - not_allowed_user_ids: [],
1694 + expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1695 + {
1696 + auth_config_id: 'auth_config_123',
1697 + user_id: 'user_123',
1698 + experimental: {
1699 + account_type: 'SHARED',
1700 + acl_config_for_shared: {
1701 + allowed_user_ids: [],
1702 + not_allowed_user_ids: [],
1703 + },
1704 },
1705 },
1615 - });
1706 + undefined
1707 + );
1708 });
1709
1710 it('maps 400 AclOnlyForShared to ComposioAclOnlyForSharedError', async () => {
ts/packages/core/test/models/customTool.test.ts
+36 -20
@@ -640,10 +640,14 @@ describe('SessionContextImpl', () => {
640 const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
641 const result = await ctx.execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' });
642
643 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_1', {
644 - tool_slug: 'GMAIL_SEND_EMAIL',
645 - arguments: { to: 'test@test.com' },
646 - });
643 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
644 + 'sess_1',
645 + {
646 + tool_slug: 'GMAIL_SEND_EMAIL',
647 + arguments: { to: 'test@test.com' },
648 + },
649 + undefined
650 + );
651 expect(result).toEqual({
652 data: { result: 'ok' },
653 error: null,
@@ -670,13 +674,17 @@ describe('SessionContextImpl', () => {
674 });
675 await ctx.execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' });
676
673 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_1', {
674 - tool_slug: 'GMAIL_SEND_EMAIL',
675 - arguments: { to: 'test@test.com' },
676 - experimental: {
677 - custom_tools: [expect.objectContaining({ slug: 'GREP' })],
677 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
678 + 'sess_1',
679 + {
680 + tool_slug: 'GMAIL_SEND_EMAIL',
681 + arguments: { to: 'test@test.com' },
682 + experimental: {
683 + custom_tools: [expect.objectContaining({ slug: 'GREP' })],
684 + },
685 },
679 - });
686 + undefined
687 + );
688 });
689
690 it('should preserve logId and error when execute() returns an error', async () => {
@@ -707,12 +715,16 @@ describe('SessionContextImpl', () => {
715 parameters: [{ in: 'header' as const, name: 'X-Custom', value: 'val' }],
716 });
717
710 - expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith('sess_1', {
711 - toolkit_slug: 'github',
712 - endpoint: 'https://api.github.com/user',
713 - method: 'GET',
714 - parameters: [{ name: 'X-Custom', type: 'header', value: 'val' }],
715 - });
718 + expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith(
719 + 'sess_1',
720 + {
721 + toolkit_slug: 'github',
722 + endpoint: 'https://api.github.com/user',
723 + method: 'GET',
724 + parameters: [{ name: 'X-Custom', type: 'header', value: 'val' }],
725 + },
726 + undefined
727 + );
728 expect(result).toEqual({
729 status: 200,
730 data: { proxy_result: true },
@@ -765,10 +777,14 @@ describe('SessionContextImpl', () => {
777 const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', customToolsMap);
778 const result = await ctx.execute('REMOTE_TOOL', { key: 'val' });
779
768 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_1', {
769 - tool_slug: 'REMOTE_TOOL',
770 - arguments: { key: 'val' },
771 - });
780 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
781 + 'sess_1',
782 + {
783 + tool_slug: 'REMOTE_TOOL',
784 + arguments: { key: 'val' },
785 + },
786 + undefined
787 + );
788 expect(result).toEqual({ data: { remote: true }, error: null, logId: 'log_3' });
789 });
790
ts/packages/core/test/models/customToolRouting.test.ts
+26 -14
@@ -308,10 +308,14 @@ describe('ToolRouterSession execution routing', () => {
308
309 await session.execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' });
310
311 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_123', {
312 - tool_slug: 'GMAIL_SEND_EMAIL',
313 - arguments: { to: 'test@test.com' },
314 - });
311 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
312 + 'sess_123',
313 + {
314 + tool_slug: 'GMAIL_SEND_EMAIL',
315 + arguments: { to: 'test@test.com' },
316 + },
317 + undefined
318 + );
319 expect(localExecute).not.toHaveBeenCalled();
320 });
321
@@ -336,12 +340,16 @@ describe('ToolRouterSession execution routing', () => {
340 parameters: [{ in: 'header', name: 'X-Test', value: '1' }],
341 });
342
339 - expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith('sess_123', {
340 - toolkit_slug: 'github',
341 - endpoint: 'https://api.github.com/user',
342 - method: 'GET',
343 - parameters: [{ name: 'X-Test', type: 'header', value: '1' }],
344 - });
343 + expect(mockClient.toolRouter.session.proxyExecute).toHaveBeenCalledWith(
344 + 'sess_123',
345 + {
346 + toolkit_slug: 'github',
347 + endpoint: 'https://api.github.com/user',
348 + method: 'GET',
349 + parameters: [{ name: 'X-Test', type: 'header', value: '1' }],
350 + },
351 + undefined
352 + );
353 expect(result).toEqual({
354 status: 200,
355 data: { ok: true },
@@ -380,10 +388,14 @@ describe('ToolRouterSession execution routing', () => {
388 const session = createSession(mockClient, [chainedTool]);
389 await session.execute('CHAINED_TOOL', { to: 'test@test.com' });
390
383 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_123', {
384 - tool_slug: 'GMAIL_SEND_EMAIL',
385 - arguments: { to: 'test@test.com' },
386 - });
391 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
392 + 'sess_123',
393 + {
394 + tool_slug: 'GMAIL_SEND_EMAIL',
395 + arguments: { to: 'test@test.com' },
396 + },
397 + undefined
398 + );
399 });
400
401 it('should route sibling local tools in-process without hitting the API', async () => {
ts/packages/core/test/models/mcp.test.ts
+68 -46
@@ -75,13 +75,16 @@ describe('MCP', () => {
75 expect(result).toHaveProperty('name', 'test-server');
76 expect(result).toHaveProperty('generate');
77 expect(typeof result.generate).toBe('function');
78 - expect(mockClient.mcp.custom.create).toHaveBeenCalledWith({
79 - name: 'test-server',
80 - toolkits: ['gmail'],
81 - auth_config_ids: [],
82 - custom_tools: [],
83 - managed_auth_via_composio: true,
84 - });
78 + expect(mockClient.mcp.custom.create).toHaveBeenCalledWith(
79 + {
80 + name: 'test-server',
81 + toolkits: ['gmail'],
82 + auth_config_ids: [],
83 + custom_tools: [],
84 + managed_auth_via_composio: true,
85 + },
86 + undefined
87 + );
88 });
89
90 it('should handle toolkits with auth config IDs', async () => {
@@ -104,13 +107,16 @@ describe('MCP', () => {
107 toolkits: [{ toolkit: 'gmail', authConfigId: 'auth_456' }],
108 });
109
107 - expect(mockClient.mcp.custom.create).toHaveBeenCalledWith({
108 - name: 'test-server',
109 - toolkits: ['gmail'],
110 - auth_config_ids: [],
111 - custom_tools: [],
112 - managed_auth_via_composio: true,
113 - });
110 + expect(mockClient.mcp.custom.create).toHaveBeenCalledWith(
111 + {
112 + name: 'test-server',
113 + toolkits: ['gmail'],
114 + auth_config_ids: [],
115 + custom_tools: [],
116 + managed_auth_via_composio: true,
117 + },
118 + undefined
119 + );
120 });
121
122 it('should validate configuration', async () => {
@@ -150,13 +156,16 @@ describe('MCP', () => {
156 expect(result).toHaveProperty('currentPage', 1);
157 expect(result).toHaveProperty('totalPages', 1);
158 expect(result.items).toHaveLength(1);
153 - expect(mockClient.mcp.list).toHaveBeenCalledWith({
154 - page_no: 1,
155 - limit: 10,
156 - toolkits: undefined,
157 - auth_config_ids: undefined,
158 - name: undefined,
159 - });
159 + expect(mockClient.mcp.list).toHaveBeenCalledWith(
160 + {
161 + page_no: 1,
162 + limit: 10,
163 + toolkits: undefined,
164 + auth_config_ids: undefined,
165 + name: undefined,
166 + },
167 + undefined
168 + );
169 });
170
171 it('should list MCP servers with filters', async () => {
@@ -176,13 +185,16 @@ describe('MCP', () => {
185 name: 'test',
186 });
187
179 - expect(mockClient.mcp.list).toHaveBeenCalledWith({
180 - page_no: 2,
181 - limit: 20,
182 - toolkits: 'gmail,slack',
183 - auth_config_ids: 'auth_1',
184 - name: 'test',
185 - });
188 + expect(mockClient.mcp.list).toHaveBeenCalledWith(
189 + {
190 + page_no: 2,
191 + limit: 20,
192 + toolkits: 'gmail,slack',
193 + auth_config_ids: 'auth_1',
194 + name: 'test',
195 + },
196 + undefined
197 + );
198 });
199
200 it('should handle validation errors', async () => {
@@ -215,7 +227,7 @@ describe('MCP', () => {
227 expect(result).toHaveProperty('id', 'mcp_123');
228 expect(result).toHaveProperty('name', 'test-server');
229 expect(result).toHaveProperty('serverInstanceCount', 5);
218 - expect(mockClient.mcp.retrieve).toHaveBeenCalledWith('mcp_123');
230 + expect(mockClient.mcp.retrieve).toHaveBeenCalledWith('mcp_123', undefined);
231 });
232 });
233
@@ -231,7 +243,7 @@ describe('MCP', () => {
243 const result = await mcp.delete('mcp_123');
244
245 expect(result).toEqual(mockResponse);
234 - expect(mockClient.mcp.delete).toHaveBeenCalledWith('mcp_123');
246 + expect(mockClient.mcp.delete).toHaveBeenCalledWith('mcp_123', undefined);
247 });
248 });
249
@@ -262,12 +274,16 @@ describe('MCP', () => {
274
275 expect(result).toHaveProperty('id', 'mcp_123');
276 expect(result).toHaveProperty('name', 'updated-server');
265 - expect(mockClient.mcp.update).toHaveBeenCalledWith('mcp_123', {
266 - name: 'updated-server',
267 - custom_tools: undefined,
268 - toolkits: ['slack'],
269 - auth_config_ids: [],
270 - });
277 + expect(mockClient.mcp.update).toHaveBeenCalledWith(
278 + 'mcp_123',
279 + {
280 + name: 'updated-server',
281 + custom_tools: undefined,
282 + toolkits: ['slack'],
283 + auth_config_ids: [],
284 + },
285 + undefined
286 + );
287 });
288
289 it('should validate update parameters', async () => {
@@ -301,11 +317,14 @@ describe('MCP', () => {
317 expect(result).toHaveProperty('userId', 'user123');
318 expect(result).toHaveProperty('type', 'streamable_http');
319 expect(result).toHaveProperty('url', 'https://mcp.example.com/instance/user123');
304 - expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({
305 - mcp_server_id: 'mcp_123',
306 - user_ids: ['user123'],
307 - managed_auth_by_composio: true,
308 - });
320 + expect(mockClient.mcp.generate.url).toHaveBeenCalledWith(
321 + {
322 + mcp_server_id: 'mcp_123',
323 + user_ids: ['user123'],
324 + managed_auth_by_composio: true,
325 + },
326 + undefined
327 + );
328 });
329
330 it('should handle manual connection management', async () => {
@@ -329,11 +348,14 @@ describe('MCP', () => {
348 manuallyManageConnections: true,
349 });
350
332 - expect(mockClient.mcp.generate.url).toHaveBeenCalledWith({
333 - mcp_server_id: 'mcp_123',
334 - user_ids: ['user123'],
335 - managed_auth_by_composio: false,
336 - });
351 + expect(mockClient.mcp.generate.url).toHaveBeenCalledWith(
352 + {
353 + mcp_server_id: 'mcp_123',
354 + user_ids: ['user123'],
355 + managed_auth_by_composio: false,
356 + },
357 + undefined
358 + );
359 });
360
361 it('should validate parameters', async () => {
ts/packages/core/test/models/toolRouter.test.ts
+786 -560
@@ -199,16 +199,19 @@ describe('ToolRouter', () => {
199
200 const session = await toolRouter.create(userId);
201
202 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
203 - user_id: userId,
204 - toolkits: undefined,
205 - auth_configs: undefined,
206 - connected_accounts: undefined,
207 - tools: undefined,
208 - tags: undefined,
209 - manage_connections: createExpectedManageConnections(),
210 - workbench: undefined,
211 - });
202 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
203 + {
204 + user_id: userId,
205 + toolkits: undefined,
206 + auth_configs: undefined,
207 + connected_accounts: undefined,
208 + tools: undefined,
209 + tags: undefined,
210 + manage_connections: createExpectedManageConnections(),
211 + workbench: undefined,
212 + },
213 + undefined
214 + );
215
216 expect(session).toHaveProperty('sessionId', 'session_123');
217 expect(session).toHaveProperty('mcp');
@@ -229,16 +232,19 @@ describe('ToolRouter', () => {
232
233 const session = await toolRouter.create(userId, {});
234
232 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
233 - user_id: userId,
234 - toolkits: undefined,
235 - auth_configs: undefined,
236 - connected_accounts: undefined,
237 - tools: undefined,
238 - tags: undefined,
239 - manage_connections: createExpectedManageConnections(),
240 - workbench: undefined,
241 - });
235 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
236 + {
237 + user_id: userId,
238 + toolkits: undefined,
239 + auth_configs: undefined,
240 + connected_accounts: undefined,
241 + tools: undefined,
242 + tags: undefined,
243 + manage_connections: createExpectedManageConnections(),
244 + workbench: undefined,
245 + },
246 + undefined
247 + );
248
249 expect(session.sessionId).toBe('session_123');
250 expect(session.preload.tools).toEqual([]);
@@ -259,19 +265,22 @@ describe('ToolRouter', () => {
265 preload: { tools: ['GMAIL_FETCH_EMAILS'] },
266 });
267
262 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
263 - user_id: userId,
264 - toolkits: {
265 - enable: ['gmail'],
266 - },
267 - auth_configs: undefined,
268 - connected_accounts: undefined,
269 - tools: undefined,
270 - tags: undefined,
271 - manage_connections: createExpectedManageConnections(),
272 - workbench: undefined,
273 - preload: { tools: ['GMAIL_FETCH_EMAILS'] },
274 - });
268 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
269 + {
270 + user_id: userId,
271 + toolkits: {
272 + enable: ['gmail'],
273 + },
274 + auth_configs: undefined,
275 + connected_accounts: undefined,
276 + tools: undefined,
277 + tags: undefined,
278 + manage_connections: createExpectedManageConnections(),
279 + workbench: undefined,
280 + preload: { tools: ['GMAIL_FETCH_EMAILS'] },
281 + },
282 + undefined
283 + );
284
285 expect(session.preload.tools).toEqual(['GMAIL_FETCH_EMAILS']);
286 expect(session.configVersion).toBe(2);
@@ -291,19 +300,22 @@ describe('ToolRouter', () => {
300 preload: { tools: 'all' },
301 });
302
294 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
295 - user_id: userId,
296 - toolkits: {
297 - enable: ['github'],
298 - },
299 - auth_configs: undefined,
300 - connected_accounts: undefined,
301 - tools: undefined,
302 - tags: undefined,
303 - manage_connections: createExpectedManageConnections(),
304 - workbench: undefined,
305 - preload: { tools: 'all' },
306 - });
303 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
304 + {
305 + user_id: userId,
306 + toolkits: {
307 + enable: ['github'],
308 + },
309 + auth_configs: undefined,
310 + connected_accounts: undefined,
311 + tools: undefined,
312 + tags: undefined,
313 + manage_connections: createExpectedManageConnections(),
314 + workbench: undefined,
315 + preload: { tools: 'all' },
316 + },
317 + undefined
318 + );
319
320 expect(session.preload.tools).toBe('all');
321 });
@@ -338,23 +350,26 @@ describe('ToolRouter', () => {
350 toolkits: ['github'],
351 });
352
341 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
342 - user_id: userId,
343 - toolkits: {
344 - enable: ['github'],
345 - },
346 - auth_configs: undefined,
347 - connected_accounts: undefined,
348 - tools: undefined,
349 - tags: undefined,
350 - manage_connections: { enable: false },
351 - workbench: { enable: false },
352 - multi_account: undefined,
353 - preload: { tools: 'all' },
354 - search: { enable: false },
355 - execute: { enable_multi_execute: false },
356 - experimental: undefined,
357 - });
353 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
354 + {
355 + user_id: userId,
356 + toolkits: {
357 + enable: ['github'],
358 + },
359 + auth_configs: undefined,
360 + connected_accounts: undefined,
361 + tools: undefined,
362 + tags: undefined,
363 + manage_connections: { enable: false },
364 + workbench: { enable: false },
365 + multi_account: undefined,
366 + preload: { tools: 'all' },
367 + search: { enable: false },
368 + execute: { enable_multi_execute: false },
369 + experimental: undefined,
370 + },
371 + undefined
372 + );
373 expect(session.preload.tools).toBe('all');
374 });
375
@@ -374,23 +389,26 @@ describe('ToolRouter', () => {
389 preload: { tools: ['GITHUB_CREATE_ISSUE'] },
390 });
391
377 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
378 - user_id: userId,
379 - toolkits: {
380 - enable: ['github'],
392 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
393 + {
394 + user_id: userId,
395 + toolkits: {
396 + enable: ['github'],
397 + },
398 + auth_configs: undefined,
399 + connected_accounts: undefined,
400 + tools: undefined,
401 + tags: undefined,
402 + manage_connections: { enable: true },
403 + workbench: { enable: true },
404 + multi_account: undefined,
405 + preload: { tools: ['GITHUB_CREATE_ISSUE'] },
406 + search: { enable: false },
407 + execute: { enable_multi_execute: false },
408 + experimental: undefined,
409 },
382 - auth_configs: undefined,
383 - connected_accounts: undefined,
384 - tools: undefined,
385 - tags: undefined,
386 - manage_connections: { enable: true },
387 - workbench: { enable: true },
388 - multi_account: undefined,
389 - preload: { tools: ['GITHUB_CREATE_ISSUE'] },
390 - search: { enable: false },
391 - execute: { enable_multi_execute: false },
392 - experimental: undefined,
393 - });
410 + undefined
411 + );
412 expect(session.preload.tools).toEqual(['GITHUB_CREATE_ISSUE']);
413 });
414
@@ -450,18 +468,21 @@ describe('ToolRouter', () => {
468
469 await toolRouter.create(userId, config);
470
453 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
454 - user_id: userId,
455 - toolkits: {
456 - enable: ['gmail', 'slack', 'github'],
457 - },
458 - auth_configs: undefined,
459 - connected_accounts: undefined,
460 - tools: undefined,
461 - tags: undefined,
462 - manage_connections: createExpectedManageConnections(),
463 - workbench: undefined,
464 - });
471 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
472 + {
473 + user_id: userId,
474 + toolkits: {
475 + enable: ['gmail', 'slack', 'github'],
476 + },
477 + auth_configs: undefined,
478 + connected_accounts: undefined,
479 + tools: undefined,
480 + tags: undefined,
481 + manage_connections: createExpectedManageConnections(),
482 + workbench: undefined,
483 + },
484 + undefined
485 + );
486 });
487
488 it('should create a session with enable toolkits configuration', async () => {
@@ -475,18 +496,21 @@ describe('ToolRouter', () => {
496
497 await toolRouter.create(userId, config);
498
478 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
479 - user_id: userId,
480 - toolkits: {
481 - enable: ['gmail', 'slack'],
482 - },
483 - auth_configs: undefined,
484 - connected_accounts: undefined,
485 - tools: undefined,
486 - tags: undefined,
487 - manage_connections: createExpectedManageConnections(),
488 - workbench: undefined,
489 - });
499 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
500 + {
501 + user_id: userId,
502 + toolkits: {
503 + enable: ['gmail', 'slack'],
504 + },
505 + auth_configs: undefined,
506 + connected_accounts: undefined,
507 + tools: undefined,
508 + tags: undefined,
509 + manage_connections: createExpectedManageConnections(),
510 + workbench: undefined,
511 + },
512 + undefined
513 + );
514 });
515
516 it('should create a session with disable toolkits configuration', async () => {
@@ -500,18 +524,21 @@ describe('ToolRouter', () => {
524
525 await toolRouter.create(userId, config);
526
503 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
504 - user_id: userId,
505 - toolkits: {
506 - disable: ['notion', 'trello'],
507 - },
508 - auth_configs: undefined,
509 - connected_accounts: undefined,
510 - tools: undefined,
511 - tags: undefined,
512 - manage_connections: createExpectedManageConnections(),
513 - workbench: undefined,
514 - });
527 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
528 + {
529 + user_id: userId,
530 + toolkits: {
531 + disable: ['notion', 'trello'],
532 + },
533 + auth_configs: undefined,
534 + connected_accounts: undefined,
535 + tools: undefined,
536 + tags: undefined,
537 + manage_connections: createExpectedManageConnections(),
538 + workbench: undefined,
539 + },
540 + undefined
541 + );
542 });
543 });
544
@@ -525,18 +552,21 @@ describe('ToolRouter', () => {
552
553 await toolRouter.create(userId, config);
554
528 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
529 - user_id: userId,
530 - toolkits: undefined,
531 - auth_configs: undefined,
532 - connected_accounts: undefined,
533 - tools: undefined,
534 - tags: {
535 - enable: ['readOnlyHint', 'idempotentHint'],
555 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
556 + {
557 + user_id: userId,
558 + toolkits: undefined,
559 + auth_configs: undefined,
560 + connected_accounts: undefined,
561 + tools: undefined,
562 + tags: {
563 + enable: ['readOnlyHint', 'idempotentHint'],
564 + },
565 + manage_connections: createExpectedManageConnections(),
566 + workbench: undefined,
567 },
537 - manage_connections: createExpectedManageConnections(),
538 - workbench: undefined,
539 - });
568 + undefined
569 + );
570 });
571
572 it('should create a session with tags object with enable property', async () => {
@@ -550,18 +580,21 @@ describe('ToolRouter', () => {
580
581 await toolRouter.create(userId, config);
582
553 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
554 - user_id: userId,
555 - toolkits: undefined,
556 - auth_configs: undefined,
557 - connected_accounts: undefined,
558 - tools: undefined,
559 - tags: {
560 - enable: ['readOnlyHint', 'idempotentHint'],
583 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
584 + {
585 + user_id: userId,
586 + toolkits: undefined,
587 + auth_configs: undefined,
588 + connected_accounts: undefined,
589 + tools: undefined,
590 + tags: {
591 + enable: ['readOnlyHint', 'idempotentHint'],
592 + },
593 + manage_connections: createExpectedManageConnections(),
594 + workbench: undefined,
595 },
562 - manage_connections: createExpectedManageConnections(),
563 - workbench: undefined,
564 - });
596 + undefined
597 + );
598 });
599
600 it('should create a session with tags object with disable property', async () => {
@@ -575,19 +608,22 @@ describe('ToolRouter', () => {
608
609 await toolRouter.create(userId, config);
610
578 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
579 - user_id: userId,
580 - toolkits: undefined,
581 - auth_configs: undefined,
582 - connected_accounts: undefined,
583 - tools: undefined,
584 - tags: {
585 - enable: undefined,
586 - disable: ['destructiveHint'],
611 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
612 + {
613 + user_id: userId,
614 + toolkits: undefined,
615 + auth_configs: undefined,
616 + connected_accounts: undefined,
617 + tools: undefined,
618 + tags: {
619 + enable: undefined,
620 + disable: ['destructiveHint'],
621 + },
622 + manage_connections: createExpectedManageConnections(),
623 + workbench: undefined,
624 },
588 - manage_connections: createExpectedManageConnections(),
589 - workbench: undefined,
590 - });
625 + undefined
626 + );
627 });
628
629 it('should create a session with tags object with both enable and disable properties', async () => {
@@ -602,19 +638,22 @@ describe('ToolRouter', () => {
638
639 await toolRouter.create(userId, config);
640
605 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
606 - user_id: userId,
607 - toolkits: undefined,
608 - auth_configs: undefined,
609 - connected_accounts: undefined,
610 - tools: undefined,
611 - tags: {
612 - enable: ['readOnlyHint', 'idempotentHint'],
613 - disable: ['destructiveHint'],
641 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
642 + {
643 + user_id: userId,
644 + toolkits: undefined,
645 + auth_configs: undefined,
646 + connected_accounts: undefined,
647 + tools: undefined,
648 + tags: {
649 + enable: ['readOnlyHint', 'idempotentHint'],
650 + disable: ['destructiveHint'],
651 + },
652 + manage_connections: createExpectedManageConnections(),
653 + workbench: undefined,
654 },
615 - manage_connections: createExpectedManageConnections(),
616 - workbench: undefined,
617 - });
655 + undefined
656 + );
657 });
658
659 it('should create a session with single tag in array', async () => {
@@ -626,18 +665,21 @@ describe('ToolRouter', () => {
665
666 await toolRouter.create(userId, config);
667
629 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
630 - user_id: userId,
631 - toolkits: undefined,
632 - auth_configs: undefined,
633 - connected_accounts: undefined,
634 - tools: undefined,
635 - tags: {
636 - enable: ['readOnlyHint'],
668 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
669 + {
670 + user_id: userId,
671 + toolkits: undefined,
672 + auth_configs: undefined,
673 + connected_accounts: undefined,
674 + tools: undefined,
675 + tags: {
676 + enable: ['readOnlyHint'],
677 + },
678 + manage_connections: createExpectedManageConnections(),
679 + workbench: undefined,
680 },
638 - manage_connections: createExpectedManageConnections(),
639 - workbench: undefined,
640 - });
681 + undefined
682 + );
683 });
684
685 it('should create a session with all tag types', async () => {
@@ -649,18 +691,21 @@ describe('ToolRouter', () => {
691
692 await toolRouter.create(userId, config);
693
652 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
653 - user_id: userId,
654 - toolkits: undefined,
655 - auth_configs: undefined,
656 - connected_accounts: undefined,
657 - tools: undefined,
658 - tags: {
659 - enable: ['readOnlyHint', 'destructiveHint', 'idempotentHint', 'openWorldHint'],
694 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
695 + {
696 + user_id: userId,
697 + toolkits: undefined,
698 + auth_configs: undefined,
699 + connected_accounts: undefined,
700 + tools: undefined,
701 + tags: {
702 + enable: ['readOnlyHint', 'destructiveHint', 'idempotentHint', 'openWorldHint'],
703 + },
704 + manage_connections: createExpectedManageConnections(),
705 + workbench: undefined,
706 },
661 - manage_connections: createExpectedManageConnections(),
662 - workbench: undefined,
663 - });
707 + undefined
708 + );
709 });
710
711 it('should create a session with tags combined with toolkits', async () => {
@@ -673,20 +718,23 @@ describe('ToolRouter', () => {
718
719 await toolRouter.create(userId, config);
720
676 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
677 - user_id: userId,
678 - toolkits: {
679 - enable: ['gmail', 'slack'],
680 - },
681 - auth_configs: undefined,
682 - connected_accounts: undefined,
683 - tools: undefined,
684 - tags: {
685 - enable: ['readOnlyHint'],
721 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
722 + {
723 + user_id: userId,
724 + toolkits: {
725 + enable: ['gmail', 'slack'],
726 + },
727 + auth_configs: undefined,
728 + connected_accounts: undefined,
729 + tools: undefined,
730 + tags: {
731 + enable: ['readOnlyHint'],
732 + },
733 + manage_connections: createExpectedManageConnections(),
734 + workbench: undefined,
735 },
687 - manage_connections: createExpectedManageConnections(),
688 - workbench: undefined,
689 - });
736 + undefined
737 + );
738 });
739 });
740
@@ -904,16 +952,19 @@ describe('ToolRouter', () => {
952
953 await toolRouter.create(userId, config);
954
907 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
908 - user_id: userId,
909 - toolkits: undefined,
910 - auth_configs: undefined,
911 - connected_accounts: undefined,
912 - tools: undefined,
913 - tags: undefined,
914 - manage_connections: createExpectedManageConnections({ enable: true }),
915 - workbench: undefined,
916 - });
955 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
956 + {
957 + user_id: userId,
958 + toolkits: undefined,
959 + auth_configs: undefined,
960 + connected_accounts: undefined,
961 + tools: undefined,
962 + tags: undefined,
963 + manage_connections: createExpectedManageConnections({ enable: true }),
964 + workbench: undefined,
965 + },
966 + undefined
967 + );
968 });
969
970 it('should create a session with manageConnections as boolean (false)', async () => {
@@ -925,16 +976,19 @@ describe('ToolRouter', () => {
976
977 await toolRouter.create(userId, config);
978
928 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
929 - user_id: userId,
930 - toolkits: undefined,
931 - auth_configs: undefined,
932 - connected_accounts: undefined,
933 - tools: undefined,
934 - tags: undefined,
935 - manage_connections: createExpectedManageConnections({ enable: false }),
936 - workbench: undefined,
937 - });
979 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
980 + {
981 + user_id: userId,
982 + toolkits: undefined,
983 + auth_configs: undefined,
984 + connected_accounts: undefined,
985 + tools: undefined,
986 + tags: undefined,
987 + manage_connections: createExpectedManageConnections({ enable: false }),
988 + workbench: undefined,
989 + },
990 + undefined
991 + );
992 });
993
994 it('should create a session with manageConnections as object with enable', async () => {
@@ -948,16 +1002,19 @@ describe('ToolRouter', () => {
1002
1003 await toolRouter.create(userId, config);
1004
951 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
952 - user_id: userId,
953 - toolkits: undefined,
954 - auth_configs: undefined,
955 - connected_accounts: undefined,
956 - tools: undefined,
957 - tags: undefined,
958 - manage_connections: createExpectedManageConnections({ enable: true }),
959 - workbench: undefined,
960 - });
1005 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1006 + {
1007 + user_id: userId,
1008 + toolkits: undefined,
1009 + auth_configs: undefined,
1010 + connected_accounts: undefined,
1011 + tools: undefined,
1012 + tags: undefined,
1013 + manage_connections: createExpectedManageConnections({ enable: true }),
1014 + workbench: undefined,
1015 + },
1016 + undefined
1017 + );
1018 });
1019
1020 it('should create a session with manageConnections object with callbackUrl', async () => {
@@ -972,19 +1029,22 @@ describe('ToolRouter', () => {
1029
1030 await toolRouter.create(userId, config);
1031
975 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
976 - user_id: userId,
977 - toolkits: undefined,
978 - auth_configs: undefined,
979 - connected_accounts: undefined,
980 - tools: undefined,
981 - tags: undefined,
982 - manage_connections: createExpectedManageConnections({
983 - enable: true,
984 - callbackUrl: 'https://myapp.com/callback',
985 - }),
986 - workbench: undefined,
987 - });
1032 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1033 + {
1034 + user_id: userId,
1035 + toolkits: undefined,
1036 + auth_configs: undefined,
1037 + connected_accounts: undefined,
1038 + tools: undefined,
1039 + tags: undefined,
1040 + manage_connections: createExpectedManageConnections({
1041 + enable: true,
1042 + callbackUrl: 'https://myapp.com/callback',
1043 + }),
1044 + workbench: undefined,
1045 + },
1046 + undefined
1047 + );
1048 });
1049
1050 it('should create a session with full manageConnections configuration', async () => {
@@ -999,19 +1059,22 @@ describe('ToolRouter', () => {
1059
1060 await toolRouter.create(userId, config);
1061
1002 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1003 - user_id: userId,
1004 - toolkits: undefined,
1005 - auth_configs: undefined,
1006 - connected_accounts: undefined,
1007 - tools: undefined,
1008 - tags: undefined,
1009 - manage_connections: createExpectedManageConnections({
1010 - enable: true,
1011 - callbackUrl: 'https://myapp.com/callback',
1012 - }),
1013 - workbench: undefined,
1014 - });
1062 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1063 + {
1064 + user_id: userId,
1065 + toolkits: undefined,
1066 + auth_configs: undefined,
1067 + connected_accounts: undefined,
1068 + tools: undefined,
1069 + tags: undefined,
1070 + manage_connections: createExpectedManageConnections({
1071 + enable: true,
1072 + callbackUrl: 'https://myapp.com/callback',
1073 + }),
1074 + workbench: undefined,
1075 + },
1076 + undefined
1077 + );
1078 });
1079 });
1080
@@ -1028,19 +1091,22 @@ describe('ToolRouter', () => {
1091
1092 await toolRouter.create(userId, config);
1093
1031 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1032 - user_id: userId,
1033 - toolkits: undefined,
1034 - auth_configs: {
1035 - gmail: 'auth_config_123',
1036 - slack: 'auth_config_456',
1094 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1095 + {
1096 + user_id: userId,
1097 + toolkits: undefined,
1098 + auth_configs: {
1099 + gmail: 'auth_config_123',
1100 + slack: 'auth_config_456',
1101 + },
1102 + connected_accounts: undefined,
1103 + tools: undefined,
1104 + tags: undefined,
1105 + manage_connections: createExpectedManageConnections(),
1106 + workbench: undefined,
1107 },
1038 - connected_accounts: undefined,
1039 - tools: undefined,
1040 - tags: undefined,
1041 - manage_connections: createExpectedManageConnections(),
1042 - workbench: undefined,
1043 - });
1108 + undefined
1109 + );
1110 });
1111
1112 it('should create a session with connectedAccounts (string coerced to array)', async () => {
@@ -1055,19 +1121,22 @@ describe('ToolRouter', () => {
1121
1122 await toolRouter.create(userId, config);
1123
1058 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1059 - user_id: userId,
1060 - toolkits: undefined,
1061 - auth_configs: undefined,
1062 - connected_accounts: {
1063 - gmail: ['conn_123'],
1064 - slack: ['conn_456'],
1124 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1125 + {
1126 + user_id: userId,
1127 + toolkits: undefined,
1128 + auth_configs: undefined,
1129 + connected_accounts: {
1130 + gmail: ['conn_123'],
1131 + slack: ['conn_456'],
1132 + },
1133 + tools: undefined,
1134 + tags: undefined,
1135 + manage_connections: createExpectedManageConnections(),
1136 + workbench: undefined,
1137 },
1066 - tools: undefined,
1067 - tags: undefined,
1068 - manage_connections: createExpectedManageConnections(),
1069 - workbench: undefined,
1070 - });
1138 + undefined
1139 + );
1140 });
1141
1142 it('should create a session with both authConfigs and connectedAccounts', async () => {
@@ -1084,20 +1153,23 @@ describe('ToolRouter', () => {
1153
1154 await toolRouter.create(userId, config);
1155
1087 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1088 - user_id: userId,
1089 - toolkits: undefined,
1090 - auth_configs: {
1091 - gmail: 'auth_config_123',
1092 - },
1093 - connected_accounts: {
1094 - slack: ['conn_456'],
1156 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1157 + {
1158 + user_id: userId,
1159 + toolkits: undefined,
1160 + auth_configs: {
1161 + gmail: 'auth_config_123',
1162 + },
1163 + connected_accounts: {
1164 + slack: ['conn_456'],
1165 + },
1166 + tools: undefined,
1167 + tags: undefined,
1168 + manage_connections: createExpectedManageConnections(),
1169 + workbench: undefined,
1170 },
1096 - tools: undefined,
1097 - tags: undefined,
1098 - manage_connections: createExpectedManageConnections(),
1099 - workbench: undefined,
1100 - });
1171 + undefined
1172 + );
1173 });
1174 });
1175
@@ -1113,20 +1185,23 @@ describe('ToolRouter', () => {
1185
1186 await toolRouter.create(userId, config);
1187
1116 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1117 - user_id: userId,
1118 - toolkits: undefined,
1119 - auth_configs: undefined,
1120 - connected_accounts: undefined,
1121 - tools: undefined,
1122 - tags: undefined,
1123 - manage_connections: createExpectedManageConnections(),
1124 - workbench: {
1125 - enable: true,
1126 - enable_proxy_execution: true,
1127 - auto_offload_threshold: undefined,
1188 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1189 + {
1190 + user_id: userId,
1191 + toolkits: undefined,
1192 + auth_configs: undefined,
1193 + connected_accounts: undefined,
1194 + tools: undefined,
1195 + tags: undefined,
1196 + manage_connections: createExpectedManageConnections(),
1197 + workbench: {
1198 + enable: true,
1199 + enable_proxy_execution: true,
1200 + auto_offload_threshold: undefined,
1201 + },
1202 },
1129 - });
1203 + undefined
1204 + );
1205 });
1206
1207 it('should create a session with autoOffloadThreshold only', async () => {
@@ -1140,20 +1215,23 @@ describe('ToolRouter', () => {
1215
1216 await toolRouter.create(userId, config);
1217
1143 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1144 - user_id: userId,
1145 - toolkits: undefined,
1146 - auth_configs: undefined,
1147 - connected_accounts: undefined,
1148 - tools: undefined,
1149 - tags: undefined,
1150 - manage_connections: createExpectedManageConnections(),
1151 - workbench: {
1152 - enable: true,
1153 - enable_proxy_execution: undefined,
1154 - auto_offload_threshold: 1000,
1218 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1219 + {
1220 + user_id: userId,
1221 + toolkits: undefined,
1222 + auth_configs: undefined,
1223 + connected_accounts: undefined,
1224 + tools: undefined,
1225 + tags: undefined,
1226 + manage_connections: createExpectedManageConnections(),
1227 + workbench: {
1228 + enable: true,
1229 + enable_proxy_execution: undefined,
1230 + auto_offload_threshold: 1000,
1231 + },
1232 },
1156 - });
1233 + undefined
1234 + );
1235 });
1236
1237 it('should create a session with full workbench configuration', async () => {
@@ -1168,20 +1246,23 @@ describe('ToolRouter', () => {
1246
1247 await toolRouter.create(userId, config);
1248
1171 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1172 - user_id: userId,
1173 - toolkits: undefined,
1174 - auth_configs: undefined,
1175 - connected_accounts: undefined,
1176 - tools: undefined,
1177 - tags: undefined,
1178 - manage_connections: createExpectedManageConnections(),
1179 - workbench: {
1180 - enable: true,
1181 - enable_proxy_execution: true,
1182 - auto_offload_threshold: 500,
1249 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1250 + {
1251 + user_id: userId,
1252 + toolkits: undefined,
1253 + auth_configs: undefined,
1254 + connected_accounts: undefined,
1255 + tools: undefined,
1256 + tags: undefined,
1257 + manage_connections: createExpectedManageConnections(),
1258 + workbench: {
1259 + enable: true,
1260 + enable_proxy_execution: true,
1261 + auto_offload_threshold: 500,
1262 + },
1263 },
1184 - });
1264 + undefined
1265 + );
1266 });
1267
1268 it('should create a session with workbench proxy and offload disabled', async () => {
@@ -1196,20 +1277,23 @@ describe('ToolRouter', () => {
1277
1278 await toolRouter.create(userId, config);
1279
1199 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1200 - user_id: userId,
1201 - toolkits: undefined,
1202 - auth_configs: undefined,
1203 - connected_accounts: undefined,
1204 - tools: undefined,
1205 - tags: undefined,
1206 - manage_connections: createExpectedManageConnections(),
1207 - workbench: {
1208 - enable: true,
1209 - enable_proxy_execution: false,
1210 - auto_offload_threshold: 0,
1280 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1281 + {
1282 + user_id: userId,
1283 + toolkits: undefined,
1284 + auth_configs: undefined,
1285 + connected_accounts: undefined,
1286 + tools: undefined,
1287 + tags: undefined,
1288 + manage_connections: createExpectedManageConnections(),
1289 + workbench: {
1290 + enable: true,
1291 + enable_proxy_execution: false,
1292 + auto_offload_threshold: 0,
1293 + },
1294 },
1212 - });
1295 + undefined
1296 + );
1297 });
1298
1299 it('should create a session with workbench entirely disabled', async () => {
@@ -1223,20 +1307,23 @@ describe('ToolRouter', () => {
1307
1308 await toolRouter.create(userId, config);
1309
1226 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1227 - user_id: userId,
1228 - toolkits: undefined,
1229 - auth_configs: undefined,
1230 - connected_accounts: undefined,
1231 - tools: undefined,
1232 - tags: undefined,
1233 - manage_connections: createExpectedManageConnections(),
1234 - workbench: {
1235 - enable: false,
1236 - enable_proxy_execution: undefined,
1237 - auto_offload_threshold: undefined,
1310 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1311 + {
1312 + user_id: userId,
1313 + toolkits: undefined,
1314 + auth_configs: undefined,
1315 + connected_accounts: undefined,
1316 + tools: undefined,
1317 + tags: undefined,
1318 + manage_connections: createExpectedManageConnections(),
1319 + workbench: {
1320 + enable: false,
1321 + enable_proxy_execution: undefined,
1322 + auto_offload_threshold: undefined,
1323 + },
1324 },
1239 - });
1325 + undefined
1326 + );
1327 });
1328
1329 it('should create a session with workbench explicitly enabled', async () => {
@@ -1252,20 +1339,23 @@ describe('ToolRouter', () => {
1339
1340 await toolRouter.create(userId, config);
1341
1255 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1256 - user_id: userId,
1257 - toolkits: undefined,
1258 - auth_configs: undefined,
1259 - connected_accounts: undefined,
1260 - tools: undefined,
1261 - tags: undefined,
1262 - manage_connections: createExpectedManageConnections(),
1263 - workbench: {
1264 - enable: true,
1265 - enable_proxy_execution: true,
1266 - auto_offload_threshold: 20000,
1342 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1343 + {
1344 + user_id: userId,
1345 + toolkits: undefined,
1346 + auth_configs: undefined,
1347 + connected_accounts: undefined,
1348 + tools: undefined,
1349 + tags: undefined,
1350 + manage_connections: createExpectedManageConnections(),
1351 + workbench: {
1352 + enable: true,
1353 + enable_proxy_execution: true,
1354 + auto_offload_threshold: 20000,
1355 + },
1356 },
1268 - });
1357 + undefined
1358 + );
1359 });
1360
1361 it('forwards sandboxSize as snake_case sandbox_size on the wire', async () => {
@@ -1457,7 +1547,8 @@ describe('ToolRouter', () => {
1547 max_accounts_per_toolkit: undefined,
1548 require_explicit_selection: true,
1549 },
1460 - })
1550 + }),
1551 + undefined
1552 );
1553 });
1554
@@ -1482,7 +1573,8 @@ describe('ToolRouter', () => {
1573 max_accounts_per_toolkit: 3,
1574 require_explicit_selection: true,
1575 },
1485 - })
1576 + }),
1577 + undefined
1578 );
1579 });
1580
@@ -1517,7 +1609,8 @@ describe('ToolRouter', () => {
1609 max_accounts_per_toolkit: 5,
1610 require_explicit_selection: true,
1611 },
1520 - })
1612 + }),
1613 + undefined
1614 );
1615 });
1616 });
@@ -1536,21 +1629,24 @@ describe('ToolRouter', () => {
1629
1630 await toolRouter.create(userId, config);
1631
1539 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1540 - user_id: userId,
1541 - toolkits: undefined,
1542 - auth_configs: undefined,
1543 - connected_accounts: undefined,
1544 - tools: undefined,
1545 - tags: undefined,
1546 - manage_connections: createExpectedManageConnections(),
1547 - workbench: undefined,
1548 - experimental: {
1549 - assistive_prompt_config: {
1550 - user_timezone: 'America/New_York',
1632 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1633 + {
1634 + user_id: userId,
1635 + toolkits: undefined,
1636 + auth_configs: undefined,
1637 + connected_accounts: undefined,
1638 + tools: undefined,
1639 + tags: undefined,
1640 + manage_connections: createExpectedManageConnections(),
1641 + workbench: undefined,
1642 + experimental: {
1643 + assistive_prompt_config: {
1644 + user_timezone: 'America/New_York',
1645 + },
1646 },
1647 },
1553 - });
1648 + undefined
1649 + );
1650 });
1651
1652 it('should not include experimental in payload when assistivePrompt is not provided', async () => {
@@ -1562,17 +1658,20 @@ describe('ToolRouter', () => {
1658
1659 await toolRouter.create(userId, config);
1660
1565 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1566 - user_id: userId,
1567 - toolkits: undefined,
1568 - auth_configs: undefined,
1569 - connected_accounts: undefined,
1570 - tools: undefined,
1571 - tags: undefined,
1572 - manage_connections: createExpectedManageConnections(),
1573 - workbench: undefined,
1574 - experimental: undefined,
1575 - });
1661 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1662 + {
1663 + user_id: userId,
1664 + toolkits: undefined,
1665 + auth_configs: undefined,
1666 + connected_accounts: undefined,
1667 + tools: undefined,
1668 + tags: undefined,
1669 + manage_connections: createExpectedManageConnections(),
1670 + workbench: undefined,
1671 + experimental: undefined,
1672 + },
1673 + undefined
1674 + );
1675 });
1676
1677 it('should not include experimental in payload when userTimezone is not provided', async () => {
@@ -1586,17 +1685,20 @@ describe('ToolRouter', () => {
1685
1686 await toolRouter.create(userId, config);
1687
1589 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1590 - user_id: userId,
1591 - toolkits: undefined,
1592 - auth_configs: undefined,
1593 - connected_accounts: undefined,
1594 - tools: undefined,
1595 - tags: undefined,
1596 - manage_connections: createExpectedManageConnections(),
1597 - workbench: undefined,
1598 - experimental: undefined,
1599 - });
1688 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1689 + {
1690 + user_id: userId,
1691 + toolkits: undefined,
1692 + auth_configs: undefined,
1693 + connected_accounts: undefined,
1694 + tools: undefined,
1695 + tags: undefined,
1696 + manage_connections: createExpectedManageConnections(),
1697 + workbench: undefined,
1698 + experimental: undefined,
1699 + },
1700 + undefined
1701 + );
1702 });
1703
1704 it('should create a session with experimental config combined with other options', async () => {
@@ -1613,23 +1715,26 @@ describe('ToolRouter', () => {
1715
1716 await toolRouter.create(userId, config);
1717
1616 - expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith({
1617 - user_id: userId,
1618 - toolkits: {
1619 - enable: ['gmail', 'slack'],
1620 - },
1621 - auth_configs: undefined,
1622 - connected_accounts: undefined,
1623 - tools: undefined,
1624 - tags: undefined,
1625 - manage_connections: createExpectedManageConnections(),
1626 - workbench: undefined,
1627 - experimental: {
1628 - assistive_prompt_config: {
1629 - user_timezone: 'Europe/London',
1718 + expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1719 + {
1720 + user_id: userId,
1721 + toolkits: {
1722 + enable: ['gmail', 'slack'],
1723 + },
1724 + auth_configs: undefined,
1725 + connected_accounts: undefined,
1726 + tools: undefined,
1727 + tags: undefined,
1728 + manage_connections: createExpectedManageConnections(),
1729 + workbench: undefined,
1730 + experimental: {
1731 + assistive_prompt_config: {
1732 + user_timezone: 'Europe/London',
1733 + },
1734 },
1735 },
1632 - });
1736 + undefined
1737 + );
1738 });
1739
1740 it('should transform experimental assistive_prompt from API response to SDK format', async () => {
@@ -1698,7 +1803,8 @@ describe('ToolRouter', () => {
1803 expect(mockClient.toolRouter.session.create).toHaveBeenCalledWith(
1804 expect.objectContaining({
1805 user_id: '',
1701 - })
1806 + }),
1807 + undefined
1808 );
1809 });
1810 });
@@ -1770,9 +1876,13 @@ describe('ToolRouter', () => {
1876 const session = await toolRouter.create(userId);
1877 const connectionRequest = await session.authorize(toolkit);
1878
1773 - expect(mockClient.toolRouter.session.link).toHaveBeenCalledWith(sessionId, {
1774 - toolkit,
1775 - });
1879 + expect(mockClient.toolRouter.session.link).toHaveBeenCalledWith(
1880 + sessionId,
1881 + {
1882 + toolkit,
1883 + },
1884 + undefined
1885 + );
1886
1887 expect(connectionRequest).toHaveProperty('id', 'conn_456');
1888 expect(connectionRequest).toHaveProperty('status', ConnectedAccountStatuses.INITIATED);
@@ -1787,10 +1897,14 @@ describe('ToolRouter', () => {
1897 callbackUrl: 'https://myapp.com/callback',
1898 });
1899
1790 - expect(mockClient.toolRouter.session.link).toHaveBeenCalledWith(sessionId, {
1791 - toolkit,
1792 - callback_url: 'https://myapp.com/callback',
1793 - });
1900 + expect(mockClient.toolRouter.session.link).toHaveBeenCalledWith(
1901 + sessionId,
1902 + {
1903 + toolkit,
1904 + callback_url: 'https://myapp.com/callback',
1905 + },
1906 + undefined
1907 + );
1908
1909 expect(connectionRequest.id).toBe('conn_456');
1910 expect(connectionRequest.redirectUrl).toBe('https://composio.dev/auth/redirect');
@@ -1826,9 +1940,13 @@ describe('ToolRouter', () => {
1940 'Authorization failed: Invalid toolkit'
1941 );
1942
1829 - expect(mockClient.toolRouter.session.link).toHaveBeenCalledWith(sessionId, {
1830 - toolkit,
1831 - });
1943 + expect(mockClient.toolRouter.session.link).toHaveBeenCalledWith(
1944 + sessionId,
1945 + {
1946 + toolkit,
1947 + },
1948 + undefined
1949 + );
1950 });
1951
1952 it('should handle network errors during authorization', async () => {
@@ -1869,16 +1987,20 @@ describe('ToolRouter', () => {
1987 },
1988 });
1989
1872 - expect(mockClient.toolRouter.session.link).toHaveBeenCalledWith(sessionId, {
1873 - toolkit,
1874 - experimental: {
1875 - account_type: 'SHARED',
1876 - acl_config_for_shared: {
1877 - allow_all_users: true,
1878 - not_allowed_user_ids: ['user_bob'],
1990 + expect(mockClient.toolRouter.session.link).toHaveBeenCalledWith(
1991 + sessionId,
1992 + {
1993 + toolkit,
1994 + experimental: {
1995 + account_type: 'SHARED',
1996 + acl_config_for_shared: {
1997 + allow_all_users: true,
1998 + not_allowed_user_ids: ['user_bob'],
1999 + },
2000 },
2001 },
1881 - });
2002 + undefined
2003 + );
2004 });
2005
2006 it('omits the experimental block entirely when not provided', async () => {
@@ -1953,12 +2075,16 @@ describe('ToolRouter', () => {
2075 const session = await toolRouter.create(userId);
2076 const result = await session.toolkits();
2077
1956 - expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(sessionId, {
1957 - cursor: undefined,
1958 - limit: undefined,
1959 - toolkits: undefined,
1960 - is_connected: undefined,
1961 - });
2078 + expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(
2079 + sessionId,
2080 + {
2081 + cursor: undefined,
2082 + limit: undefined,
2083 + toolkits: undefined,
2084 + is_connected: undefined,
2085 + },
2086 + undefined
2087 + );
2088
2089 expect(result).toHaveProperty('items');
2090 expect(result).toHaveProperty('cursor', 'cursor_789');
@@ -1975,12 +2101,16 @@ describe('ToolRouter', () => {
2101 cursor: 'cursor_abc',
2102 });
2103
1978 - expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(sessionId, {
1979 - cursor: 'cursor_abc',
1980 - limit: 10,
1981 - toolkits: undefined,
1982 - is_connected: undefined,
1983 - });
2104 + expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(
2105 + sessionId,
2106 + {
2107 + cursor: 'cursor_abc',
2108 + limit: 10,
2109 + toolkits: undefined,
2110 + is_connected: undefined,
2111 + },
2112 + undefined
2113 + );
2114
2115 expect(result.items).toHaveLength(3);
2116 });
@@ -1993,12 +2123,16 @@ describe('ToolRouter', () => {
2123 toolkits: ['gmail', 'slack'],
2124 });
2125
1996 - expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(sessionId, {
1997 - cursor: undefined,
1998 - limit: undefined,
1999 - toolkits: ['gmail', 'slack'],
2000 - is_connected: undefined,
2001 - });
2126 + expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(
2127 + sessionId,
2128 + {
2129 + cursor: undefined,
2130 + limit: undefined,
2131 + toolkits: ['gmail', 'slack'],
2132 + is_connected: undefined,
2133 + },
2134 + undefined
2135 + );
2136
2137 expect(result.items).toHaveLength(3);
2138 });
@@ -2011,12 +2145,16 @@ describe('ToolRouter', () => {
2145 isConnected: true,
2146 });
2147
2014 - expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(sessionId, {
2015 - cursor: undefined,
2016 - limit: undefined,
2017 - toolkits: undefined,
2018 - is_connected: true,
2019 - });
2148 + expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(
2149 + sessionId,
2150 + {
2151 + cursor: undefined,
2152 + limit: undefined,
2153 + toolkits: undefined,
2154 + is_connected: true,
2155 + },
2156 + undefined
2157 + );
2158
2159 expect(result.items).toHaveLength(3);
2160 });
@@ -2031,12 +2169,16 @@ describe('ToolRouter', () => {
2169 toolkits: ['github'],
2170 });
2171
2034 - expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(sessionId, {
2035 - cursor: 'cursor_xyz',
2036 - limit: 5,
2037 - toolkits: ['github'],
2038 - is_connected: undefined,
2039 - });
2172 + expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(
2173 + sessionId,
2174 + {
2175 + cursor: 'cursor_xyz',
2176 + limit: 5,
2177 + toolkits: ['github'],
2178 + is_connected: undefined,
2179 + },
2180 + undefined
2181 + );
2182
2183 expect(result.items).toHaveLength(3);
2184 });
@@ -2052,12 +2194,16 @@ describe('ToolRouter', () => {
2194 isConnected: false,
2195 });
2196
2055 - expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(sessionId, {
2056 - cursor: 'cursor_xyz',
2057 - limit: 5,
2058 - toolkits: ['github', 'gmail'],
2059 - is_connected: false,
2060 - });
2197 + expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(
2198 + sessionId,
2199 + {
2200 + cursor: 'cursor_xyz',
2201 + limit: 5,
2202 + toolkits: ['github', 'gmail'],
2203 + is_connected: false,
2204 + },
2205 + undefined
2206 + );
2207
2208 expect(result.items).toHaveLength(3);
2209 });
@@ -2289,9 +2435,13 @@ describe('ToolRouter', () => {
2435 const session = await toolRouter.create(userId);
2436 const result = await session.search({ query: 'send emails' });
2437
2292 - expect(mockClient.toolRouter.session.search).toHaveBeenCalledWith(sessionId, {
2293 - queries: [{ use_case: 'send emails' }],
2294 - });
2438 + expect(mockClient.toolRouter.session.search).toHaveBeenCalledWith(
2439 + sessionId,
2440 + {
2441 + queries: [{ use_case: 'send emails' }],
2442 + },
2443 + undefined
2444 + );
2445 expect(result.success).toBe(true);
2446 expect(result.results[0].useCase).toBe('send emails');
2447 expect(result.results[0].primaryToolSlugs).toEqual(['GMAIL_SEND_EMAIL']);
@@ -2308,10 +2458,14 @@ describe('ToolRouter', () => {
2458 const session = await toolRouter.create(userId);
2459 await session.search({ query: 'send emails', toolkits: ['gmail', 'slack'] });
2460
2311 - expect(mockClient.toolRouter.session.search).toHaveBeenCalledWith(sessionId, {
2312 - queries: [{ use_case: 'send emails' }],
2313 - toolkits: ['gmail', 'slack'],
2314 - });
2461 + expect(mockClient.toolRouter.session.search).toHaveBeenCalledWith(
2462 + sessionId,
2463 + {
2464 + queries: [{ use_case: 'send emails' }],
2465 + toolkits: ['gmail', 'slack'],
2466 + },
2467 + undefined
2468 + );
2469 });
2470
2471 it('should pass inline custom tools to search', async () => {
@@ -2341,17 +2495,21 @@ describe('ToolRouter', () => {
2495 });
2496 await session.search({ query: 'search local text' });
2497
2344 - expect(mockClient.toolRouter.session.search).toHaveBeenCalledWith(sessionId, {
2345 - queries: [{ use_case: 'search local text' }],
2346 - experimental: {
2347 - custom_tools: [
2348 - expect.objectContaining({
2349 - slug: 'GREP',
2350 - preload: true,
2351 - }),
2352 - ],
2498 + expect(mockClient.toolRouter.session.search).toHaveBeenCalledWith(
2499 + sessionId,
2500 + {
2501 + queries: [{ use_case: 'search local text' }],
2502 + experimental: {
2503 + custom_tools: [
2504 + expect.objectContaining({
2505 + slug: 'GREP',
2506 + preload: true,
2507 + }),
2508 + ],
2509 + },
2510 },
2354 - });
2511 + undefined
2512 + );
2513 });
2514
2515 it('should propagate search API errors', async () => {
@@ -2385,10 +2543,14 @@ describe('ToolRouter', () => {
2543 body: 'Hello',
2544 });
2545
2388 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
2389 - tool_slug: 'GMAIL_SEND_EMAIL',
2390 - arguments: { to: 'user@example.com', subject: 'Hi', body: 'Hello' },
2391 - });
2546 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
2547 + sessionId,
2548 + {
2549 + tool_slug: 'GMAIL_SEND_EMAIL',
2550 + arguments: { to: 'user@example.com', subject: 'Hi', body: 'Hello' },
2551 + },
2552 + undefined
2553 + );
2554 expect(result.data).toEqual({ tool_slug: 'GMAIL_SEND_EMAIL', id: 'msg_123' });
2555 expect(result.error).toBeNull();
2556 expect(result.logId).toBe('log_abc');
@@ -2410,10 +2572,14 @@ describe('ToolRouter', () => {
2572 const session = await toolRouter.create(userId);
2573 await session.execute('HACKERNEWS_GET_USER');
2574
2413 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
2414 - tool_slug: 'HACKERNEWS_GET_USER',
2415 - arguments: {},
2416 - });
2575 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
2576 + sessionId,
2577 + {
2578 + tool_slug: 'HACKERNEWS_GET_USER',
2579 + arguments: {},
2580 + },
2581 + undefined
2582 + );
2583 });
2584
2585 it('should pass account option to session execute', async () => {
@@ -2423,11 +2589,15 @@ describe('ToolRouter', () => {
2589 const session = await toolRouter.create(userId);
2590 await session.execute('GMAIL_SEND_EMAIL', { to: 'user@example.com' }, { account: 'work' });
2591
2426 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
2427 - tool_slug: 'GMAIL_SEND_EMAIL',
2428 - arguments: { to: 'user@example.com' },
2429 - account: 'work',
2430 - });
2592 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
2593 + sessionId,
2594 + {
2595 + tool_slug: 'GMAIL_SEND_EMAIL',
2596 + arguments: { to: 'user@example.com' },
2597 + account: 'work',
2598 + },
2599 + undefined
2600 + );
2601 });
2602
2603 it('should pass inline custom tools to remote execute when custom tools are bound', async () => {
@@ -2456,13 +2626,17 @@ describe('ToolRouter', () => {
2626 });
2627 await session.execute('GMAIL_SEND_EMAIL', { to: 'user@example.com' });
2628
2459 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
2460 - tool_slug: 'GMAIL_SEND_EMAIL',
2461 - arguments: { to: 'user@example.com' },
2462 - experimental: {
2463 - custom_tools: [expect.objectContaining({ slug: 'GREP' })],
2629 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
2630 + sessionId,
2631 + {
2632 + tool_slug: 'GMAIL_SEND_EMAIL',
2633 + arguments: { to: 'user@example.com' },
2634 + experimental: {
2635 + custom_tools: [expect.objectContaining({ slug: 'GREP' })],
2636 + },
2637 },
2465 - });
2638 + undefined
2639 + );
2640 });
2641 });
2642
@@ -2496,7 +2670,11 @@ describe('ToolRouter', () => {
2670 });
2671
2672 const toolsInstance = (Tools as any).mock.results[0].value;
2499 - expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(sessionId, undefined);
2673 + expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
2674 + sessionId,
2675 + undefined,
2676 + undefined
2677 + );
2678 expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
2679 sessionId,
2680 [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
@@ -2521,9 +2699,11 @@ describe('ToolRouter', () => {
2699 const tools = await session.tools(modifiers);
2700
2701 const toolsInstance = (Tools as any).mock.results[0].value;
2524 - expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(sessionId, {
2525 - modifySchema: modifiers.modifySchema,
2526 - });
2702 + expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
2703 + sessionId,
2704 + { modifySchema: modifiers.modifySchema },
2705 + undefined
2706 + );
2707 expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
2708 sessionId,
2709 [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
@@ -2853,9 +3033,11 @@ describe('ToolRouter', () => {
3033 expect(Tools).toHaveBeenCalledTimes(2);
3034
3035 const firstToolsInstance = (Tools as any).mock.results[0].value;
2856 - expect(firstToolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(sessionId, {
2857 - modifySchema: modifier1.modifySchema,
2858 - });
3036 + expect(firstToolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
3037 + sessionId,
3038 + { modifySchema: modifier1.modifySchema },
3039 + undefined
3040 + );
3041 expect(firstToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
3042 sessionId,
3043 [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
@@ -2863,9 +3045,11 @@ describe('ToolRouter', () => {
3045 );
3046
3047 const secondToolsInstance = (Tools as any).mock.results[1].value;
2866 - expect(secondToolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(sessionId, {
2867 - modifySchema: modifier2.modifySchema,
2868 - });
3048 + expect(secondToolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
3049 + sessionId,
3050 + { modifySchema: modifier2.modifySchema },
3051 + undefined
3052 + );
3053 expect(secondToolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
3054 sessionId,
3055 [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
@@ -2892,6 +3076,7 @@ describe('ToolRouter', () => {
3076 const toolsInstance = (Tools as any).mock.results[0].value;
3077 expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
3078 'custom_session_123',
3079 + undefined,
3080 undefined
3081 );
3082 expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
@@ -2920,6 +3105,7 @@ describe('ToolRouter', () => {
3105 const toolsInstance = (Tools as any).mock.results[0].value;
3106 expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
3107 'empty_session_123',
3108 + undefined,
3109 undefined
3110 );
3111 expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
@@ -2991,18 +3177,26 @@ describe('ToolRouter', () => {
3177 await session1.toolkits();
3178 await session2.toolkits();
3179
2994 - expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith('session_1', {
2995 - cursor: undefined,
2996 - limit: undefined,
2997 - toolkits: undefined,
2998 - is_connected: undefined,
2999 - });
3000 - expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith('session_2', {
3001 - cursor: undefined,
3002 - limit: undefined,
3003 - toolkits: undefined,
3004 - is_connected: undefined,
3005 - });
3180 + expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(
3181 + 'session_1',
3182 + {
3183 + cursor: undefined,
3184 + limit: undefined,
3185 + toolkits: undefined,
3186 + is_connected: undefined,
3187 + },
3188 + undefined
3189 + );
3190 + expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(
3191 + 'session_2',
3192 + {
3193 + cursor: undefined,
3194 + limit: undefined,
3195 + toolkits: undefined,
3196 + is_connected: undefined,
3197 + },
3198 + undefined
3199 + );
3200 });
3201
3202 it('should handle rapid successive calls', async () => {
@@ -3033,7 +3227,7 @@ describe('ToolRouter', () => {
3227
3228 const session = await toolRouter.use(sessionId);
3229
3036 - expect(mockClient.toolRouter.session.retrieve).toHaveBeenCalledWith(sessionId);
3230 + expect(mockClient.toolRouter.session.retrieve).toHaveBeenCalledWith(sessionId, undefined);
3231 expect(mockClient.toolRouter.session.attach).not.toHaveBeenCalled();
3232 expect(mockClient.post).not.toHaveBeenCalled();
3233 expect(session).toHaveProperty('sessionId', 'session_123');
@@ -3075,11 +3269,15 @@ describe('ToolRouter', () => {
3269
3270 const session = await toolRouter.use(sessionId, { customTools: [grepTool] });
3271
3078 - expect(mockClient.toolRouter.session.attach).toHaveBeenCalledWith(sessionId, {
3079 - experimental: {
3080 - custom_tools: [expect.objectContaining({ slug: 'GREP' })],
3272 + expect(mockClient.toolRouter.session.attach).toHaveBeenCalledWith(
3273 + sessionId,
3274 + {
3275 + experimental: {
3276 + custom_tools: [expect.objectContaining({ slug: 'GREP' })],
3277 + },
3278 },
3082 - });
3279 + undefined
3280 + );
3281 expect(mockClient.toolRouter.session.attach.mock.calls[0][1].experimental).not.toHaveProperty(
3282 'custom_toolkits'
3283 );
@@ -3122,7 +3320,11 @@ describe('ToolRouter', () => {
3320 expect(Tools).toHaveBeenCalled();
3321
3322 const toolsInstance = (Tools as any).mock.results[0].value;
3125 - expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(sessionId, undefined);
3323 + expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
3324 + sessionId,
3325 + undefined,
3326 + undefined
3327 + );
3328 expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
3329 sessionId,
3330 [{ slug: 'COMPOSIO_SEARCH_TOOLS' }],
@@ -3138,9 +3340,13 @@ describe('ToolRouter', () => {
3340
3341 const connectionRequest = await session.authorize('github');
3342
3141 - expect(mockClient.toolRouter.session.link).toHaveBeenCalledWith(sessionId, {
3142 - toolkit: 'github',
3143 - });
3343 + expect(mockClient.toolRouter.session.link).toHaveBeenCalledWith(
3344 + sessionId,
3345 + {
3346 + toolkit: 'github',
3347 + },
3348 + undefined
3349 + );
3350 expect(connectionRequest).toHaveProperty('redirectUrl', 'https://composio.dev/auth/redirect');
3351 expect(connectionRequest).toHaveProperty('status', ConnectedAccountStatuses.INITIATED);
3352 });
@@ -3153,12 +3359,16 @@ describe('ToolRouter', () => {
3359
3360 const toolkitsResult = await session.toolkits();
3361
3156 - expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(sessionId, {
3157 - cursor: undefined,
3158 - limit: undefined,
3159 - toolkits: undefined,
3160 - is_connected: undefined,
3161 - });
3362 + expect(mockClient.toolRouter.session.toolkits).toHaveBeenCalledWith(
3363 + sessionId,
3364 + {
3365 + cursor: undefined,
3366 + limit: undefined,
3367 + toolkits: undefined,
3368 + is_connected: undefined,
3369 + },
3370 + undefined
3371 + );
3372 expect(toolkitsResult.items).toHaveLength(3);
3373 expect(toolkitsResult.items[0].slug).toBe('gmail');
3374 });
@@ -3189,11 +3399,15 @@ describe('ToolRouter', () => {
3399 const session = await toolRouter.use(sessionId, { customTools: [grepTool] });
3400 await session.tools();
3401
3192 - expect(mockClient.toolRouter.session.attach).toHaveBeenCalledWith(sessionId, {
3193 - experimental: {
3194 - custom_tools: [expect.objectContaining({ slug: 'GREP', preload: true })],
3402 + expect(mockClient.toolRouter.session.attach).toHaveBeenCalledWith(
3403 + sessionId,
3404 + {
3405 + experimental: {
3406 + custom_tools: [expect.objectContaining({ slug: 'GREP', preload: true })],
3407 + },
3408 },
3196 - });
3409 + undefined
3410 + );
3411 expect(mockClient.post).not.toHaveBeenCalled();
3412 expect(mockClient.toolRouter.session.retrieve).not.toHaveBeenCalled();
3413 const wrappedTools = mockProvider.wrapTools.mock.calls[0][0] as Array<{ slug: string }>;
@@ -3250,12 +3464,16 @@ describe('ToolRouter', () => {
3464
3465 const wrappedTools = mockProvider.wrapTools.mock.calls[0][0] as Array<{ slug: string }>;
3466 expect(wrappedTools.map(tool => tool.slug)).toEqual(['COMPOSIO_SEARCH_TOOLS', 'LOCAL_GREP']);
3253 - expect(mockClient.toolRouter.session.search).toHaveBeenCalledWith(sessionId, {
3254 - queries: [{ use_case: 'search local text' }],
3255 - experimental: {
3256 - custom_tools: [expect.objectContaining({ slug: 'GREP', preload: true })],
3467 + expect(mockClient.toolRouter.session.search).toHaveBeenCalledWith(
3468 + sessionId,
3469 + {
3470 + queries: [{ use_case: 'search local text' }],
3471 + experimental: {
3472 + custom_tools: [expect.objectContaining({ slug: 'GREP', preload: true })],
3473 + },
3474 },
3258 - });
3475 + undefined
3476 + );
3477 });
3478 it('should handle different session IDs', async () => {
3479 const session1Response = {
@@ -3278,8 +3496,16 @@ describe('ToolRouter', () => {
3496 expect(session1.sessionId).toBe('session_1');
3497 expect(session2.sessionId).toBe('session_2');
3498 expect(mockClient.toolRouter.session.retrieve).toHaveBeenCalledTimes(2);
3281 - expect(mockClient.toolRouter.session.retrieve).toHaveBeenNthCalledWith(1, 'session_1');
3282 - expect(mockClient.toolRouter.session.retrieve).toHaveBeenNthCalledWith(2, 'session_2');
3499 + expect(mockClient.toolRouter.session.retrieve).toHaveBeenNthCalledWith(
3500 + 1,
3501 + 'session_1',
3502 + undefined
3503 + );
3504 + expect(mockClient.toolRouter.session.retrieve).toHaveBeenNthCalledWith(
3505 + 2,
3506 + 'session_2',
3507 + undefined
3508 + );
3509 expect(mockClient.post).not.toHaveBeenCalled();
3510 });
3511
@@ -3297,7 +3523,7 @@ describe('ToolRouter', () => {
3523 mockClient.toolRouter.session.retrieve.mockRejectedValueOnce(error);
3524
3525 await expect(toolRouter.use(sessionId)).rejects.toThrow('Session not found');
3300 - expect(mockClient.toolRouter.session.retrieve).toHaveBeenCalledWith(sessionId);
3526 + expect(mockClient.toolRouter.session.retrieve).toHaveBeenCalledWith(sessionId, undefined);
3527 expect(mockClient.post).not.toHaveBeenCalled();
3528 });
3529
ts/packages/core/test/models/toolkits.test.ts
+48 -33
@@ -133,7 +133,7 @@ describe('Toolkits', () => {
133 noAuth: false,
134 },
135 ]);
136 - expect(mockClient.toolkits.list).toHaveBeenCalledWith({});
136 + expect(mockClient.toolkits.list).toHaveBeenCalledWith({}, undefined);
137 });
138
139 it('should get a single toolkit by slug', async () => {
@@ -174,7 +174,7 @@ describe('Toolkits', () => {
174 getCurrentUserEndpoint: '/user',
175 getCurrentUserEndpointMethod: 'GET',
176 });
177 - expect(mockClient.toolkits.retrieve).toHaveBeenCalledWith('github');
177 + expect(mockClient.toolkits.retrieve).toHaveBeenCalledWith('github', undefined, undefined);
178 });
179
180 it('should handle toolkit without getCurrentUserEndpointMethod', async () => {
@@ -354,29 +354,38 @@ describe('Toolkits', () => {
354 const connectionRequest = await toolkits.authorize(userId, toolkitSlug);
355
356 // Verify the flow
357 - expect(mockClient.toolkits.retrieve).toHaveBeenCalledWith(toolkitSlug);
358 - expect(mockClient.authConfigs.list).toHaveBeenCalledWith({
359 - toolkit_slug: toolkitSlug,
360 - });
361 - expect(mockClient.authConfigs.create).toHaveBeenCalledWith({
362 - toolkit: {
363 - slug: toolkitSlug,
364 - },
365 - auth_config: {
366 - type: 'use_composio_managed_auth',
367 - credentials: undefined,
368 - name: 'Test Toolkit Auth Config',
369 - tool_access_config: undefined,
357 + expect(mockClient.toolkits.retrieve).toHaveBeenCalledWith(toolkitSlug, undefined, undefined);
358 + expect(mockClient.authConfigs.list).toHaveBeenCalledWith(
359 + {
360 + toolkit_slug: toolkitSlug,
361 },
371 - });
372 - expect(mockClient.connectedAccounts.create).toHaveBeenCalledWith({
373 - auth_config: {
374 - id: 'auth_config_123',
362 + undefined
363 + );
364 + expect(mockClient.authConfigs.create).toHaveBeenCalledWith(
365 + {
366 + toolkit: {
367 + slug: toolkitSlug,
368 + },
369 + auth_config: {
370 + type: 'use_composio_managed_auth',
371 + credentials: undefined,
372 + name: 'Test Toolkit Auth Config',
373 + tool_access_config: undefined,
374 + },
375 },
376 - connection: {
377 - user_id: userId,
376 + undefined
377 + );
378 + expect(mockClient.connectedAccounts.create).toHaveBeenCalledWith(
379 + {
380 + auth_config: {
381 + id: 'auth_config_123',
382 + },
383 + connection: {
384 + user_id: userId,
385 + },
386 },
379 - });
387 + undefined
388 + );
389 expect(connectionRequest).toHaveProperty('id', 'conn_123');
390 expect(connectionRequest).toHaveProperty('waitForConnection');
391 expect(typeof connectionRequest.waitForConnection).toBe('function');
@@ -431,19 +440,25 @@ describe('Toolkits', () => {
440 const connectionRequest = await toolkits.authorize(userId, toolkitSlug);
441
442 // Verify the flow
434 - expect(mockClient.toolkits.retrieve).toHaveBeenCalledWith(toolkitSlug);
435 - expect(mockClient.authConfigs.list).toHaveBeenCalledWith({
436 - toolkit_slug: toolkitSlug,
437 - });
438 - expect(mockClient.authConfigs.create).not.toHaveBeenCalled();
439 - expect(mockClient.connectedAccounts.create).toHaveBeenCalledWith({
440 - auth_config: {
441 - id: 'existing_auth_123',
443 + expect(mockClient.toolkits.retrieve).toHaveBeenCalledWith(toolkitSlug, undefined, undefined);
444 + expect(mockClient.authConfigs.list).toHaveBeenCalledWith(
445 + {
446 + toolkit_slug: toolkitSlug,
447 },
443 - connection: {
444 - user_id: userId,
448 + undefined
449 + );
450 + expect(mockClient.authConfigs.create).not.toHaveBeenCalled();
451 + expect(mockClient.connectedAccounts.create).toHaveBeenCalledWith(
452 + {
453 + auth_config: {
454 + id: 'existing_auth_123',
455 + },
456 + connection: {
457 + user_id: userId,
458 + },
459 },
446 - });
460 + undefined
461 + );
462 expect(connectionRequest).toHaveProperty('id', 'conn_123');
463 expect(connectionRequest).toHaveProperty('waitForConnection');
464 expect(typeof connectionRequest.waitForConnection).toBe('function');
ts/packages/core/test/models/triggers.test.ts
+106 -58
@@ -246,7 +246,7 @@ describe('Triggers', () => {
246
247 const result = await triggers.listActive();
248
249 - expect(mockClient.triggerInstances.listActive).toHaveBeenCalledWith(undefined);
249 + expect(mockClient.triggerInstances.listActive).toHaveBeenCalledWith(undefined, undefined);
250 expect(result).toEqual({
251 items: mockTriggerInstances.items.map(item => ({
252 id: item.id,
@@ -279,15 +279,18 @@ describe('Triggers', () => {
279
280 await triggers.listActive(query);
281
282 - expect(mockClient.triggerInstances.listActive).toHaveBeenCalledWith({
283 - auth_config_ids: query.authConfigIds,
284 - connected_account_ids: query.connectedAccountIds,
285 - limit: query.limit,
286 - cursor: query.cursor,
287 - show_disabled: query.showDisabled,
288 - trigger_ids: query.triggerIds,
289 - trigger_names: query.triggerNames,
290 - });
282 + expect(mockClient.triggerInstances.listActive).toHaveBeenCalledWith(
283 + {
284 + auth_config_ids: query.authConfigIds,
285 + connected_account_ids: query.connectedAccountIds,
286 + limit: query.limit,
287 + cursor: query.cursor,
288 + show_disabled: query.showDisabled,
289 + trigger_ids: query.triggerIds,
290 + trigger_names: query.triggerNames,
291 + },
292 + undefined
293 + );
294 });
295 });
296
@@ -311,19 +314,30 @@ describe('Triggers', () => {
314
315 const result = await triggers.create(userId, slug, body);
316
314 - expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(slug, {
315 - toolkit_versions: 'latest',
316 - });
317 - expect(mockClient.connectedAccounts.list).toHaveBeenCalledWith({
318 - user_ids: [userId],
319 - toolkit_slugs: [mockTriggerType.toolkit.slug],
320 - });
321 - expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(slug, {
322 - connected_account_id: body.connectedAccountId,
323 - trigger_config: body.triggerConfig,
324 - toolkit_versions: 'latest',
325 - user_id: userId,
326 - });
317 + expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(
318 + slug,
319 + {
320 + toolkit_versions: 'latest',
321 + },
322 + undefined
323 + );
324 + expect(mockClient.connectedAccounts.list).toHaveBeenCalledWith(
325 + {
326 + user_ids: [userId],
327 + toolkit_slugs: [mockTriggerType.toolkit.slug],
328 + },
329 + undefined
330 + );
331 + expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(
332 + slug,
333 + {
334 + connected_account_id: body.connectedAccountId,
335 + trigger_config: body.triggerConfig,
336 + toolkit_versions: 'latest',
337 + user_id: userId,
338 + },
339 + undefined
340 + );
341 expect(result).toEqual({ triggerId: mockTriggerUpsertResponse.trigger_id });
342 });
343
@@ -337,12 +351,16 @@ describe('Triggers', () => {
351
352 const result = await triggers.create(userId, slug, bodyWithoutConnectedAccount);
353
340 - expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(slug, {
341 - connected_account_id: 'conn-456',
342 - trigger_config: bodyWithoutConnectedAccount.triggerConfig,
343 - toolkit_versions: 'latest',
344 - user_id: userId,
345 - });
354 + expect(mockClient.triggerInstances.upsert).toHaveBeenCalledWith(
355 + slug,
356 + {
357 + connected_account_id: 'conn-456',
358 + trigger_config: bodyWithoutConnectedAccount.triggerConfig,
359 + toolkit_versions: 'latest',
360 + user_id: userId,
361 + },
362 + undefined
363 + );
364 expect(logger.warn).toHaveBeenCalledWith(
365 `[Warn] Multiple connected accounts found for user ${userId}, using the first one. Pass connectedAccountId to select a specific account.`
366 );
@@ -414,7 +432,11 @@ describe('Triggers', () => {
432
433 const result = await triggers.update(triggerId, body);
434
417 - expect(mockClient.triggerInstances.manage.update).toHaveBeenCalledWith(triggerId, body);
435 + expect(mockClient.triggerInstances.manage.update).toHaveBeenCalledWith(
436 + triggerId,
437 + body,
438 + undefined
439 + );
440 expect(result).toEqual(mockTriggerUpdateResponse);
441 });
442 });
@@ -426,7 +448,7 @@ describe('Triggers', () => {
448
449 const result = await triggers.delete(triggerId);
450
429 - expect(mockClient.triggerInstances.manage.delete).toHaveBeenCalledWith(triggerId);
451 + expect(mockClient.triggerInstances.manage.delete).toHaveBeenCalledWith(triggerId, undefined);
452 expect(result).toEqual({ triggerId: mockTriggerDeleteResponse.trigger_id });
453 });
454 });
@@ -438,9 +460,13 @@ describe('Triggers', () => {
460
461 const result = await triggers.disable(triggerId);
462
441 - expect(mockClient.triggerInstances.manage.update).toHaveBeenCalledWith(triggerId, {
442 - status: 'disable',
443 - });
463 + expect(mockClient.triggerInstances.manage.update).toHaveBeenCalledWith(
464 + triggerId,
465 + {
466 + status: 'disable',
467 + },
468 + undefined
469 + );
470 expect(result).toEqual(mockTriggerUpdateResponse);
471 });
472 });
@@ -452,9 +478,13 @@ describe('Triggers', () => {
478
479 const result = await triggers.enable(triggerId);
480
455 - expect(mockClient.triggerInstances.manage.update).toHaveBeenCalledWith(triggerId, {
456 - status: 'enable',
457 - });
481 + expect(mockClient.triggerInstances.manage.update).toHaveBeenCalledWith(
482 + triggerId,
483 + {
484 + status: 'enable',
485 + },
486 + undefined
487 + );
488 expect(result).toEqual(mockTriggerUpdateResponse);
489 });
490 });
@@ -465,12 +495,15 @@ describe('Triggers', () => {
495
496 const result = await triggers.listTypes();
497
468 - expect(mockClient.triggersTypes.list).toHaveBeenCalledWith({
469 - cursor: undefined,
470 - limit: undefined,
471 - toolkit_slugs: undefined,
472 - toolkit_versions: 'latest',
473 - });
498 + expect(mockClient.triggersTypes.list).toHaveBeenCalledWith(
499 + {
500 + cursor: undefined,
501 + limit: undefined,
502 + toolkit_slugs: undefined,
503 + toolkit_versions: 'latest',
504 + },
505 + undefined
506 + );
507 expect(result).toEqual({
508 items: mockTriggerTypes.items.map(item => ({
509 ...item,
@@ -487,12 +520,15 @@ describe('Triggers', () => {
520
521 const result = await triggers.listTypes(query);
522
490 - expect(mockClient.triggersTypes.list).toHaveBeenCalledWith({
491 - cursor: undefined,
492 - limit: query.limit,
493 - toolkit_slugs: query.toolkits,
494 - toolkit_versions: 'latest',
495 - });
523 + expect(mockClient.triggersTypes.list).toHaveBeenCalledWith(
524 + {
525 + cursor: undefined,
526 + limit: query.limit,
527 + toolkit_slugs: query.toolkits,
528 + toolkit_versions: 'latest',
529 + },
530 + undefined
531 + );
532 expect(result).toEqual({
533 items: mockTriggerTypes.items,
534 nextCursor: mockTriggerTypes.next_cursor,
@@ -508,9 +544,13 @@ describe('Triggers', () => {
544
545 const result = await triggers.getType(slug);
546
511 - expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(slug, {
512 - toolkit_versions: 'latest', // Uses global default
513 - });
547 + expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(
548 + slug,
549 + {
550 + toolkit_versions: 'latest', // Uses global default
551 + },
552 + undefined
553 + );
554 expect(result).toEqual(mockTriggerType);
555 });
556
@@ -525,9 +565,13 @@ describe('Triggers', () => {
565
566 const result = await customTriggers.getType(slug);
567
528 - expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(slug, {
529 - toolkit_versions: customToolkitVersions, // Uses configured global versions
530 - });
568 + expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(
569 + slug,
570 + {
571 + toolkit_versions: customToolkitVersions, // Uses configured global versions
572 + },
573 + undefined
574 + );
575 expect(result).toEqual(mockTriggerType);
576 });
577
@@ -537,9 +581,13 @@ describe('Triggers', () => {
581
582 const result = await triggers.getType(slug);
583
540 - expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(slug, {
541 - toolkit_versions: 'latest', // Default to latest
542 - });
584 + expect(mockClient.triggersTypes.retrieve).toHaveBeenCalledWith(
585 + slug,
586 + {
587 + toolkit_versions: 'latest', // Default to latest
588 + },
589 + undefined
590 + );
591 expect(result).toEqual(mockTriggerType);
592 });
593 });
ts/packages/core/test/tools/fileModifiers.test.ts
+42 -11
@@ -6,6 +6,7 @@ import {
6 ComposioFileUploadAbortedError,
7 ComposioFileUploadError,
8 } from '../../src/errors/FileModifierErrors';
9 +import { ComposioRequestCancelledError } from '../../src/errors/SDKErrors';
10 import * as fileUtils from '../../src/utils/fileUtils.node';
11 import { Tools } from '../../src/models/Tools';
12 import { createTestContext, setupTest, mockToolExecution } from '../utils/toolExecuteUtils';
@@ -481,6 +482,32 @@ describe('FileToolModifier', () => {
482 ).rejects.toThrow(ComposioFileUploadError);
483 });
484
485 + it('should throw ComposioRequestCancelledError on caller-aborted upload', async () => {
486 + const controller = new AbortController();
487 + vi.mocked(fileUtils.getFileDataAfterUploadingToS3).mockImplementationOnce(async () => {
488 + controller.abort();
489 + const error = new Error('The operation was aborted');
490 + error.name = 'AbortError';
491 + throw error;
492 + });
493 +
494 + const params = {
495 + arguments: {
496 + file: '/path/to/file.txt',
497 + },
498 + userId: 'test-user',
499 + };
500 +
501 + await expect(
502 + fileToolModifier.fileUploadModifier(mockTool, {
503 + toolSlug: 'test-tool',
504 + toolkitSlug: 'test-toolkit',
505 + params,
506 + signal: controller.signal,
507 + })
508 + ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
509 + });
510 +
511 it('should handle File object for file_uploadable parameters', async () => {
512 const mockFileData = {
513 name: 'file.txt',
@@ -1982,18 +2009,22 @@ describe('Tools with dangerouslyAllowAutoUploadDownloadFiles', () => {
2009 });
2010
2011 expect(fileUtils.getFileDataAfterUploadingToS3).not.toHaveBeenCalled();
1985 - expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {
1986 - arguments: {
1987 - file: '/path/to/file.txt',
2012 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
2013 + 'COMPOSIO_TOOL',
2014 + {
2015 + arguments: {
2016 + file: '/path/to/file.txt',
2017 + },
2018 + allow_tracing: undefined,
2019 + connected_account_id: undefined,
2020 + custom_auth_params: undefined,
2021 + custom_connection_data: undefined,
2022 + text: undefined,
2023 + user_id: 'test-user',
2024 + version: 'latest',
2025 },
1989 - allow_tracing: undefined,
1990 - connected_account_id: undefined,
1991 - custom_auth_params: undefined,
1992 - custom_connection_data: undefined,
1993 - text: undefined,
1994 - user_id: 'test-user',
1995 - version: 'latest',
1996 - });
2026 + undefined
2027 + );
2028 });
2029
2030 it('warns once per tool when auto-upload is off and the tool has a file-uploadable input', async () => {
ts/packages/core/test/tools/modifiers.test.ts
+9 -4
@@ -98,7 +98,8 @@ describe('Tools Modifiers', () => {
98 slug,
99 expect.objectContaining({
100 arguments: { limit: 10 },
101 - })
101 + }),
102 + undefined
103 );
104 });
105
@@ -240,9 +241,13 @@ describe('Tools Modifiers', () => {
241 });
242
243 // Verify schema modification
243 - expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(slug, {
244 - modifySchema: schemaModifier,
245 - });
244 + expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(
245 + slug,
246 + {
247 + modifySchema: schemaModifier,
248 + },
249 + undefined
250 + );
251 expect(mockTool.description).toBe('Enhanced GITHUB_GET_REPOS for better context');
252 expect(mockTool.tags).toContain('enhanced');
253 expect(mockTool.tags).toContain('modified');
ts/packages/core/test/tools/requestOptions.test.ts new
+458
@@ -0,0 +1,458 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import { mockClient } from '../utils/mocks/client.mock';
3 +import { toolMocks } from '../utils/mocks/data.mock';
4 +import { Tools } from '../../src/models/Tools';
5 +import ComposioClient, { APIUserAbortError } from '@composio/client';
6 +import { MockProvider } from '../utils/mocks/provider.mock';
7 +import { ComposioRequestCancelledError } from '../../src/errors/SDKErrors';
8 +import type { SessionContext } from '../../src/types/customTool.types';
9 +import { ComposioToolExecutionError } from '../../src/errors/ToolErrors';
10 +
11 +describe('Cancellation — error normalization', () => {
12 + let tools: Tools<unknown, unknown, MockProvider>;
13 +
14 + beforeEach(() => {
15 + vi.clearAllMocks();
16 + tools = new Tools(mockClient as unknown as ComposioClient, { provider: new MockProvider() });
17 + });
18 +
19 + it('translates a real APIUserAbortError (which inherits name==="Error") into ComposioRequestCancelledError', async () => {
20 + const realAbort = new APIUserAbortError();
21 + expect(realAbort.name).toBe('Error');
22 +
23 + mockClient.tools.list.mockImplementationOnce(async () => {
24 + throw realAbort;
25 + });
26 +
27 + await expect(
28 + tools.getRawComposioTools({ search: 'send email' }, undefined, {
29 + signal: AbortSignal.abort(),
30 + })
31 + ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
32 + });
33 +
34 + it('translates a generic AbortError into ComposioRequestCancelledError', async () => {
35 + mockClient.tools.list.mockImplementationOnce(async () => {
36 + const err = new Error('The operation was aborted');
37 + err.name = 'AbortError';
38 + throw err;
39 + });
40 +
41 + await expect(
42 + tools.getRawComposioTools({ search: 'send email' }, undefined, {
43 + signal: AbortSignal.abort(),
44 + })
45 + ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
46 + });
47 +
48 + it('walks error.cause to detect a wrapped abort', async () => {
49 + mockClient.tools.list.mockImplementationOnce(async () => {
50 + const inner = new APIUserAbortError();
51 + const outer = new Error('Request failed during retry', { cause: inner });
52 + outer.name = 'APIError';
53 + throw outer;
54 + });
55 +
56 + await expect(
57 + tools.getRawComposioTools({ search: 'send email' }, undefined, {
58 + signal: AbortSignal.abort(),
59 + })
60 + ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
61 + });
62 +
63 + it('does NOT relabel an unrelated failure as cancellation even if the signal aborts after it', async () => {
64 + // TOCTOU guard: classification keys on the error being abort-shaped, not just
65 + // on signal.aborted. A genuine failure (e.g. a 500) that happens to coincide
66 + // with a late abort must surface as-is, never as a caller cancellation.
67 + const controller = new AbortController();
68 + const serverError = new Error('Internal Server Error');
69 + mockClient.tools.list.mockImplementationOnce(async () => {
70 + controller.abort();
71 + throw serverError;
72 + });
73 +
74 + await expect(
75 + tools.getRawComposioTools({ search: 'send email' }, undefined, {
76 + signal: controller.signal,
77 + })
78 + ).rejects.toBe(serverError);
79 + });
80 +
81 + it('abort during execute surfaces as ComposioRequestCancelledError, not ComposioToolExecutionError', async () => {
82 + const controller = new AbortController();
83 + vi.spyOn(tools, 'getRawComposioToolBySlug').mockResolvedValueOnce(
84 + toolMocks.transformedTool as never
85 + );
86 + mockClient.tools.execute.mockImplementationOnce(async () => {
87 + controller.abort();
88 + const err = new Error('Request was aborted');
89 + err.name = 'APIUserAbortError';
90 + throw err;
91 + });
92 +
93 + try {
94 + await tools.execute(
95 + 'COMPOSIO_TOOL',
96 + { userId: 'user_1', arguments: {}, dangerouslySkipVersionCheck: true },
97 + { signal: controller.signal }
98 + );
99 + throw new Error('expected throw');
100 + } catch (err) {
101 + expect(err).toBeInstanceOf(ComposioRequestCancelledError);
102 + expect(err).not.toBeInstanceOf(ComposioToolExecutionError);
103 + }
104 + });
105 +
106 + it('abort during schema retrieval surfaces as ComposioRequestCancelledError, not ComposioToolNotFoundError', async () => {
107 + mockClient.tools.retrieve.mockReset();
108 + mockClient.tools.retrieve.mockImplementationOnce(async () => {
109 + const err = new Error('Request was aborted');
110 + err.name = 'APIUserAbortError';
111 + throw err;
112 + });
113 +
114 + await expect(
115 + tools.getRawComposioToolBySlug('GITHUB_GET_REPOS', undefined, {
116 + signal: AbortSignal.abort(),
117 + })
118 + ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
119 + });
120 +
121 + it('ComposioRequestCancelledError carries a non-empty message', async () => {
122 + mockClient.tools.list.mockReset();
123 + mockClient.tools.list.mockImplementationOnce(async () => {
124 + const err = new Error('The operation was aborted');
125 + err.name = 'APIUserAbortError';
126 + throw err;
127 + });
128 +
129 + try {
130 + await tools.getRawComposioTools({ search: 'send email' }, undefined, {
131 + signal: AbortSignal.abort(),
132 + });
133 + throw new Error('expected throw');
134 + } catch (err) {
135 + expect(err).toBeInstanceOf(ComposioRequestCancelledError);
136 + expect((err as Error).message).toMatch(/cancelled/i);
137 + }
138 + });
139 +});
140 +
141 +describe('Cancellation — execute signal forwarding', () => {
142 + let tools: Tools<unknown, unknown, MockProvider>;
143 +
144 + beforeEach(() => {
145 + vi.clearAllMocks();
146 + tools = new Tools(mockClient as unknown as ComposioClient, { provider: new MockProvider() });
147 + });
148 +
149 + it('forwards signal to client.tools.execute and schema lookup', async () => {
150 + const controller = new AbortController();
151 + const requestOptions = { signal: controller.signal };
152 +
153 + const getRawSpy = vi.spyOn(tools, 'getRawComposioToolBySlug');
154 + getRawSpy.mockResolvedValueOnce(toolMocks.transformedTool as never);
155 + mockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);
156 +
157 + await tools.execute(
158 + 'COMPOSIO_TOOL',
159 + { userId: 'user_1', arguments: {}, dangerouslySkipVersionCheck: true },
160 + requestOptions
161 + );
162 +
163 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
164 + 'COMPOSIO_TOOL',
165 + expect.any(Object),
166 + requestOptions
167 + );
168 + expect(getRawSpy).toHaveBeenCalledWith('COMPOSIO_TOOL', expect.any(Object), requestOptions);
169 + });
170 +
171 + it('pre-aborted signal short-circuits before modifiers run', async () => {
172 + vi.spyOn(tools, 'getRawComposioToolBySlug').mockResolvedValueOnce(
173 + toolMocks.transformedTool as never
174 + );
175 +
176 + const controller = new AbortController();
177 + controller.abort();
178 +
179 + await expect(
180 + tools.execute(
181 + 'COMPOSIO_TOOL',
182 + { userId: 'user_1', arguments: {}, dangerouslySkipVersionCheck: true },
183 + { beforeExecute: vi.fn(p => p.params), signal: controller.signal }
184 + )
185 + ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
186 + });
187 +
188 + it('runs afterExecute to completion when the signal fires after the tool already executed', async () => {
189 + const controller = new AbortController();
190 +
191 + vi.spyOn(tools, 'getRawComposioToolBySlug').mockResolvedValueOnce(
192 + toolMocks.transformedTool as never
193 + );
194 + // The remote tool executes successfully, then the caller's signal fires
195 + // (e.g. an AbortSignal.timeout) before post-processing runs.
196 + mockClient.tools.execute.mockImplementationOnce(async () => {
197 + controller.abort();
198 + return toolMocks.rawToolExecuteResponse;
199 + });
200 +
201 + const afterExecute = vi.fn(({ result }) => result);
202 +
203 + const result = await tools.execute(
204 + 'COMPOSIO_TOOL',
205 + { userId: 'user_1', arguments: {}, dangerouslySkipVersionCheck: true },
206 + { afterExecute, signal: controller.signal }
207 + );
208 +
209 + // The tool already committed (the side effect happened), so the abort lost
210 + // the race: afterExecute MUST still run rather than being silently skipped.
211 + expect(afterExecute).toHaveBeenCalledTimes(1);
212 + expect(result).toBeDefined();
213 + });
214 +});
215 +
216 +describe('Cancellation — custom-tool AbortError classification', () => {
217 + it('AbortError from tool internal abort (signal NOT fired) is NOT misclassified as cancellation', async () => {
218 + const { z } = await import('zod');
219 + const { createCustomTool } = await import('../../src/models/CustomTool');
220 + const { executeCustomTool } = await import('../../src/models/customToolExecution');
221 + const customTool = createCustomTool('OWN_ABORT_TOOL', {
222 + name: 'Own abort',
223 + description: 'test',
224 + inputParams: z.object({}),
225 + execute: async () => {
226 + const err = new Error('Tool internal timeout');
227 + err.name = 'AbortError';
228 + throw err;
229 + },
230 + });
231 +
232 + const controller = new AbortController();
233 + const result = await executeCustomTool(
234 + { handle: customTool, finalSlug: 'LOCAL_OWN_ABORT_TOOL' } as never,
235 + {},
236 + createSessionContext(),
237 + { signal: controller.signal }
238 + );
239 +
240 + expect(result.successful).toBe(false);
241 + expect(result.error).toBe('Tool internal timeout');
242 + });
243 +
244 + it('AbortError after caller abort IS classified as cancellation', async () => {
245 + const { z } = await import('zod');
246 + const { createCustomTool } = await import('../../src/models/CustomTool');
247 + const { executeCustomTool } = await import('../../src/models/customToolExecution');
248 + const controller = new AbortController();
249 +
250 + const customTool = createCustomTool('COOP_CANCEL_TOOL', {
251 + name: 'Coop cancel',
252 + description: 'test',
253 + inputParams: z.object({}),
254 + execute: async () => {
255 + controller.abort();
256 + const err = new Error('The operation was aborted');
257 + err.name = 'AbortError';
258 + throw err;
259 + },
260 + });
261 +
262 + await expect(
263 + executeCustomTool(
264 + { handle: customTool, finalSlug: 'LOCAL_COOP_CANCEL_TOOL' } as never,
265 + {},
266 + createSessionContext(),
267 + { signal: controller.signal }
268 + )
269 + ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
270 + });
271 +
272 + it('pre-aborted signal short-circuits before custom-tool user code runs', async () => {
273 + const { z } = await import('zod');
274 + const { createCustomTool } = await import('../../src/models/CustomTool');
275 + const { executeCustomTool } = await import('../../src/models/customToolExecution');
276 + const userExecute = vi.fn();
277 + const customTool = createCustomTool('CUSTOM_TOOL', {
278 + name: 'Custom tool',
279 + description: 'test',
280 + inputParams: z.object({}),
281 + execute: async () => {
282 + await userExecute();
283 + return {};
284 + },
285 + });
286 +
287 + const controller = new AbortController();
288 + controller.abort();
289 +
290 + await expect(
291 + executeCustomTool(
292 + { handle: customTool, finalSlug: 'LOCAL_CUSTOM_TOOL' } as never,
293 + {},
294 + createSessionContext(),
295 + { signal: controller.signal }
296 + )
297 + ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
298 + expect(userExecute).not.toHaveBeenCalled();
299 + });
300 +});
301 +
302 +function createSessionContext(): SessionContext {
303 + return {
304 + userId: 'user_1',
305 + execute: vi.fn(),
306 + proxyExecute: vi.fn(),
307 + };
308 +}
309 +
310 +describe('Cancellation — SessionContext signal forwarding', () => {
311 + it('ctx.execute aborts are normalized so in-tool try/catch detects ComposioRequestCancelledError', async () => {
312 + const { SessionContextImpl } = await import('../../src/models/SessionContext');
313 + const { executeCustomTool: execCustomTool } =
314 + await import('../../src/models/customToolExecution');
315 +
316 + const controller = new AbortController();
317 + const sessionExecuteSpy = vi.fn().mockImplementation(async () => {
318 + controller.abort();
319 + throw new APIUserAbortError();
320 + });
321 + const fakeClient = {
322 + toolRouter: { session: { execute: sessionExecuteSpy, proxyExecute: vi.fn() } },
323 + };
324 + const ctxInstance = new SessionContextImpl(fakeClient as never, 'u', 's');
325 +
326 + let observedInToolError: unknown = undefined;
327 + const { z } = await import('zod');
328 + const customToolEntry = {
329 + handle: {
330 + slug: 'INTOOL_CATCH',
331 + name: 'in-tool catch',
332 + inputParams: z.object({}),
333 + execute: async (_input: unknown, ctx: SessionContext) => {
334 + try {
335 + await ctx.execute('SOMETHING', {});
336 + return { reached: true };
337 + } catch (err) {
338 + observedInToolError = err;
339 + throw err;
340 + }
341 + },
342 + },
343 + };
344 +
345 + await expect(
346 + execCustomTool(customToolEntry as never, {}, ctxInstance, {
347 + signal: controller.signal,
348 + })
349 + ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
350 +
351 + expect(observedInToolError).toBeInstanceOf(ComposioRequestCancelledError);
352 + });
353 +});
354 +
355 +describe('Cancellation — composite operation forwarding', () => {
356 + beforeEach(() => {
357 + vi.clearAllMocks();
358 + });
359 +
360 + it('toolkits.authorize forwards signal through every preflight call', async () => {
361 + const { Toolkits } = await import('../../src/models/Toolkits');
362 + const toolkits = new Toolkits(mockClient as unknown as ComposioClient);
363 +
364 + const getToolkitBySlugSpy = vi
365 + .spyOn(
366 + toolkits as unknown as { getToolkitBySlug: (...args: unknown[]) => Promise<unknown> },
367 + 'getToolkitBySlug'
368 + )
369 + .mockResolvedValue({
370 + slug: 'github',
371 + name: 'GitHub',
372 + authConfigDetails: [{ mode: 'OAUTH2', fields: {} }],
373 + } as never);
374 + const { AuthConfigs } = await import('../../src/models/AuthConfigs');
375 + const authConfigsListSpy = vi
376 + .spyOn(AuthConfigs.prototype, 'list')
377 + .mockImplementation(async (_query, reqOpts) => {
378 + await mockClient.authConfigs.list({} as never, reqOpts);
379 + return { items: [{ id: 'ac_existing' } as never], nextCursor: null, totalPages: 1 };
380 + });
381 + mockClient.authConfigs.list.mockResolvedValueOnce({
382 + items: [{ id: 'ac_existing' }],
383 + totalPages: 1,
384 + } as never);
385 + mockClient.connectedAccounts.list.mockResolvedValueOnce({
386 + items: [],
387 + totalPages: 1,
388 + } as never);
389 + mockClient.connectedAccounts.create = vi.fn().mockResolvedValue({
390 + id: 'ca_new',
391 + connectionData: { val: { status: 'INITIATED', redirectUrl: null } },
392 + });
393 +
394 + const requestOptions = { signal: new AbortController().signal };
395 + await toolkits.authorize('user_1', 'github', undefined, requestOptions);
396 +
397 + expect(getToolkitBySlugSpy).toHaveBeenCalledWith('github', requestOptions);
398 + expect(authConfigsListSpy).toHaveBeenCalledWith({ toolkit: 'github' }, requestOptions);
399 + expect(mockClient.connectedAccounts.list).toHaveBeenCalledWith(
400 + expect.any(Object),
401 + requestOptions
402 + );
403 + expect(mockClient.connectedAccounts.create).toHaveBeenCalledWith(
404 + expect.any(Object),
405 + requestOptions
406 + );
407 + });
408 +
409 + it('connectedAccounts.initiate forwards signal to list preflight and create', async () => {
410 + const { ConnectedAccounts } = await import('../../src/models/ConnectedAccounts');
411 + const connectedAccounts = new ConnectedAccounts(mockClient as unknown as ComposioClient);
412 +
413 + mockClient.connectedAccounts.list.mockResolvedValueOnce({
414 + items: [],
415 + totalPages: 1,
416 + } as never);
417 + mockClient.connectedAccounts.create = vi.fn().mockResolvedValue({
418 + id: 'ca_new',
419 + connectionData: { val: { status: 'INITIATED', redirectUrl: null } },
420 + });
421 +
422 + const requestOptions = { signal: new AbortController().signal };
423 + await connectedAccounts.initiate('user_1', 'ac_1', { allowMultiple: true }, requestOptions);
424 +
425 + expect(mockClient.connectedAccounts.list).toHaveBeenCalledWith(
426 + expect.any(Object),
427 + requestOptions
428 + );
429 + expect(mockClient.connectedAccounts.create).toHaveBeenCalledWith(
430 + expect.any(Object),
431 + requestOptions
432 + );
433 + });
434 +
435 + it('connectedAccounts.link forwards signal to list preflight and link.create', async () => {
436 + const { ConnectedAccounts } = await import('../../src/models/ConnectedAccounts');
437 + const linkCreate = vi.fn().mockResolvedValue({
438 + connected_account_id: 'ca_new',
439 + redirect_url: 'https://example.test/cb',
440 + });
441 + const extendedClient = { ...mockClient, link: { create: linkCreate } };
442 + const connectedAccounts = new ConnectedAccounts(extendedClient as unknown as ComposioClient);
443 +
444 + mockClient.connectedAccounts.list.mockResolvedValueOnce({
445 + items: [],
446 + totalPages: 1,
447 + } as never);
448 +
449 + const requestOptions = { signal: new AbortController().signal };
450 + await connectedAccounts.link('user_1', 'ac_1', { allowMultiple: true }, requestOptions);
451 +
452 + expect(mockClient.connectedAccounts.list).toHaveBeenCalledWith(
453 + expect.any(Object),
454 + requestOptions
455 + );
456 + expect(linkCreate).toHaveBeenCalledWith(expect.any(Object), requestOptions);
457 + });
458 +});
ts/packages/core/test/tools/tools.test.ts
+624 -408
@@ -62,11 +62,14 @@ describe('Tools', () => {
62
63 await context.tools.getRawComposioTools(query);
64
65 - expect(mockClient.tools.list).toHaveBeenCalledWith({
66 - tool_slugs: 'TOOL1,TOOL2',
67 - limit: 9999,
68 - toolkit_versions: 'latest',
69 - });
65 + expect(mockClient.tools.list).toHaveBeenCalledWith(
66 + {
67 + tool_slugs: 'TOOL1,TOOL2',
68 + limit: 9999,
69 + toolkit_versions: 'latest',
70 + },
71 + undefined
72 + );
73 });
74
75 it('should handle toolkit query parameters correctly', async () => {
@@ -81,11 +84,14 @@ describe('Tools', () => {
84
85 await context.tools.getRawComposioTools(query);
86
84 - expect(mockClient.tools.list).toHaveBeenCalledWith({
85 - toolkit_slug: 'github',
86 - important: 'true',
87 - toolkit_versions: 'latest',
88 - });
87 + expect(mockClient.tools.list).toHaveBeenCalledWith(
88 + {
89 + toolkit_slug: 'github',
90 + important: 'true',
91 + toolkit_versions: 'latest',
92 + },
93 + undefined
94 + );
95 });
96
97 it('should respect explicit important=false to opt-out', async () => {
@@ -102,11 +108,14 @@ describe('Tools', () => {
108
109 await context.tools.getRawComposioTools(query);
110
105 - expect(mockClient.tools.list).toHaveBeenCalledWith({
106 - toolkit_slug: 'github',
107 - limit: 10,
108 - toolkit_versions: 'latest',
109 - });
111 + expect(mockClient.tools.list).toHaveBeenCalledWith(
112 + {
113 + toolkit_slug: 'github',
114 + limit: 10,
115 + toolkit_versions: 'latest',
116 + },
117 + undefined
118 + );
119 });
120
121 it('should handle toolkit search parameters correctly', async () => {
@@ -123,12 +132,15 @@ describe('Tools', () => {
132
133 await context.tools.getRawComposioTools(query);
134
126 - expect(mockClient.tools.list).toHaveBeenCalledWith({
127 - toolkit_slug: 'github',
128 - limit: 10,
129 - search: 'test',
130 - toolkit_versions: 'latest',
131 - });
135 + expect(mockClient.tools.list).toHaveBeenCalledWith(
136 + {
137 + toolkit_slug: 'github',
138 + limit: 10,
139 + search: 'test',
140 + toolkit_versions: 'latest',
141 + },
142 + undefined
143 + );
144 });
145
146 it('should handle toolkit scopes parameters correctly', async () => {
@@ -144,12 +156,15 @@ describe('Tools', () => {
156
157 await context.tools.getRawComposioTools(query);
158
147 - expect(mockClient.tools.list).toHaveBeenCalledWith({
148 - toolkit_slug: 'todoist',
149 - important: 'true',
150 - scopes: ['task:add', 'task:read'],
151 - toolkit_versions: 'latest',
152 - });
159 + expect(mockClient.tools.list).toHaveBeenCalledWith(
160 + {
161 + toolkit_slug: 'todoist',
162 + important: 'true',
163 + scopes: ['task:add', 'task:read'],
164 + toolkit_versions: 'latest',
165 + },
166 + undefined
167 + );
168 });
169
170 it('should handle toolkit scopes with search parameters correctly', async () => {
@@ -167,13 +182,16 @@ describe('Tools', () => {
182
183 await context.tools.getRawComposioTools(query);
184
170 - expect(mockClient.tools.list).toHaveBeenCalledWith({
171 - toolkit_slug: 'todoist',
172 - limit: 10,
173 - search: 'add task',
174 - scopes: ['task:add'],
175 - toolkit_versions: 'latest',
176 - });
185 + expect(mockClient.tools.list).toHaveBeenCalledWith(
186 + {
187 + toolkit_slug: 'todoist',
188 + limit: 10,
189 + search: 'add task',
190 + scopes: ['task:add'],
191 + toolkit_versions: 'latest',
192 + },
193 + undefined
194 + );
195 });
196
197 it('should respect explicit important=true', async () => {
@@ -190,12 +208,15 @@ describe('Tools', () => {
208
209 await context.tools.getRawComposioTools(query);
210
193 - expect(mockClient.tools.list).toHaveBeenCalledWith({
194 - toolkit_slug: 'github',
195 - important: 'true',
196 - limit: 10,
197 - toolkit_versions: 'latest',
198 - });
211 + expect(mockClient.tools.list).toHaveBeenCalledWith(
212 + {
213 + toolkit_slug: 'github',
214 + important: 'true',
215 + limit: 10,
216 + toolkit_versions: 'latest',
217 + },
218 + undefined
219 + );
220 });
221
222 it('should NOT auto-apply important when tags are passed with values', async () => {
@@ -212,12 +233,15 @@ describe('Tools', () => {
233
234 await context.tools.getRawComposioTools(query);
235
215 - expect(mockClient.tools.list).toHaveBeenCalledWith({
216 - toolkit_slug: 'github',
217 - tags: ['important', 'custom'],
218 - limit: 10,
219 - toolkit_versions: 'latest',
220 - });
236 + expect(mockClient.tools.list).toHaveBeenCalledWith(
237 + {
238 + toolkit_slug: 'github',
239 + tags: ['important', 'custom'],
240 + limit: 10,
241 + toolkit_versions: 'latest',
242 + },
243 + undefined
244 + );
245 // Should NOT include important: 'true' when tags are provided
246 });
247
@@ -234,11 +258,14 @@ describe('Tools', () => {
258
259 await context.tools.getRawComposioTools(query);
260
237 - expect(mockClient.tools.list).toHaveBeenCalledWith({
238 - toolkit_slug: 'github',
239 - tags: [],
240 - toolkit_versions: 'latest',
241 - });
261 + expect(mockClient.tools.list).toHaveBeenCalledWith(
262 + {
263 + toolkit_slug: 'github',
264 + tags: [],
265 + toolkit_versions: 'latest',
266 + },
267 + undefined
268 + );
269 // Should NOT include important: 'true' when tags array is present (even if empty)
270 });
271
@@ -255,11 +282,14 @@ describe('Tools', () => {
282
283 await context.tools.getRawComposioTools(query);
284
258 - expect(mockClient.tools.list).toHaveBeenCalledWith({
259 - toolkit_slug: 'github',
260 - limit: 10,
261 - toolkit_versions: 'latest',
262 - });
285 + expect(mockClient.tools.list).toHaveBeenCalledWith(
286 + {
287 + toolkit_slug: 'github',
288 + limit: 10,
289 + toolkit_versions: 'latest',
290 + },
291 + undefined
292 + );
293 // Should NOT include important: 'true' when limit is provided
294 });
295
@@ -355,13 +385,23 @@ describe('Tools', () => {
385 const result = await context.tools.getRawToolRouterSessionTools('session_123');
386
387 expect(result.map(tool => tool.slug)).toEqual(['FIRST_TOOL', 'SECOND_TOOL']);
358 - expect(mockClient.toolRouter.session.tools).toHaveBeenNthCalledWith(1, 'session_123', {
359 - limit: 500,
360 - });
361 - expect(mockClient.toolRouter.session.tools).toHaveBeenNthCalledWith(2, 'session_123', {
362 - limit: 500,
363 - cursor: 'next_page',
364 - });
388 + expect(mockClient.toolRouter.session.tools).toHaveBeenNthCalledWith(
389 + 1,
390 + 'session_123',
391 + {
392 + limit: 500,
393 + },
394 + undefined
395 + );
396 + expect(mockClient.toolRouter.session.tools).toHaveBeenNthCalledWith(
397 + 2,
398 + 'session_123',
399 + {
400 + limit: 500,
401 + cursor: 'next_page',
402 + },
403 + undefined
404 + );
405 });
406 });
407
@@ -373,7 +413,11 @@ describe('Tools', () => {
413
414 const result = await context.tools.getRawComposioToolBySlug(slug);
415
376 - expect(mockClient.tools.retrieve).toHaveBeenCalledWith(slug, { toolkit_versions: 'latest' });
416 + expect(mockClient.tools.retrieve).toHaveBeenCalledWith(
417 + slug,
418 + { toolkit_versions: 'latest' },
419 + undefined
420 + );
421 expect(result.slug).toEqual(toolMocks.transformedTool.slug);
422 });
423
@@ -414,9 +458,13 @@ describe('Tools', () => {
458 });
459
460 // Should use 'version' param, not 'toolkit_versions'
417 - expect(mockClient.tools.retrieve).toHaveBeenCalledWith(slug, {
418 - version: explicitVersion,
419 - });
461 + expect(mockClient.tools.retrieve).toHaveBeenCalledWith(
462 + slug,
463 + {
464 + version: explicitVersion,
465 + },
466 + undefined
467 + );
468 });
469
470 it('should use version parameter when provided (latest string)', async () => {
@@ -429,9 +477,13 @@ describe('Tools', () => {
477 });
478
479 // Should use 'version' param with 'latest'
432 - expect(mockClient.tools.retrieve).toHaveBeenCalledWith(slug, {
433 - version: 'latest',
434 - });
480 + expect(mockClient.tools.retrieve).toHaveBeenCalledWith(
481 + slug,
482 + {
483 + version: 'latest',
484 + },
485 + undefined
486 + );
487 });
488
489 it('should use version parameter when provided (version mapping object)', async () => {
@@ -449,9 +501,13 @@ describe('Tools', () => {
501 await toolsWithVersions.getRawComposioToolBySlug(slug);
502
503 // Should use 'toolkit_versions' param with mapping object (not 'version')
452 - expect(mockClient.tools.retrieve).toHaveBeenCalledWith(slug, {
453 - toolkit_versions: versionMapping,
454 - });
504 + expect(mockClient.tools.retrieve).toHaveBeenCalledWith(
505 + slug,
506 + {
507 + toolkit_versions: versionMapping,
508 + },
509 + undefined
510 + );
511 });
512
513 it('should fallback to SDK toolkitVersions when version not provided', async () => {
@@ -463,9 +519,13 @@ describe('Tools', () => {
519 await context.tools.getRawComposioToolBySlug(slug);
520
521 // Should use 'toolkit_versions' param with SDK-level config
466 - expect(mockClient.tools.retrieve).toHaveBeenCalledWith(slug, {
467 - toolkit_versions: 'latest',
468 - });
522 + expect(mockClient.tools.retrieve).toHaveBeenCalledWith(
523 + slug,
524 + {
525 + toolkit_versions: 'latest',
526 + },
527 + undefined
528 + );
529 });
530
531 it('should prioritize explicit version over SDK toolkitVersions', async () => {
@@ -485,9 +545,13 @@ describe('Tools', () => {
545 });
546
547 // Explicit version should take precedence, using 'version' param
488 - expect(mockClient.tools.retrieve).toHaveBeenCalledWith(slug, {
489 - version: explicitVersion,
490 - });
548 + expect(mockClient.tools.retrieve).toHaveBeenCalledWith(
549 + slug,
550 + {
551 + version: explicitVersion,
552 + },
553 + undefined
554 + );
555 });
556
557 it('should support combining version and modifySchema options', async () => {
@@ -505,9 +569,13 @@ describe('Tools', () => {
569 });
570
571 // Should use version param
508 - expect(mockClient.tools.retrieve).toHaveBeenCalledWith(slug, {
509 - version: explicitVersion,
510 - });
572 + expect(mockClient.tools.retrieve).toHaveBeenCalledWith(
573 + slug,
574 + {
575 + version: explicitVersion,
576 + },
577 + undefined
578 + );
579 // Should also apply schema modifier
580 expect(schemaModifier).toHaveBeenCalled();
581 expect(result.description).toEqual('Modified description');
@@ -657,9 +725,13 @@ describe('Tools', () => {
725
726 const result = await context.tools.get(userId, slug);
727
660 - expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(slug, {
661 - modifySchema: undefined,
662 - });
728 + expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(
729 + slug,
730 + {
731 + modifySchema: undefined,
732 + },
733 + undefined
734 + );
735 expect(context.mockProvider.wrapTools).toHaveBeenCalledWith(
736 [toolMocks.transformedTool],
737 expect.any(Function)
@@ -678,7 +750,11 @@ describe('Tools', () => {
750
751 const result = await context.tools.get(userId, filters);
752
681 - expect(getRawComposioToolsSpy).toHaveBeenCalledWith(filters, { modifySchema: undefined });
753 + expect(getRawComposioToolsSpy).toHaveBeenCalledWith(
754 + filters,
755 + { modifySchema: undefined },
756 + undefined
757 + );
758 expect(context.mockProvider.wrapTools).toHaveBeenCalled();
759 expect(result).toEqual('wrapped-tools-collection');
760 });
@@ -697,9 +773,13 @@ describe('Tools', () => {
773
774 await context.tools.get(userId, slug, { modifySchema: schemaModifier });
775
700 - expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(slug, {
701 - modifySchema: schemaModifier,
702 - });
776 + expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(
777 + slug,
778 + {
779 + modifySchema: schemaModifier,
780 + },
781 + undefined
782 + );
783 });
784 });
785
@@ -717,16 +797,20 @@ describe('Tools', () => {
797
798 const result = await context.tools.execute(slug, body);
799
720 - expect(mockClient.tools.execute).toHaveBeenCalledWith(slug, {
721 - allow_tracing: undefined,
722 - connected_account_id: undefined,
723 - custom_auth_params: undefined,
724 - custom_connection_data: undefined,
725 - arguments: body.arguments,
726 - user_id: body.userId,
727 - version: 'latest',
728 - text: undefined,
729 - });
800 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
801 + slug,
802 + {
803 + allow_tracing: undefined,
804 + connected_account_id: undefined,
805 + custom_auth_params: undefined,
806 + custom_connection_data: undefined,
807 + arguments: body.arguments,
808 + user_id: body.userId,
809 + version: 'latest',
810 + text: undefined,
811 + },
812 + undefined
813 + );
814 expect(result).toEqual(toolMocks.toolExecuteResponse);
815 });
816
@@ -743,16 +827,20 @@ describe('Tools', () => {
827
828 const result = await context.tools.execute(slug, body);
829
746 - expect(mockClient.tools.execute).toHaveBeenCalledWith(slug, {
747 - allow_tracing: undefined,
748 - connected_account_id: 'test-connected-account-id',
749 - custom_auth_params: undefined,
750 - custom_connection_data: undefined,
751 - arguments: body.arguments,
752 - user_id: body.userId,
753 - version: 'latest',
754 - text: undefined,
755 - });
830 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
831 + slug,
832 + {
833 + allow_tracing: undefined,
834 + connected_account_id: 'test-connected-account-id',
835 + custom_auth_params: undefined,
836 + custom_connection_data: undefined,
837 + arguments: body.arguments,
838 + user_id: body.userId,
839 + version: 'latest',
840 + text: undefined,
841 + },
842 + undefined
843 + );
844 expect(result).toEqual(toolMocks.toolExecuteResponse);
845 });
846
@@ -774,20 +862,24 @@ describe('Tools', () => {
862
863 const result = await context.tools.execute(slug, body);
864
777 - expect(mockClient.tools.execute).toHaveBeenCalledWith(slug, {
778 - allow_tracing: undefined,
779 - connected_account_id: 'test-connected-account-id',
780 - custom_auth_params: {
781 - base_url: 'https://custom-api.example.com',
782 - parameters: [{ name: 'x-api-key', value: 'test-key', in: 'header' }],
783 - body: { extra: 'data' },
865 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
866 + slug,
867 + {
868 + allow_tracing: undefined,
869 + connected_account_id: 'test-connected-account-id',
870 + custom_auth_params: {
871 + base_url: 'https://custom-api.example.com',
872 + parameters: [{ name: 'x-api-key', value: 'test-key', in: 'header' }],
873 + body: { extra: 'data' },
874 + },
875 + custom_connection_data: undefined,
876 + arguments: body.arguments,
877 + user_id: body.userId,
878 + version: 'latest',
879 + text: undefined,
880 },
785 - custom_connection_data: undefined,
786 - arguments: body.arguments,
787 - user_id: body.userId,
788 - version: 'latest',
789 - text: undefined,
790 - });
881 + undefined
882 + );
883 expect(result).toEqual(toolMocks.toolExecuteResponse);
884 });
885
@@ -805,16 +897,21 @@ describe('Tools', () => {
897 await context.tools.execute(slug, body);
898
899 // Verify getRawComposioToolBySlug was called with version
808 - expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(slug, {
809 - version: explicitVersion,
810 - });
900 + expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(
901 + slug,
902 + {
903 + version: explicitVersion,
904 + },
905 + undefined
906 + );
907
908 // Verify the API execute call received the version
909 expect(mockClient.tools.execute).toHaveBeenCalledWith(
910 slug,
911 expect.objectContaining({
912 version: explicitVersion,
817 - })
913 + }),
914 + undefined
915 );
916 });
917
@@ -832,9 +929,13 @@ describe('Tools', () => {
929 await context.tools.execute(slug, body);
930
931 // Verify getRawComposioToolBySlug was called with version: 'latest'
835 - expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(slug, {
836 - version: 'latest',
837 - });
932 + expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(
933 + slug,
934 + {
935 + version: 'latest',
936 + },
937 + undefined
938 + );
939 });
940
941 it('should not pass version to getRawComposioToolBySlug() when not provided in execute()', async () => {
@@ -850,9 +951,13 @@ describe('Tools', () => {
951 await context.tools.execute(slug, body);
952
953 // Verify getRawComposioToolBySlug was called without version (should fallback to SDK config)
853 - expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(slug, {
854 - version: undefined,
855 - });
954 + expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(
955 + slug,
956 + {
957 + version: undefined,
958 + },
959 + undefined
960 + );
961 });
962 });
963
@@ -896,34 +1001,37 @@ describe('Tools', () => {
1001
1002 const result = await context.tools.proxyExecute(proxyParams);
1003
899 - expect(mockClient.tools.proxy).toHaveBeenCalledWith({
900 - endpoint: '/api/test',
901 - method: 'POST',
902 - body: { data: 'test' },
903 - connected_account_id: 'test-account-id',
904 - parameters: [
905 - {
906 - name: 'Authorization',
907 - type: 'header',
908 - value: 'Bearer token123',
909 - },
910 - {
911 - name: 'Content-Type',
912 - type: 'header',
913 - value: 'application/json',
914 - },
915 - {
916 - name: 'page',
917 - type: 'query',
918 - value: '1',
919 - },
920 - {
921 - name: 'limit',
922 - type: 'query',
923 - value: '10',
924 - },
925 - ],
926 - });
1004 + expect(mockClient.tools.proxy).toHaveBeenCalledWith(
1005 + {
1006 + endpoint: '/api/test',
1007 + method: 'POST',
1008 + body: { data: 'test' },
1009 + connected_account_id: 'test-account-id',
1010 + parameters: [
1011 + {
1012 + name: 'Authorization',
1013 + type: 'header',
1014 + value: 'Bearer token123',
1015 + },
1016 + {
1017 + name: 'Content-Type',
1018 + type: 'header',
1019 + value: 'application/json',
1020 + },
1021 + {
1022 + name: 'page',
1023 + type: 'query',
1024 + value: '1',
1025 + },
1026 + {
1027 + name: 'limit',
1028 + type: 'query',
1029 + value: '10',
1030 + },
1031 + ],
1032 + },
1033 + undefined
1034 + );
1035
1036 expect(result).toEqual(expectedProxyResponse);
1037 });
@@ -955,24 +1063,27 @@ describe('Tools', () => {
1063
1064 const result = await context.tools.proxyExecute(proxyParams);
1065
958 - expect(mockClient.tools.proxy).toHaveBeenCalledWith({
959 - endpoint: '/api/headers-only',
960 - method: 'GET',
961 - body: undefined,
962 - connected_account_id: undefined,
963 - parameters: [
964 - {
965 - name: 'Authorization',
966 - type: 'header',
967 - value: 'Bearer token123',
968 - },
969 - {
970 - name: 'Accept',
971 - type: 'header',
972 - value: 'application/json',
973 - },
974 - ],
975 - });
1066 + expect(mockClient.tools.proxy).toHaveBeenCalledWith(
1067 + {
1068 + endpoint: '/api/headers-only',
1069 + method: 'GET',
1070 + body: undefined,
1071 + connected_account_id: undefined,
1072 + parameters: [
1073 + {
1074 + name: 'Authorization',
1075 + type: 'header',
1076 + value: 'Bearer token123',
1077 + },
1078 + {
1079 + name: 'Accept',
1080 + type: 'header',
1081 + value: 'application/json',
1082 + },
1083 + ],
1084 + },
1085 + undefined
1086 + );
1087
1088 expect(result).toEqual(expectedProxyResponse);
1089 });
@@ -1004,24 +1115,27 @@ describe('Tools', () => {
1115
1116 const result = await context.tools.proxyExecute(proxyParams);
1117
1007 - expect(mockClient.tools.proxy).toHaveBeenCalledWith({
1008 - endpoint: '/api/search',
1009 - method: 'GET',
1010 - body: undefined,
1011 - connected_account_id: undefined,
1012 - parameters: [
1013 - {
1014 - name: 'q',
1015 - type: 'query',
1016 - value: 'test search',
1017 - },
1018 - {
1019 - name: 'page',
1020 - type: 'query',
1021 - value: '2',
1022 - },
1023 - ],
1024 - });
1118 + expect(mockClient.tools.proxy).toHaveBeenCalledWith(
1119 + {
1120 + endpoint: '/api/search',
1121 + method: 'GET',
1122 + body: undefined,
1123 + connected_account_id: undefined,
1124 + parameters: [
1125 + {
1126 + name: 'q',
1127 + type: 'query',
1128 + value: 'test search',
1129 + },
1130 + {
1131 + name: 'page',
1132 + type: 'query',
1133 + value: '2',
1134 + },
1135 + ],
1136 + },
1137 + undefined
1138 + );
1139
1140 expect(result).toEqual(expectedProxyResponse);
1141 });
@@ -1043,13 +1157,16 @@ describe('Tools', () => {
1157
1158 const result = await context.tools.proxyExecute(proxyParams);
1159
1046 - expect(mockClient.tools.proxy).toHaveBeenCalledWith({
1047 - endpoint: '/api/no-params',
1048 - method: 'PUT',
1049 - body: { update: 'data' },
1050 - connected_account_id: 'test-account-id',
1051 - parameters: [],
1052 - });
1160 + expect(mockClient.tools.proxy).toHaveBeenCalledWith(
1161 + {
1162 + endpoint: '/api/no-params',
1163 + method: 'PUT',
1164 + body: { update: 'data' },
1165 + connected_account_id: 'test-account-id',
1166 + parameters: [],
1167 + },
1168 + undefined
1169 + );
1170
1171 expect(result).toEqual(expectedProxyResponse);
1172 });
@@ -1081,24 +1198,27 @@ describe('Tools', () => {
1198
1199 const result = await context.tools.proxyExecute(proxyParams);
1200
1084 - expect(mockClient.tools.proxy).toHaveBeenCalledWith({
1085 - endpoint: '/api/numeric',
1086 - method: 'GET',
1087 - body: undefined,
1088 - connected_account_id: undefined,
1089 - parameters: [
1090 - {
1091 - name: 'count',
1092 - type: 'query',
1093 - value: '42',
1094 - },
1095 - {
1096 - name: 'Version',
1097 - type: 'header',
1098 - value: '1.5',
1099 - },
1100 - ],
1101 - });
1201 + expect(mockClient.tools.proxy).toHaveBeenCalledWith(
1202 + {
1203 + endpoint: '/api/numeric',
1204 + method: 'GET',
1205 + body: undefined,
1206 + connected_account_id: undefined,
1207 + parameters: [
1208 + {
1209 + name: 'count',
1210 + type: 'query',
1211 + value: '42',
1212 + },
1213 + {
1214 + name: 'Version',
1215 + type: 'header',
1216 + value: '1.5',
1217 + },
1218 + ],
1219 + },
1220 + undefined
1221 + );
1222
1223 expect(result).toEqual(expectedProxyResponse);
1224 });
@@ -1141,11 +1261,15 @@ describe('Tools', () => {
1261
1262 const result = await context.tools.executeSessionTool(toolSlug, body);
1263
1144 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
1145 - tool_slug: toolSlug,
1146 - arguments: body.arguments,
1147 - enable_auto_workbench_offload: true,
1148 - });
1264 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
1265 + sessionId,
1266 + {
1267 + tool_slug: toolSlug,
1268 + arguments: body.arguments,
1269 + enable_auto_workbench_offload: true,
1270 + },
1271 + undefined
1272 + );
1273 expect(result).toEqual({
1274 data: { results: true },
1275 error: null,
@@ -1180,14 +1304,18 @@ describe('Tools', () => {
1304 },
1305 });
1306
1183 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
1184 - tool_slug: toolSlug,
1185 - arguments: body.arguments,
1186 - enable_auto_workbench_offload: true,
1187 - experimental: {
1188 - custom_tools: [expect.objectContaining({ slug: 'GREP' })],
1307 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
1308 + sessionId,
1309 + {
1310 + tool_slug: toolSlug,
1311 + arguments: body.arguments,
1312 + enable_auto_workbench_offload: true,
1313 + experimental: {
1314 + custom_tools: [expect.objectContaining({ slug: 'GREP' })],
1315 + },
1316 },
1190 - });
1317 + undefined
1318 + );
1319 });
1320
1321 it('should throw validation error for invalid parameters', async () => {
@@ -1250,11 +1378,15 @@ describe('Tools', () => {
1378 params: { query: 'original' },
1379 });
1380
1253 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
1254 - tool_slug: toolSlug,
1255 - arguments: { query: 'modified' },
1256 - enable_auto_workbench_offload: true,
1257 - });
1381 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
1382 + sessionId,
1383 + {
1384 + tool_slug: toolSlug,
1385 + arguments: { query: 'modified' },
1386 + enable_auto_workbench_offload: true,
1387 + },
1388 + undefined
1389 + );
1390 });
1391
1392 it('should apply afterExecute modifier', async () => {
@@ -1394,11 +1526,15 @@ describe('Tools', () => {
1526 // Call the captured execute function
1527 const result = await capturedExecuteFn!('COMPOSIO_TOOL', { query: 'test' });
1528
1397 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
1398 - tool_slug: 'COMPOSIO_TOOL',
1399 - arguments: { query: 'test' },
1400 - enable_auto_workbench_offload: true,
1401 - });
1529 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
1530 + sessionId,
1531 + {
1532 + tool_slug: 'COMPOSIO_TOOL',
1533 + arguments: { query: 'test' },
1534 + enable_auto_workbench_offload: true,
1535 + },
1536 + undefined
1537 + );
1538 expect(result).toEqual({
1539 data: { results: true },
1540 error: null,
@@ -1435,11 +1571,15 @@ describe('Tools', () => {
1571 await capturedExecuteFn!('COMPOSIO_TOOL', { query: 'test' });
1572
1573 expect(modifiers.beforeExecute).toHaveBeenCalled();
1438 - expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(sessionId, {
1439 - tool_slug: 'COMPOSIO_TOOL',
1440 - arguments: { query: 'test', modified: true },
1441 - enable_auto_workbench_offload: true,
1442 - });
1574 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
1575 + sessionId,
1576 + {
1577 + tool_slug: 'COMPOSIO_TOOL',
1578 + arguments: { query: 'test', modified: true },
1579 + enable_auto_workbench_offload: true,
1580 + },
1581 + undefined
1582 + );
1583 });
1584
1585 it('should handle multiple tools', async () => {
@@ -1481,11 +1621,14 @@ describe('Tools', () => {
1621
1622 await context.tools.getRawComposioTools({ tools: ['TEST_TOOL'] });
1623
1484 - expect(mockClient.tools.list).toHaveBeenCalledWith({
1485 - tool_slugs: 'TEST_TOOL',
1486 - limit: 9999,
1487 - toolkit_versions: 'latest',
1488 - });
1624 + expect(mockClient.tools.list).toHaveBeenCalledWith(
1625 + {
1626 + tool_slugs: 'TEST_TOOL',
1627 + limit: 9999,
1628 + toolkit_versions: 'latest',
1629 + },
1630 + undefined
1631 + );
1632 });
1633
1634 it('should pass global version string when configured', async () => {
@@ -1502,11 +1645,14 @@ describe('Tools', () => {
1645
1646 await tools.getRawComposioTools({ toolkits: ['github'] });
1647
1505 - expect(mockClient.tools.list).toHaveBeenCalledWith({
1506 - toolkit_slug: 'github',
1507 - important: 'true',
1508 - toolkit_versions: '20251201_03',
1509 - });
1648 + expect(mockClient.tools.list).toHaveBeenCalledWith(
1649 + {
1650 + toolkit_slug: 'github',
1651 + important: 'true',
1652 + toolkit_versions: '20251201_03',
1653 + },
1654 + undefined
1655 + );
1656 });
1657
1658 it('should pass toolkit-specific versions when configured as object', async () => {
@@ -1527,15 +1673,18 @@ describe('Tools', () => {
1673
1674 await tools.getRawComposioTools({ toolkits: ['github'] });
1675
1530 - expect(mockClient.tools.list).toHaveBeenCalledWith({
1531 - toolkit_slug: 'github',
1532 - important: 'true',
1533 - toolkit_versions: {
1534 - github: '20251201_01',
1535 - slack: 'latest',
1536 - gmail: '20251201_05',
1676 + expect(mockClient.tools.list).toHaveBeenCalledWith(
1677 + {
1678 + toolkit_slug: 'github',
1679 + important: 'true',
1680 + toolkit_versions: {
1681 + github: '20251201_01',
1682 + slack: 'latest',
1683 + gmail: '20251201_05',
1684 + },
1685 },
1538 - });
1686 + undefined
1687 + );
1688 });
1689
1690 it('should pass versions when fetching tools by tool slugs', async () => {
@@ -1555,14 +1704,17 @@ describe('Tools', () => {
1704
1705 await tools.getRawComposioTools({ tools: ['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE'] });
1706
1558 - expect(mockClient.tools.list).toHaveBeenCalledWith({
1559 - tool_slugs: 'GITHUB_CREATE_ISSUE,SLACK_SEND_MESSAGE',
1560 - limit: 9999,
1561 - toolkit_versions: {
1562 - github: '20251201_01',
1563 - slack: 'latest',
1707 + expect(mockClient.tools.list).toHaveBeenCalledWith(
1708 + {
1709 + tool_slugs: 'GITHUB_CREATE_ISSUE,SLACK_SEND_MESSAGE',
1710 + limit: 9999,
1711 + toolkit_versions: {
1712 + github: '20251201_01',
1713 + slack: 'latest',
1714 + },
1715 },
1565 - });
1716 + undefined
1717 + );
1718 });
1719
1720 it('should pass versions when searching tools', async () => {
@@ -1579,10 +1731,13 @@ describe('Tools', () => {
1731
1732 await tools.getRawComposioTools({ search: 'create issue' });
1733
1582 - expect(mockClient.tools.list).toHaveBeenCalledWith({
1583 - search: 'create issue',
1584 - toolkit_versions: 'latest',
1585 - });
1734 + expect(mockClient.tools.list).toHaveBeenCalledWith(
1735 + {
1736 + search: 'create issue',
1737 + toolkit_versions: 'latest',
1738 + },
1739 + undefined
1740 + );
1741 });
1742 });
1743
@@ -1594,9 +1749,13 @@ describe('Tools', () => {
1749
1750 await context.tools.getRawComposioToolBySlug('GITHUB_CREATE_ISSUE');
1751
1597 - expect(mockClient.tools.retrieve).toHaveBeenCalledWith('GITHUB_CREATE_ISSUE', {
1598 - toolkit_versions: 'latest',
1599 - });
1752 + expect(mockClient.tools.retrieve).toHaveBeenCalledWith(
1753 + 'GITHUB_CREATE_ISSUE',
1754 + {
1755 + toolkit_versions: 'latest',
1756 + },
1757 + undefined
1758 + );
1759 });
1760
1761 it('should pass global version when retrieving single tool', async () => {
@@ -1610,9 +1769,13 @@ describe('Tools', () => {
1769
1770 await tools.getRawComposioToolBySlug('GITHUB_CREATE_ISSUE');
1771
1613 - expect(mockClient.tools.retrieve).toHaveBeenCalledWith('GITHUB_CREATE_ISSUE', {
1614 - toolkit_versions: '20251201_03',
1615 - });
1772 + expect(mockClient.tools.retrieve).toHaveBeenCalledWith(
1773 + 'GITHUB_CREATE_ISSUE',
1774 + {
1775 + toolkit_versions: '20251201_03',
1776 + },
1777 + undefined
1778 + );
1779 });
1780
1781 it('should pass toolkit-specific versions when retrieving single tool', async () => {
@@ -1630,13 +1793,17 @@ describe('Tools', () => {
1793
1794 await tools.getRawComposioToolBySlug('SLACK_SEND_MESSAGE');
1795
1633 - expect(mockClient.tools.retrieve).toHaveBeenCalledWith('SLACK_SEND_MESSAGE', {
1634 - toolkit_versions: {
1635 - github: '20251201_01',
1636 - slack: 'latest',
1637 - gmail: '20251201_05',
1796 + expect(mockClient.tools.retrieve).toHaveBeenCalledWith(
1797 + 'SLACK_SEND_MESSAGE',
1798 + {
1799 + toolkit_versions: {
1800 + github: '20251201_01',
1801 + slack: 'latest',
1802 + gmail: '20251201_05',
1803 + },
1804 },
1639 - });
1805 + undefined
1806 + );
1807 });
1808 });
1809
@@ -1653,16 +1820,20 @@ describe('Tools', () => {
1820
1821 await context.tools.execute('GITHUB_CREATE_ISSUE', executeParams);
1822
1656 - expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {
1657 - allow_tracing: undefined,
1658 - connected_account_id: 'test-account',
1659 - custom_auth_params: undefined,
1660 - custom_connection_data: undefined,
1661 - arguments: { title: 'Test Issue' },
1662 - user_id: undefined,
1663 - version: 'latest', // should use latest as default
1664 - text: undefined,
1665 - });
1823 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
1824 + 'COMPOSIO_TOOL',
1825 + {
1826 + allow_tracing: undefined,
1827 + connected_account_id: 'test-account',
1828 + custom_auth_params: undefined,
1829 + custom_connection_data: undefined,
1830 + arguments: { title: 'Test Issue' },
1831 + user_id: undefined,
1832 + version: 'latest', // should use latest as default
1833 + text: undefined,
1834 + },
1835 + undefined
1836 + );
1837 });
1838
1839 it('should use global version when configured', async () => {
@@ -1680,16 +1851,20 @@ describe('Tools', () => {
1851
1852 await tools.execute('GITHUB_CREATE_ISSUE', executeParams);
1853
1683 - expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {
1684 - allow_tracing: undefined,
1685 - connected_account_id: 'test-account',
1686 - custom_auth_params: undefined,
1687 - custom_connection_data: undefined,
1688 - arguments: { title: 'Test Issue' },
1689 - user_id: undefined,
1690 - version: '20251201_03', // should use global version
1691 - text: undefined,
1692 - });
1854 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
1855 + 'COMPOSIO_TOOL',
1856 + {
1857 + allow_tracing: undefined,
1858 + connected_account_id: 'test-account',
1859 + custom_auth_params: undefined,
1860 + custom_connection_data: undefined,
1861 + arguments: { title: 'Test Issue' },
1862 + user_id: undefined,
1863 + version: '20251201_03', // should use global version
1864 + text: undefined,
1865 + },
1866 + undefined
1867 + );
1868 });
1869
1870 it('should use toolkit-specific version when configured as object', async () => {
@@ -1721,16 +1896,20 @@ describe('Tools', () => {
1896
1897 await tools.execute('GITHUB_CREATE_ISSUE', executeParams);
1898
1724 - expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {
1725 - allow_tracing: undefined,
1726 - connected_account_id: 'test-account',
1727 - custom_auth_params: undefined,
1728 - custom_connection_data: undefined,
1729 - arguments: { title: 'Test Issue' },
1730 - user_id: undefined,
1731 - version: '20251201_01', // should use test-toolkit-specific version
1732 - text: undefined,
1733 - });
1899 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
1900 + 'COMPOSIO_TOOL',
1901 + {
1902 + allow_tracing: undefined,
1903 + connected_account_id: 'test-account',
1904 + custom_auth_params: undefined,
1905 + custom_connection_data: undefined,
1906 + arguments: { title: 'Test Issue' },
1907 + user_id: undefined,
1908 + version: '20251201_01', // should use test-toolkit-specific version
1909 + text: undefined,
1910 + },
1911 + undefined
1912 + );
1913 });
1914
1915 it('should use fallback to "latest" when toolkit not in version mapping', async () => {
@@ -1760,16 +1939,20 @@ describe('Tools', () => {
1939
1940 await tools.execute('NOTION_CREATE_PAGE', executeParams);
1941
1763 - expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {
1764 - allow_tracing: undefined,
1765 - connected_account_id: 'test-account',
1766 - custom_auth_params: undefined,
1767 - custom_connection_data: undefined,
1768 - arguments: { title: 'Test Page' },
1769 - user_id: undefined,
1770 - version: 'latest', // should fallback to latest for unknown toolkit
1771 - text: undefined,
1772 - });
1942 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
1943 + 'COMPOSIO_TOOL',
1944 + {
1945 + allow_tracing: undefined,
1946 + connected_account_id: 'test-account',
1947 + custom_auth_params: undefined,
1948 + custom_connection_data: undefined,
1949 + arguments: { title: 'Test Page' },
1950 + user_id: undefined,
1951 + version: 'latest', // should fallback to latest for unknown toolkit
1952 + text: undefined,
1953 + },
1954 + undefined
1955 + );
1956 });
1957
1958 it('should prioritize explicit version parameter over configured versions', async () => {
@@ -1792,16 +1975,20 @@ describe('Tools', () => {
1975
1976 await tools.execute('GITHUB_CREATE_ISSUE', executeParams);
1977
1795 - expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {
1796 - allow_tracing: undefined,
1797 - connected_account_id: 'test-account',
1798 - custom_auth_params: undefined,
1799 - custom_connection_data: undefined,
1800 - arguments: { title: 'Test Issue' },
1801 - user_id: undefined,
1802 - version: '20251201_03', // explicit version takes precedence
1803 - text: undefined,
1804 - });
1978 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
1979 + 'COMPOSIO_TOOL',
1980 + {
1981 + allow_tracing: undefined,
1982 + connected_account_id: 'test-account',
1983 + custom_auth_params: undefined,
1984 + custom_connection_data: undefined,
1985 + arguments: { title: 'Test Issue' },
1986 + user_id: undefined,
1987 + version: '20251201_03', // explicit version takes precedence
1988 + text: undefined,
1989 + },
1990 + undefined
1991 + );
1992 });
1993
1994 it('should handle tool without toolkit gracefully', async () => {
@@ -1832,16 +2019,20 @@ describe('Tools', () => {
2019
2020 await tools.execute('SOME_CUSTOM_TOOL', executeParams);
2021
1835 - expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {
1836 - allow_tracing: undefined,
1837 - connected_account_id: 'test-account',
1838 - custom_auth_params: undefined,
1839 - custom_connection_data: undefined,
1840 - arguments: { query: 'test' },
1841 - user_id: undefined,
1842 - version: 'latest', // should fallback to latest for unknown toolkit
1843 - text: undefined,
1844 - });
2022 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
2023 + 'COMPOSIO_TOOL',
2024 + {
2025 + allow_tracing: undefined,
2026 + connected_account_id: 'test-account',
2027 + custom_auth_params: undefined,
2028 + custom_connection_data: undefined,
2029 + arguments: { query: 'test' },
2030 + user_id: undefined,
2031 + version: 'latest', // should fallback to latest for unknown toolkit
2032 + text: undefined,
2033 + },
2034 + undefined
2035 + );
2036 });
2037 });
2038
@@ -1878,14 +2069,17 @@ describe('Tools', () => {
2069
2070 await tools.getRawComposioTools({ toolkits: ['github'] });
2071
1881 - expect(mockClient.tools.list).toHaveBeenCalledWith({
1882 - toolkit_slug: 'github',
1883 - important: 'true',
1884 - toolkit_versions: {
1885 - github: '20251201_08',
1886 - slack: 'latest',
2072 + expect(mockClient.tools.list).toHaveBeenCalledWith(
2073 + {
2074 + toolkit_slug: 'github',
2075 + important: 'true',
2076 + toolkit_versions: {
2077 + github: '20251201_08',
2078 + slack: 'latest',
2079 + },
2080 },
1888 - });
2081 + undefined
2082 + );
2083 });
2084
2085 it('should prioritize user config over environment variables', async () => {
@@ -1909,14 +2103,17 @@ describe('Tools', () => {
2103
2104 await tools.getRawComposioTools({ toolkits: ['github'] });
2105
1912 - expect(mockClient.tools.list).toHaveBeenCalledWith({
1913 - toolkit_slug: 'github',
1914 - important: 'true',
1915 - toolkit_versions: {
1916 - github: '20251201_04', // user config wins
1917 - gmail: '20251201_05', // from user config
2106 + expect(mockClient.tools.list).toHaveBeenCalledWith(
2107 + {
2108 + toolkit_slug: 'github',
2109 + important: 'true',
2110 + toolkit_versions: {
2111 + github: '20251201_04', // user config wins
2112 + gmail: '20251201_05', // from user config
2113 + },
2114 },
1919 - });
2115 + undefined
2116 + );
2117 });
2118
2119 it('should use global version string to override everything', async () => {
@@ -1937,11 +2134,14 @@ describe('Tools', () => {
2134
2135 await tools.getRawComposioTools({ toolkits: ['github'] });
2136
1940 - expect(mockClient.tools.list).toHaveBeenCalledWith({
1941 - toolkit_slug: 'github',
1942 - important: 'true',
1943 - toolkit_versions: '20251201_09', // global version ignores env vars
1944 - });
2137 + expect(mockClient.tools.list).toHaveBeenCalledWith(
2138 + {
2139 + toolkit_slug: 'github',
2140 + important: 'true',
2141 + toolkit_versions: '20251201_09', // global version ignores env vars
2142 + },
2143 + undefined
2144 + );
2145 });
2146 });
2147
@@ -1989,16 +2189,20 @@ describe('Tools', () => {
2189 const result = await context.tools.execute('GITHUB_CREATE_ISSUE', executeParams);
2190
2191 expect(result).toEqual(toolMocks.toolExecuteResponse);
1992 - expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {
1993 - allow_tracing: undefined,
1994 - connected_account_id: 'test-account',
1995 - custom_auth_params: undefined,
1996 - custom_connection_data: undefined,
1997 - arguments: { title: 'Test Issue' },
1998 - user_id: undefined,
1999 - version: 'latest',
2000 - text: undefined,
2001 - });
2192 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
2193 + 'COMPOSIO_TOOL',
2194 + {
2195 + allow_tracing: undefined,
2196 + connected_account_id: 'test-account',
2197 + custom_auth_params: undefined,
2198 + custom_connection_data: undefined,
2199 + arguments: { title: 'Test Issue' },
2200 + user_id: undefined,
2201 + version: 'latest',
2202 + text: undefined,
2203 + },
2204 + undefined
2205 + );
2206 });
2207
2208 it('should succeed when executing with a specific version (not "latest") without dangerouslySkipVersionCheck', async () => {
@@ -2028,16 +2232,20 @@ describe('Tools', () => {
2232 const result = await tools.execute('GITHUB_CREATE_ISSUE', executeParams);
2233
2234 expect(result).toEqual(toolMocks.toolExecuteResponse);
2031 - expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {
2032 - allow_tracing: undefined,
2033 - connected_account_id: 'test-account',
2034 - custom_auth_params: undefined,
2035 - custom_connection_data: undefined,
2036 - arguments: { title: 'Test Issue' },
2037 - user_id: undefined,
2038 - version: '20251201_01', // specific version should work without skip flag
2039 - text: undefined,
2040 - });
2235 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
2236 + 'COMPOSIO_TOOL',
2237 + {
2238 + allow_tracing: undefined,
2239 + connected_account_id: 'test-account',
2240 + custom_auth_params: undefined,
2241 + custom_connection_data: undefined,
2242 + arguments: { title: 'Test Issue' },
2243 + user_id: undefined,
2244 + version: '20251201_01', // specific version should work without skip flag
2245 + text: undefined,
2246 + },
2247 + undefined
2248 + );
2249 });
2250
2251 it('should succeed when explicit version parameter overrides "latest" config', async () => {
@@ -2054,16 +2262,20 @@ describe('Tools', () => {
2262 const result = await context.tools.execute('GITHUB_CREATE_ISSUE', executeParams);
2263
2264 expect(result).toEqual(toolMocks.toolExecuteResponse);
2057 - expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {
2058 - allow_tracing: undefined,
2059 - connected_account_id: 'test-account',
2060 - custom_auth_params: undefined,
2061 - custom_connection_data: undefined,
2062 - arguments: { title: 'Test Issue' },
2063 - user_id: undefined,
2064 - version: '20251201_03',
2065 - text: undefined,
2066 - });
2265 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
2266 + 'COMPOSIO_TOOL',
2267 + {
2268 + allow_tracing: undefined,
2269 + connected_account_id: 'test-account',
2270 + custom_auth_params: undefined,
2271 + custom_connection_data: undefined,
2272 + arguments: { title: 'Test Issue' },
2273 + user_id: undefined,
2274 + version: '20251201_03',
2275 + text: undefined,
2276 + },
2277 + undefined
2278 + );
2279 });
2280
2281 it('should throw error when explicit version parameter is "latest" without dangerouslySkipVersionCheck', async () => {
@@ -2173,16 +2385,20 @@ describe('Tools', () => {
2385 const result = await storedExecuteToolFn('GITHUB_CREATE_ISSUE', { title: 'Test Issue' });
2386
2387 expect(result).toEqual(toolMocks.toolExecuteResponse);
2176 - expect(mockClient.tools.execute).toHaveBeenCalledWith('COMPOSIO_TOOL', {
2177 - allow_tracing: undefined,
2178 - connected_account_id: undefined,
2179 - custom_auth_params: undefined,
2180 - custom_connection_data: undefined,
2181 - arguments: { title: 'Test Issue' },
2182 - user_id: userId,
2183 - version: 'latest',
2184 - text: undefined,
2185 - });
2388 + expect(mockClient.tools.execute).toHaveBeenCalledWith(
2389 + 'COMPOSIO_TOOL',
2390 + {
2391 + allow_tracing: undefined,
2392 + connected_account_id: undefined,
2393 + custom_auth_params: undefined,
2394 + custom_connection_data: undefined,
2395 + arguments: { title: 'Test Issue' },
2396 + user_id: userId,
2397 + version: 'latest',
2398 + text: undefined,
2399 + },
2400 + undefined
2401 + );
2402 });
2403 });
2404 });
ts/packages/core/test/utils/fileUtils.test.ts
+1 -1
@@ -107,7 +107,7 @@ describe('fileUtils', () => {
107 });
108
109 expect(result.name).toBe('document.pdf');
110 - expect(mockFetch).toHaveBeenCalledWith(urlWithQuery);
110 + expect(mockFetch).toHaveBeenCalledWith(urlWithQuery, { signal: undefined });
111 });
112
113 it('should generate filename when URL has no filename', async () => {
ts/packages/core/test/utils/mocks/client.mock.ts
+14
@@ -12,9 +12,23 @@ export const mockClient = {
12 connectedAccounts: {
13 list: vi.fn(),
14 get: vi.fn(),
15 + retrieve: vi.fn(),
16 + delete: vi.fn(),
17 + refresh: vi.fn(),
18 + updateStatus: vi.fn(),
19 },
20 toolkits: {
21 + list: vi.fn(),
22 + retrieve: vi.fn(),
23 + retrieveCategories: vi.fn(),
24 + },
25 + authConfigs: {
26 + list: vi.fn(),
27 + create: vi.fn(),
28 retrieve: vi.fn(),
29 + update: vi.fn(),
30 + delete: vi.fn(),
31 + updateStatus: vi.fn(),
32 },
33 toolRouter: {
34 session: {