@composio/core 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/{CustomTool-C4tv-GL1.mjs → CustomTool-BMlZfJVz.mjs} +16 -6
  2. package/dist/{CustomTool-BKhHv2hJ.d.mts → CustomTool-CB5vm1Jc.d.mts} +1 -1
  3. package/dist/{FileModifierErrors-B8V8_3VE.mjs → FileModifierErrors-BqFmpRsm.mjs} +1 -1
  4. package/dist/{FileToolModifier.utils.neutral-D_YkHwZP.mjs → FileToolModifier.utils.neutral-DWFpnsj2.mjs} +4 -2
  5. package/dist/{SsrfErrors-DNJt57GL.mjs → SsrfErrors-C91YhASE.mjs} +137 -13
  6. package/dist/{Telemetry-CBtSnWrm.mjs → Telemetry-HlftxMx6.mjs} +2 -34
  7. package/dist/{cancellation-jUVItfHw.mjs → cancellation-CXpfmiVo.mjs} +7 -5
  8. package/dist/{composio-CldtZUyC.d.mts → composio-DLGaeN70.d.mts} +333 -32
  9. package/dist/{customTool.types-DC5fPOOi.d.mts → customTool.types-BAmEh3MB.d.mts} +131 -38
  10. package/dist/docs/reference/sdk-reference/typescript/auth-configs.mdx +2 -2
  11. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +3 -13
  12. package/dist/docs/reference/sdk-reference/typescript/session.mdx +50 -6
  13. package/dist/docs/reference/sdk-reference/typescript/toolkits.mdx +4 -4
  14. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +33 -23
  15. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +3 -2
  16. package/dist/{errors-DyZt79fi.mjs → errors-BuEKehbI.mjs} +23 -3
  17. package/dist/experimental/index.d.mts +2 -2
  18. package/dist/experimental/index.mjs +1 -1
  19. package/dist/{fileUtils.node-BwpUOF0s.mjs → fileUtils.node-L7XD8UPr.mjs} +11 -9
  20. package/dist/index.d.mts +164 -104
  21. package/dist/index.mjs +382 -153
  22. package/dist/models/Files.node.d.mts +2 -3
  23. package/dist/models/Files.node.mjs +2 -2
  24. package/dist/models/Files.workerd.d.mts +2 -3
  25. package/dist/platform/node.d.mts +2 -3
  26. package/dist/platform/workerd.d.mts +2 -3
  27. package/dist/{sensitiveFileUploadPaths-B0w8dqpv.mjs → sensitiveFileUploadPaths-B6pBt9lO.mjs} +10 -7
  28. package/dist/{ssrfGuard.node-DlxO8uzr.mjs → ssrfGuard.node-B9xQB4za.mjs} +197 -30
  29. package/dist/{types-BgsRW-XH.d.mts → types-CxLPO0Xq.d.mts} +2 -2
  30. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +3 -4
  31. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +3 -4
  32. package/dist/utils/modifiers/FileToolModifier.node.d.mts +3 -4
  33. package/dist/utils/modifiers/FileToolModifier.node.mjs +6 -6
  34. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +3 -4
  35. package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
  36. package/dist/utils/ssrfGuard.node.d.mts +19 -10
  37. package/dist/utils/ssrfGuard.node.mjs +1 -1
  38. package/dist/utils/ssrfGuard.workerd.d.mts +12 -4
  39. package/dist/utils/ssrfGuard.workerd.mjs +2 -2
  40. package/package.json +26 -8
  41. package/src/errors/ToolErrors.ts +24 -0
  42. package/src/index.ts +4 -0
  43. package/src/models/CustomTool.ts +41 -6
  44. package/src/models/MCP.ts +29 -15
  45. package/src/models/RemoteFile.ts +54 -36
  46. package/src/models/ToolRouter.ts +1 -0
  47. package/src/models/ToolRouterSession.ts +115 -13
  48. package/src/models/Toolkits.ts +1 -2
  49. package/src/models/Tools.ts +55 -25
  50. package/src/models/Triggers.ts +22 -2
  51. package/src/services/pusher/Pusher.ts +29 -10
  52. package/src/telemetry/redact.ts +133 -6
  53. package/src/types/toolRouter.types.ts +54 -3
  54. package/src/types/toolkit.types.ts +17 -0
  55. package/src/utils/fileUtils.node.ts +10 -2
  56. package/src/utils/jsonSchema.ts +4 -1
  57. package/src/utils/logger.ts +6 -6
  58. package/src/utils/pinnedDispatcher.node.ts +109 -13
  59. package/src/utils/sdk.ts +1 -1
  60. package/src/utils/ssrfGuard.node.ts +153 -27
  61. package/src/utils/ssrfGuard.workerd.ts +15 -1
  62. package/src/utils/transformers/toolkits.ts +79 -2
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "engines": {
5
5
  "node": ">=22.22.3"
6
6
  },
7
- "version": "0.18.0",
7
+ "version": "0.19.0",
8
8
  "description": "",
9
9
  "main": "dist/index.mjs",
10
10
  "publishConfig": {
@@ -73,6 +73,24 @@
73
73
  "types": "./dist/utils/json-schema.d.mts",
74
74
  "default": "./dist/utils/json-schema.mjs"
75
75
  },
76
+ "./utils/ssrf-guard": {
77
+ "workerd": {
78
+ "types": "./dist/utils/ssrfGuard.workerd.d.mts",
79
+ "default": "./dist/utils/ssrfGuard.workerd.mjs"
80
+ },
81
+ "edge-light": {
82
+ "types": "./dist/utils/ssrfGuard.workerd.d.mts",
83
+ "default": "./dist/utils/ssrfGuard.workerd.mjs"
84
+ },
85
+ "node": {
86
+ "types": "./dist/utils/ssrfGuard.node.d.mts",
87
+ "default": "./dist/utils/ssrfGuard.node.mjs"
88
+ },
89
+ "default": {
90
+ "types": "./dist/utils/ssrfGuard.node.d.mts",
91
+ "default": "./dist/utils/ssrfGuard.node.mjs"
92
+ }
93
+ },
76
94
  "./generated": {
77
95
  "types": "./generated/index.d.ts",
78
96
  "default": "./generated/index.js"
@@ -94,12 +112,12 @@
94
112
  "devDependencies": {
95
113
  "@type-challenges/utils": "^0.1.1",
96
114
  "@types/semver": "^7.8.0",
97
- "tsdown": "^0.22.14",
98
- "tsx": "^4.23.12",
115
+ "tsdown": "^0.23.0",
116
+ "tsx": "^4.23.13",
99
117
  "typedoc": "^0.28.20",
100
118
  "typescript": "npm:@typescript/typescript6@^6.0.2",
101
- "vitest": "^4.1.11",
102
- "zod": "^4.4.3"
119
+ "vitest": "^5.0.1",
120
+ "zod": "^4.5.4"
103
121
  },
104
122
  "peerDependencies": {
105
123
  "zod": ">=3.25.76 <5"
@@ -108,13 +126,13 @@
108
126
  "@composio/client": "0.1.0-alpha.76",
109
127
  "@types/json-schema": "^7.0.15",
110
128
  "is-fs-case-sensitive": "^2.0.0",
111
- "openai": "^7.2.0",
129
+ "openai": "^7.15.0",
112
130
  "picocolors": "^1.1.1",
113
131
  "pusher-js": "^8.6.0",
114
132
  "semver": "^7.8.5",
115
- "undici": "^7.29.0",
133
+ "undici": "^7.29.1",
116
134
  "zod-to-json-schema": "^3.25.2",
117
- "@composio/json-schema-to-zod": "0.3.1"
135
+ "@composio/json-schema-to-zod": "0.3.3"
118
136
  },
119
137
  "gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064",
120
138
  "repository": {
@@ -5,6 +5,7 @@ import { ComposioConnectedAccountNotFoundError } from './ConnectedAccountsErrors
5
5
  export const ToolErrorCodes = {
6
6
  TOOLSET_NOT_DEFINED: 'TOOLSET_NOT_DEFINED',
7
7
  TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',
8
+ TOOL_FETCH_ERROR: 'TOOL_FETCH_ERROR',
8
9
  INVALID_MODIFIER: 'INVALID_MODIFIER',
9
10
  TOOL_EXECUTION_ERROR: 'TOOL_EXECUTION_ERROR',
10
11
  INVALID_TOOL_ARGUMENTS: 'INVALID_TOOL_ARGUMENTS',
@@ -45,6 +46,29 @@ export class ComposioToolNotFoundError extends ComposioError {
45
46
  }
46
47
  }
47
48
 
49
+ /**
50
+ * Error thrown when a tool schema could not be fetched for a reason other than
51
+ * the tool not existing (for example an invalid API key, a server error, or a
52
+ * network failure). The underlying client error is preserved as `cause`.
53
+ */
54
+ export class ComposioToolFetchError extends ComposioError {
55
+ constructor(
56
+ message: string = 'Failed to fetch tool',
57
+ options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
58
+ ) {
59
+ super(message, {
60
+ ...options,
61
+ code: ToolErrorCodes.TOOL_FETCH_ERROR,
62
+ possibleFixes: options.possibleFixes || [
63
+ 'Ensure the tool slug is valid',
64
+ 'Ensure you are using the correct API key',
65
+ 'Ensure you are using the correct API endpoint / Base URL and it is working',
66
+ ],
67
+ });
68
+ this.name = 'ComposioToolFetchError';
69
+ }
70
+ }
71
+
48
72
  export class ComposioInvalidModifierError extends ComposioError {
49
73
  constructor(
50
74
  message: string = 'Invalid modifier',
package/src/index.ts CHANGED
@@ -33,6 +33,10 @@ export {
33
33
  isBlockedSensitiveFileUploadPath,
34
34
  BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS,
35
35
  } from './utils/sensitiveFileUploadPaths';
36
+ // Bounded response reader for files fetched from user-supplied URLs. Exported
37
+ // for the same reason as the denylist guard above: downstream packages read
38
+ // remote files too, and every such read must enforce the same size cap.
39
+ export { readResponseBodyWithLimit, MAX_URL_UPLOAD_SIZE_BYTES } from './utils/readResponseBody';
36
40
  export {
37
41
  sanitizeSchemaPropertyKeys,
38
42
  restoreOriginalKeys,
@@ -514,7 +514,11 @@ export function buildCustomToolsMapFromResponse(
514
514
  }
515
515
  }
516
516
 
517
- const findHandle = (originalSlug: string, toolkit?: string): HandleMatch | undefined => {
517
+ const findHandle = (
518
+ finalSlug: string,
519
+ originalSlug: string,
520
+ toolkit?: string
521
+ ): HandleMatch | undefined => {
518
522
  const originalSlugKey = originalSlug.toUpperCase();
519
523
  const qualifiedMatch = handlesByQualifiedOriginalSlug.get(
520
524
  qualifiedOriginalSlugKey(toolkit, originalSlugKey)
@@ -522,13 +526,26 @@ export function buildCustomToolsMapFromResponse(
522
526
  if (qualifiedMatch) return qualifiedMatch;
523
527
 
524
528
  const bareMatches = handlesByOriginalSlug.get(originalSlugKey) ?? [];
525
- return bareMatches.length === 1 ? bareMatches[0] : undefined;
529
+ // Response tool not defined locally; nothing to route in-process.
530
+ if (bareMatches.length === 0) return undefined;
531
+ // A bare match may only stand in when the response carries no toolkit identity.
532
+ // Binding a toolkit child to another toolkit's handler would silently execute
533
+ // the wrong implementation.
534
+ if (toolkit === undefined && bareMatches.length === 1) return bareMatches[0];
535
+
536
+ const registered = [
537
+ ...new Set(bareMatches.map(m => (m.toolkit ?? 'custom').toUpperCase())),
538
+ ].sort();
539
+ throw new ValidationError(
540
+ `Cannot map custom tool "${finalSlug}": original slug "${originalSlug}" for toolkit ` +
541
+ `"${toolkit ?? 'custom'}" has no exact local match. Registered for toolkits: ${registered.join(', ')}.`
542
+ );
526
543
  };
527
544
 
528
545
  const addEntry = (finalSlug: string, originalSlug: string, toolkit?: string | null) => {
529
546
  const resolvedToolkit = toolkit ?? undefined;
530
- const match = findHandle(originalSlug, resolvedToolkit);
531
- if (!match) return; // Response tool not found in our handles (shouldn't happen)
547
+ const match = findHandle(finalSlug, originalSlug, resolvedToolkit);
548
+ if (!match) return;
532
549
 
533
550
  const finalSlugKey = finalSlug.toUpperCase();
534
551
  if (byFinalSlug.has(finalSlugKey)) {
@@ -537,13 +554,21 @@ export function buildCustomToolsMapFromResponse(
537
554
  );
538
555
  }
539
556
 
557
+ const entryToolkit = resolvedToolkit ?? match.toolkit;
558
+ const qualifiedKey = qualifiedOriginalSlugKey(entryToolkit, originalSlug);
559
+ if (byToolkitAndOriginalSlug.has(qualifiedKey)) {
560
+ throw new ValidationError(
561
+ `Custom tool slug collision: original slug "${match.handle.slug}" is already registered for toolkit "${entryToolkit ?? 'custom'}".`
562
+ );
563
+ }
564
+
540
565
  const entry: CustomToolsMapEntry = {
541
566
  handle: match.handle,
542
567
  finalSlug,
543
- toolkit: resolvedToolkit ?? match.toolkit,
568
+ toolkit: entryToolkit,
544
569
  };
545
570
  byFinalSlug.set(finalSlugKey, entry);
546
- byToolkitAndOriginalSlug.set(qualifiedOriginalSlugKey(entry.toolkit, originalSlug), entry);
571
+ byToolkitAndOriginalSlug.set(qualifiedKey, entry);
547
572
  addOriginalSlugAlias({ byOriginalSlug, ambiguousOriginalSlugs, originalSlug, entry });
548
573
  };
549
574
 
@@ -563,6 +588,16 @@ export function buildCustomToolsMapFromResponse(
563
588
  }
564
589
  }
565
590
 
591
+ // Ambiguity follows the local definitions, not whichever subset the response
592
+ // happened to include: a shared child slug must never become callable by its
593
+ // bare name just because a sibling was omitted.
594
+ for (const [originalSlugKey, matches] of handlesByOriginalSlug) {
595
+ if (matches.length > 1) {
596
+ byOriginalSlug.delete(originalSlugKey);
597
+ ambiguousOriginalSlugs.add(originalSlugKey);
598
+ }
599
+ }
600
+
566
601
  return {
567
602
  byFinalSlug,
568
603
  byOriginalSlug,
package/src/models/MCP.ts CHANGED
@@ -99,16 +99,19 @@ export class MCP {
99
99
 
100
100
  const toolkits: string[] = [];
101
101
  const auth_config_ids: string[] = [];
102
- const custom_tools: string[] = config.data.allowedTools ?? [];
102
+ const allowed_tools: string[] = config.data.allowedTools ?? [];
103
103
 
104
104
  // extract all the toolkits, authconfigs, and allowed tools to separate slugs
105
105
  config.data.toolkits.forEach(toolkit => {
106
106
  if (typeof toolkit === 'string') {
107
107
  toolkits.push(toolkit);
108
- } else if (toolkit.toolkit) {
109
- toolkits.push(toolkit.toolkit);
110
- } else if (toolkit.authConfigId) {
111
- auth_config_ids.push(toolkit.authConfigId);
108
+ } else {
109
+ if (toolkit.toolkit) {
110
+ toolkits.push(toolkit.toolkit);
111
+ }
112
+ if (toolkit.authConfigId) {
113
+ auth_config_ids.push(toolkit.authConfigId);
114
+ }
112
115
  }
113
116
  });
114
117
 
@@ -116,7 +119,7 @@ export class MCP {
116
119
  name,
117
120
  toolkits,
118
121
  auth_config_ids,
119
- custom_tools,
122
+ allowed_tools,
120
123
  // if manually manage account is set to true, disable composio account management tools
121
124
  managed_auth_via_composio: config.data.manuallyManageConnections ? false : true,
122
125
  };
@@ -380,28 +383,39 @@ export class MCP {
380
383
 
381
384
  const toolkits: string[] = [];
382
385
  const auth_config_ids: string[] = [];
383
- const custom_tools: string[] | undefined = params.allowedTools ?? undefined;
384
386
 
385
387
  // extract all the toolkits, authconfigs, and allowed tools to separate slugs
386
388
  params.toolkits?.forEach(toolkit => {
387
389
  if (typeof toolkit === 'string') {
388
390
  toolkits.push(toolkit);
389
- } else if (toolkit.toolkit) {
390
- toolkits.push(toolkit.toolkit);
391
- } else if (toolkit.authConfigId) {
392
- auth_config_ids.push(toolkit.authConfigId);
391
+ } else {
392
+ if (toolkit.toolkit) {
393
+ toolkits.push(toolkit.toolkit);
394
+ }
395
+ if (toolkit.authConfigId) {
396
+ auth_config_ids.push(toolkit.authConfigId);
397
+ }
393
398
  }
394
399
  });
400
+
401
+ // Build a sparse PATCH body: only fields the caller provided are sent, so omitted
402
+ // fields keep their current server-side values. `allowed_tools` is sent whenever it
403
+ // is provided, independently of `toolkits` (tool-only updates are valid), and must
404
+ // use the API field `allowed_tools` — the update endpoint does not read the
405
+ // deprecated create-only alias `custom_tools`. `manuallyManageConnections` is
406
+ // inverted into `managed_auth_via_composio`, matching create() and generate().
395
407
  const updateBody = {
396
- ...{ name: params.name ?? undefined },
397
- ...(params.toolkits
408
+ ...(params.name !== undefined ? { name: params.name } : {}),
409
+ ...(params.toolkits !== undefined
398
410
  ? {
399
- custom_tools: custom_tools,
400
411
  toolkits: toolkits,
401
412
  auth_config_ids: auth_config_ids,
402
413
  }
403
414
  : {}),
404
- ...{ managed_auth_via_composio: params.manuallyManageConnections ?? undefined },
415
+ ...(params.allowedTools !== undefined ? { allowed_tools: params.allowedTools } : {}),
416
+ ...(params.manuallyManageConnections !== undefined
417
+ ? { managed_auth_via_composio: !params.manuallyManageConnections }
418
+ : {}),
405
419
  };
406
420
  const response = await withCancellation(
407
421
  () => this.client.mcp.update(serverId, updateBody, requestOptions),
@@ -8,7 +8,12 @@ function getParentDir(filePath: string): string {
8
8
  return filePath.slice(0, lastSep);
9
9
  }
10
10
  import { RemoteFileData, RemoteFileDataSchema } from '../types/ToolRouterSessionFilesMount.types';
11
- import { RemoteFileDownloadError, ValidationError } from '../errors';
11
+ import {
12
+ ComposioBlockedInternalUrlError,
13
+ RemoteFileDownloadError,
14
+ ValidationError,
15
+ } from '../errors';
16
+ import { readResponseBodyWithLimit } from '../utils/readResponseBody';
12
17
 
13
18
  /**
14
19
  * Represents a file stored in a tool router session's file mount.
@@ -77,31 +82,58 @@ export class RemoteFile {
77
82
  return platform.basename(this.mountRelativePath);
78
83
  }
79
84
 
85
+ private downloadError(message: string, cause: unknown, response?: Response) {
86
+ return new RemoteFileDownloadError(message, {
87
+ statusCode: response?.status,
88
+ statusText: response?.statusText,
89
+ downloadUrl: this.downloadUrl,
90
+ mountRelativePath: this.mountRelativePath,
91
+ filename: this.filename,
92
+ cause,
93
+ });
94
+ }
95
+
96
+ private async downloadBytes(): Promise<{ content: Uint8Array; contentType: string }> {
97
+ let response: Response;
98
+ try {
99
+ response = await ssrfSafeFetchWhereSupported(this.downloadUrl);
100
+ } catch (error) {
101
+ if (error instanceof ComposioBlockedInternalUrlError) {
102
+ throw error;
103
+ }
104
+ throw this.downloadError('Failed to download file', error);
105
+ }
106
+
107
+ if (!response.ok) {
108
+ await response.body?.cancel().catch(() => undefined);
109
+ throw this.downloadError(
110
+ `Failed to download file: ${response.status} ${response.statusText}`,
111
+ new Error(`HTTP ${response.status}: ${response.statusText}`),
112
+ response
113
+ );
114
+ }
115
+
116
+ try {
117
+ const content = response.body
118
+ ? await readResponseBodyWithLimit(response)
119
+ : new Uint8Array(await response.arrayBuffer());
120
+ return {
121
+ content,
122
+ contentType: response.headers?.get?.('content-type') ?? '',
123
+ };
124
+ } catch (error) {
125
+ await response.body?.cancel().catch(() => undefined);
126
+ throw this.downloadError('Failed to read downloaded file', error, response);
127
+ }
128
+ }
129
+
80
130
  /**
81
131
  * Fetches the file content as a buffer.
82
132
  * @returns The file content as a Uint8Array
83
133
  * @throws RemoteFileDownloadError if the fetch fails
84
134
  */
85
135
  async buffer(): Promise<Uint8Array> {
86
- // SSRF guard: `downloadUrl` is set from an API response, so it is untrusted
87
- // input like every other response field, and its bytes are handed straight
88
- // back to the caller. See ssrfGuard.node.ts.
89
- const response = await ssrfSafeFetchWhereSupported(this.downloadUrl);
90
- if (!response.ok) {
91
- throw new RemoteFileDownloadError(
92
- `Failed to download file: ${response.status} ${response.statusText}`,
93
- {
94
- statusCode: response.status,
95
- statusText: response.statusText,
96
- downloadUrl: this.downloadUrl,
97
- mountRelativePath: this.mountRelativePath,
98
- filename: this.filename,
99
- cause: new Error(`HTTP ${response.status}: ${response.statusText}`),
100
- }
101
- );
102
- }
103
- const arrayBuffer = await response.arrayBuffer();
104
- return new Uint8Array(arrayBuffer);
136
+ return (await this.downloadBytes()).content;
105
137
  }
106
138
 
107
139
  /**
@@ -120,22 +152,8 @@ export class RemoteFile {
120
152
  * @throws RemoteFileDownloadError if the fetch fails
121
153
  */
122
154
  async blob(): Promise<Blob> {
123
- // SSRF guard: see `buffer()`.
124
- const response = await ssrfSafeFetchWhereSupported(this.downloadUrl);
125
- if (!response.ok) {
126
- throw new RemoteFileDownloadError(
127
- `Failed to download file: ${response.status} ${response.statusText}`,
128
- {
129
- statusCode: response.status,
130
- statusText: response.statusText,
131
- downloadUrl: this.downloadUrl,
132
- mountRelativePath: this.mountRelativePath,
133
- filename: this.filename,
134
- cause: new Error(`HTTP ${response.status}: ${response.statusText}`),
135
- }
136
- );
137
- }
138
- return response.blob();
155
+ const { content, contentType } = await this.downloadBytes();
156
+ return new Blob([content as BlobPart], { type: contentType });
139
157
  }
140
158
 
141
159
  /**
@@ -71,6 +71,7 @@ function getSessionMetadata(
71
71
  session: SessionCreateResponse | SessionRetrieveResponse | SessionAttachResponse
72
72
  ) {
73
73
  const metadata: ToolRouterSessionMetadata = {
74
+ config: session.config,
74
75
  preload: session.config.preload,
75
76
  workbench: session.config.workbench,
76
77
  configVersion: session.config_version,
@@ -16,12 +16,16 @@ import {
16
16
  ToolRouterSessionExecuteResponseSchema,
17
17
  ToolRouterSessionProxyExecuteResponse,
18
18
  ToolRouterSessionExecuteOptions,
19
+ ToolRouterSessionConfig,
19
20
  ToolRouterSessionMetadata,
20
21
  ToolRouterSessionPreloadConfig,
21
22
  ToolRouterSessionWorkbenchConfig,
22
23
  ToolRouterSessionWarning,
23
24
  ToolRouterUpdateSessionConfig,
24
25
  ToolRouterUpdateSessionConfigSchema,
26
+ ToolRouterSessionEnsureConnectedOptions,
27
+ ToolRouterSessionEnsureConnectedOptionsSchema,
28
+ ToolRouterSessionEnsureConnectedResult,
25
29
  type ToolRouterSessionDeleteResponse,
26
30
  } from '../types/toolRouter.types';
27
31
  import {
@@ -118,6 +122,12 @@ export class ToolRouterSession<
118
122
  /** Hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`). Exists on every session at runtime, but only surfaced in the type when the session is created with `{ mcp: true }` (which returns `Session`); the default `SessionWithoutMcp` omits `mcp`, so MCP is an explicit opt-in. See https://docs.composio.dev/docs/sessions-via-mcp */
119
123
  public readonly mcp: ToolRouterMCPServerConfig;
120
124
  public readonly experimental: SessionExperimental;
125
+ /**
126
+ * Server-side session configuration (toolkit/tool allowlists, tags, preload,
127
+ * sandbox, manage_connections) as returned by the API. Refreshed in place by
128
+ * `update()`.
129
+ */
130
+ public config: ToolRouterSessionConfig;
121
131
  public preload: ToolRouterSessionPreloadConfig;
122
132
  /** Resolved sandbox (code-execution) config returned by the API. `enable` defaults to `true` server-side. */
123
133
  public sandbox?: ToolRouterSessionWorkbenchConfig;
@@ -131,7 +141,7 @@ export class ToolRouterSession<
131
141
 
132
142
  constructor(
133
143
  private readonly client: ComposioClient,
134
- private readonly config: ComposioConfig<TProvider> | undefined,
144
+ private readonly sdkConfig: ComposioConfig<TProvider> | undefined,
135
145
  sessionId: string,
136
146
  mcp: ToolRouterMCPServerConfig,
137
147
  experimentalOverrides?: Pick<SessionExperimental, 'assistivePrompt'>,
@@ -139,6 +149,12 @@ export class ToolRouterSession<
139
149
  private readonly userId?: string,
140
150
  metadata?: ToolRouterSessionMetadata
141
151
  ) {
152
+ const config: ToolRouterSessionConfig = metadata?.config ?? {
153
+ user_id: userId ?? '',
154
+ execute: {},
155
+ search: {},
156
+ preload: { tools: [] },
157
+ };
142
158
  if (customToolsMap && !userId) {
143
159
  throw new Error('userId is required when custom tools are bound to a session.');
144
160
  }
@@ -148,8 +164,9 @@ export class ToolRouterSession<
148
164
  assistivePrompt: experimentalOverrides?.assistivePrompt,
149
165
  files: new ToolRouterSessionFilesMount(client, sessionId),
150
166
  };
151
- this.preload = metadata?.preload ?? { tools: [] };
152
- this.sandbox = metadata?.workbench;
167
+ this.config = config;
168
+ this.preload = metadata?.preload ?? config.preload;
169
+ this.sandbox = metadata?.workbench ?? config.workbench;
153
170
  this.configVersion = metadata?.configVersion;
154
171
  this.warnings = metadata?.warnings ?? [];
155
172
  this.preloadedCustomToolSlugs = metadata?.preloadedCustomToolSlugs ?? [];
@@ -193,7 +210,7 @@ export class ToolRouterSession<
193
210
  modifiers?: SessionMetaToolOptions,
194
211
  requestOptions?: ComposioRequestOptions
195
212
  ): Promise<ReturnType<TProvider['wrapTools']>> {
196
- const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
213
+ const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.sdkConfig);
197
214
  const rawTools = await ToolsModel.getRawToolRouterSessionTools(
198
215
  this.sessionId,
199
216
  undefined,
@@ -226,13 +243,13 @@ export class ToolRouterSession<
226
243
  );
227
244
  };
228
245
 
229
- if (!this.config?.provider) {
246
+ if (!this.sdkConfig?.provider) {
230
247
  throw new Error(
231
248
  'A provider is required when using custom tools with session.tools(). ' +
232
249
  'Pass a provider in the Composio constructor.'
233
250
  );
234
251
  }
235
- return this.config.provider.wrapTools(sessionTools, routingExecuteFn) as ReturnType<
252
+ return this.sdkConfig.provider.wrapTools(sessionTools, routingExecuteFn) as ReturnType<
236
253
  TProvider['wrapTools']
237
254
  >;
238
255
  }
@@ -375,9 +392,13 @@ export class ToolRouterSession<
375
392
  tools: tk.tools.map(tool => {
376
393
  // Look up by toolkit + original slug so toolkits can safely reuse common names
377
394
  // like VERSION, CLICK, or SEARCH without losing the backend-assigned final slug.
395
+ // Only trust a bare alias that belongs to this toolkit.
396
+ const bare = this.customToolsMap!.byOriginalSlug.get(tool.slug.toUpperCase());
378
397
  const entry =
379
398
  findCustomToolMapEntryByToolkitAndOriginalSlug(this.customToolsMap, tk.slug, tool.slug) ??
380
- this.customToolsMap!.byOriginalSlug.get(tool.slug.toUpperCase());
399
+ (bare?.toolkit && bare.toolkit.toLowerCase() === tk.slug.toLowerCase()
400
+ ? bare
401
+ : undefined);
381
402
  return {
382
403
  slug: entry?.finalSlug ?? tool.slug,
383
404
  name: tool.name,
@@ -466,6 +487,83 @@ export class ToolRouterSession<
466
487
  );
467
488
  }
468
489
 
490
+ /**
491
+ * Ensure a toolkit has an active connection in this session, reconciling
492
+ * `authorize()`/`session.link` with the session's active connection state.
493
+ *
494
+ * If the session already resolves an ACTIVE connection (or the toolkit is
495
+ * no-auth), this returns immediately without creating a link — unlike
496
+ * `authorize()`, which always starts a new link flow, even when one is
497
+ * already connected. Otherwise it starts the authorization flow and waits
498
+ * for the new connection to become ACTIVE.
499
+ *
500
+ * For interactive flows that should surface the redirect URL instead of
501
+ * blocking, use `authorize()` and its `waitForConnection()` directly.
502
+ *
503
+ * @param toolkit - The toolkit slug to ensure a connection for (e.g. 'github')
504
+ * @param options - Optional authorization options plus `timeout` (ms to wait
505
+ * for a newly-initiated connection, default 60000)
506
+ * @returns The toolkit's canonical slug, whether it was already connected,
507
+ * and the active connected account (omitted for no-auth toolkits)
508
+ * @throws {ValidationError} If the options fail validation
509
+ * @throws {ConnectionRequestTimeoutError} If a newly-initiated connection does
510
+ * not become active within `timeout`
511
+ * @throws {ConnectionRequestFailedError} If the new connection enters a failed,
512
+ * expired, or revoked state
513
+ *
514
+ * @example
515
+ * ```typescript
516
+ * const session = await composio.sessions.create({ toolkits: ['github'] });
517
+ * const { wasConnected, connectedAccount } = await session.ensureConnected('github');
518
+ * if (!wasConnected) console.log('Newly linked:', connectedAccount?.id);
519
+ * ```
520
+ */
521
+ async ensureConnected(
522
+ toolkit: string,
523
+ options?: ToolRouterSessionEnsureConnectedOptions,
524
+ requestOptions?: ComposioRequestOptions
525
+ ): Promise<ToolRouterSessionEnsureConnectedResult> {
526
+ const parsedOptions = ToolRouterSessionEnsureConnectedOptionsSchema.safeParse(options ?? {});
527
+ if (!parsedOptions.success) {
528
+ throw new ValidationError('Failed to parse tool router ensureConnected options', {
529
+ cause: parsedOptions.error,
530
+ });
531
+ }
532
+ const { callbackUrl, alias, experimental, timeout } = parsedOptions.data;
533
+
534
+ const state = await this.toolkits({ toolkits: [toolkit] }, requestOptions);
535
+ const existing = state.items.find(item => item.slug.toLowerCase() === toolkit.toLowerCase());
536
+
537
+ if (existing?.isNoAuth) {
538
+ return { toolkit: existing.slug, wasConnected: true };
539
+ }
540
+ const activeAccount = existing?.connection?.connectedAccount;
541
+ if (existing?.connection?.isActive && activeAccount) {
542
+ return {
543
+ toolkit: existing.slug,
544
+ wasConnected: true,
545
+ connectedAccount: { id: activeAccount.id, status: activeAccount.status },
546
+ };
547
+ }
548
+
549
+ const request = await this.authorize(
550
+ toolkit,
551
+ {
552
+ ...(callbackUrl !== undefined && { callbackUrl }),
553
+ ...(alias !== undefined && { alias }),
554
+ ...(experimental !== undefined && { experimental }),
555
+ },
556
+ requestOptions
557
+ );
558
+ const account = await request.waitForConnection(timeout);
559
+
560
+ return {
561
+ toolkit: existing?.slug ?? toolkit,
562
+ wasConnected: false,
563
+ connectedAccount: { id: account.id, status: account.status },
564
+ };
565
+ }
566
+
469
567
  /**
470
568
  * Query the connection state of toolkits in the session.
471
569
  * Supports pagination and filtering by toolkit slugs.
@@ -555,14 +653,15 @@ export class ToolRouterSession<
555
653
  /**
556
654
  * Execute a tool within the session.
557
655
  *
558
- * For custom tools, accepts the original slug (e.g. "GREP") or the
559
- * full slug (e.g. "LOCAL_GREP"). Custom tools are executed in-process;
560
- * remote tools are sent to the Composio backend.
656
+ * For custom tools, accepts the full slug (e.g. "LOCAL_GREP") or the
657
+ * original slug (e.g. "GREP") when that original slug is unique across
658
+ * the session's custom tools and toolkits. Custom tools are executed
659
+ * in-process; remote tools are sent to the Composio backend.
561
660
  *
562
661
  * @param toolSlug - The tool slug to execute
563
662
  * @param arguments_ - Optional tool arguments
564
663
  * @param options - Optional execution options
565
- * @param options.account - Account identifier for direct app tool execution in multi-account sessions. Helper/meta tools either ignore this top-level field or define their own account-selection fields.
664
+ * @param options.account - Account identifier for direct app tool execution. Accepted on every project: in multi-account sessions it picks the account; on single-account projects it must match one of the session's active connections for the toolkit. Helper/meta tools either ignore this top-level field or define their own account-selection fields.
566
665
  * @returns The tool execution result
567
666
  */
568
667
  async execute(
@@ -659,12 +758,13 @@ export class ToolRouterSession<
659
758
  /**
660
759
  * Partially update the session configuration.
661
760
  * Only the fields provided will be changed; omitted fields are preserved.
662
- * Mutates this session's `configVersion`, `preload`, and `warnings` in-place.
761
+ * Mutates this session's `config`, `configVersion`, `preload`, `sandbox`,
762
+ * and `warnings` in-place, and resolves to the updated session `config`.
663
763
  */
664
764
  async update(
665
765
  config: ToolRouterUpdateSessionConfig,
666
766
  requestOptions?: ComposioRequestOptions
667
- ): Promise<void> {
767
+ ): Promise<ToolRouterSessionConfig> {
668
768
  const parsed = ToolRouterUpdateSessionConfigSchema.parse(config);
669
769
  const params = transformToolRouterUpdateParams(parsed);
670
770
  const response = await withCancellation(
@@ -672,9 +772,11 @@ export class ToolRouterSession<
672
772
  requestOptions?.signal
673
773
  );
674
774
  this.configVersion = response.config_version;
775
+ this.config = response.config;
675
776
  this.preload = response.config.preload;
676
777
  this.sandbox = response.config.workbench;
677
778
  this.warnings = response.warnings ?? [];
779
+ return this.config;
678
780
  }
679
781
 
680
782
  /**
@@ -1,4 +1,4 @@
1
- import ComposioClient from '@composio/client';
1
+ import ComposioClient, { APIError } from '@composio/client';
2
2
  import {
3
3
  ToolkitListParams,
4
4
  ToolKitListResponse,
@@ -16,7 +16,6 @@ import { ConnectionRequest } from '../types/connectionRequest.types';
16
16
  import { telemetry } from '../telemetry/Telemetry';
17
17
  import { AuthSchemeType } from '../types/authConfigs.types';
18
18
  import logger from '../utils/logger';
19
- import { APIError } from 'openai';
20
19
  import {
21
20
  transformToolkitListResponse,
22
21
  transformToolkitRetrieveCategoriesResponse,