@composio/core 0.19.0 → 0.20.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 (87) hide show
  1. package/dist/{CustomTool-CB5vm1Jc.d.mts → CustomTool-B3m-188G.d.mts} +1 -1
  2. package/dist/{CustomTool-BMlZfJVz.mjs → CustomTool-fYEFjSLM.mjs} +1 -1
  3. package/dist/{FileModifierErrors-BqFmpRsm.mjs → FileModifierErrors-CdGSABoq.mjs} +1 -1
  4. package/dist/{SsrfErrors-C91YhASE.mjs → SsrfErrors-DiQldIdC.mjs} +18 -7
  5. package/dist/{Telemetry-HlftxMx6.mjs → Telemetry-JRJJYS4I.mjs} +2 -2
  6. package/dist/{cancellation-CXpfmiVo.mjs → cancellation-Dwa9lGHA.mjs} +2 -2
  7. package/dist/{composio-DLGaeN70.d.mts → composio-B36OXii1.d.mts} +2691 -119
  8. package/dist/{customTool.types-BAmEh3MB.d.mts → customTool.types-C436M_D0.d.mts} +431 -98
  9. package/dist/docs/reference/sdk-reference/typescript/auth-configs.mdx +10 -10
  10. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +5 -2
  11. package/dist/docs/reference/sdk-reference/typescript/connected-accounts.mdx +101 -18
  12. package/dist/docs/reference/sdk-reference/typescript/custom-toolkits.mdx +123 -0
  13. package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +9 -2
  14. package/dist/docs/reference/sdk-reference/typescript/index.mdx +7 -0
  15. package/dist/docs/reference/sdk-reference/typescript/keyring.mdx +56 -0
  16. package/dist/docs/reference/sdk-reference/typescript/logs.mdx +78 -0
  17. package/dist/docs/reference/sdk-reference/typescript/mcp.mdx +15 -15
  18. package/dist/docs/reference/sdk-reference/typescript/meta.json +8 -1
  19. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +10 -10
  20. package/dist/docs/reference/sdk-reference/typescript/session.mdx +77 -27
  21. package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +24 -10
  22. package/dist/docs/reference/sdk-reference/typescript/toolkits.mdx +149 -12
  23. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +18 -18
  24. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +25 -25
  25. package/dist/docs/reference/sdk-reference/typescript/usage.mdx +78 -0
  26. package/dist/docs/reference/sdk-reference/typescript/webhook-endpoints.mdx +162 -0
  27. package/dist/docs/reference/sdk-reference/typescript/webhook-subscriptions.mdx +218 -0
  28. package/dist/docs/reference/sdk-reference/typescript/webhooks.mdx +20 -0
  29. package/dist/{errors-BuEKehbI.mjs → errors-D_A4b2c2.mjs} +123 -4
  30. package/dist/experimental/index.d.mts +2 -2
  31. package/dist/experimental/index.mjs +1 -1
  32. package/dist/{fileUtils.node-L7XD8UPr.mjs → fileUtils.node-DNLhLg0W.mjs} +4 -4
  33. package/dist/index.d.mts +264 -51
  34. package/dist/index.mjs +2338 -168
  35. package/dist/models/Files.node.mjs +2 -2
  36. package/dist/{sensitiveFileUploadPaths-B6pBt9lO.mjs → sensitiveFileUploadPaths-BlLp-Yo2.mjs} +1 -1
  37. package/dist/{ssrfGuard.node-B9xQB4za.mjs → ssrfGuard.node-BZ270bcu.mjs} +1 -1
  38. package/dist/{types-CxLPO0Xq.d.mts → types-Br3GBya5.d.mts} +2 -2
  39. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  40. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  41. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  42. package/dist/utils/modifiers/FileToolModifier.node.mjs +5 -5
  43. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  44. package/dist/utils/ssrfGuard.node.mjs +1 -1
  45. package/dist/utils/ssrfGuard.workerd.mjs +1 -1
  46. package/package.json +2 -2
  47. package/src/composio.ts +207 -10
  48. package/src/errors/ConnectedAccountsErrors.ts +47 -0
  49. package/src/errors/SDKErrors.ts +52 -0
  50. package/src/errors/ToolRouterErrors.ts +57 -0
  51. package/src/errors/index.ts +3 -0
  52. package/src/index.ts +11 -0
  53. package/src/lib/toolRouterMcp.ts +132 -0
  54. package/src/lib/toolRouterParams.ts +116 -29
  55. package/src/models/ConnectedAccounts.ts +118 -2
  56. package/src/models/CustomToolkits.ts +169 -0
  57. package/src/models/Experimental.ts +27 -0
  58. package/src/models/Keyring.ts +65 -0
  59. package/src/models/Logs.ts +101 -0
  60. package/src/models/ToolRouter.ts +42 -14
  61. package/src/models/ToolRouterSession.ts +120 -9
  62. package/src/models/Toolkits.ts +180 -0
  63. package/src/models/Tools.ts +3 -1
  64. package/src/models/Triggers.ts +3 -88
  65. package/src/models/Usage.ts +119 -0
  66. package/src/models/Webhooks.ts +520 -0
  67. package/src/services/pusher/Pusher.ts +17 -6
  68. package/src/types/authConfigs.types.ts +2 -0
  69. package/src/types/connectedAccounts.types.ts +54 -0
  70. package/src/types/customToolkits.types.ts +102 -0
  71. package/src/types/keyring.types.ts +32 -0
  72. package/src/types/logs.types.ts +108 -0
  73. package/src/types/toolRouter.types.ts +205 -11
  74. package/src/types/toolkit.types.ts +144 -0
  75. package/src/types/usage.types.ts +81 -0
  76. package/src/types/webhooks.types.ts +143 -0
  77. package/src/utils/constants.ts +1 -5
  78. package/src/utils/logger.ts +39 -7
  79. package/src/utils/sdk.ts +385 -22
  80. package/src/utils/transformers/connectedAccounts.ts +37 -2
  81. package/src/utils/transformers/customToolkits.ts +98 -0
  82. package/src/utils/transformers/keyring.ts +24 -0
  83. package/src/utils/transformers/logs.ts +85 -0
  84. package/src/utils/transformers/toolkits.ts +106 -3
  85. package/src/utils/transformers/triggers.ts +2 -2
  86. package/src/utils/transformers/usage.ts +77 -0
  87. package/src/utils/transformers/webhooks.ts +139 -0
@@ -0,0 +1,132 @@
1
+ import { ComposioMCPDestinationError } from '../errors/ToolRouterErrors';
2
+ import type { ComposioRequestHeaders } from '../types/composio.types';
3
+ import type { MCPServerType, ToolRouterMCPServerConfig } from '../types/toolRouter.types';
4
+ import logger from '../utils/logger';
5
+ import { ORG_ID_HEADER, PROJECT_ID_HEADER, resolveCredentialHeaders } from '../utils/sdk';
6
+
7
+ type OriginRole = 'API base URL' | 'MCP URL';
8
+
9
+ type ParsedOrigin = { origin: string } | { error: ComposioMCPDestinationError };
10
+
11
+ /**
12
+ * Returns the tuple origin (`scheme://host[:port]`) of an absolute URL.
13
+ *
14
+ * URLs without a tuple origin (`data:`, `file:`, `blob:` without a base, and
15
+ * similar) serialize their origin as the opaque string `null`. Two such URLs
16
+ * would compare equal, so they are rejected before any comparison happens.
17
+ */
18
+ const parseOrigin = (url: string, role: OriginRole): ParsedOrigin => {
19
+ let parsed: URL;
20
+ try {
21
+ parsed = new URL(url);
22
+ } catch (_error) {
23
+ return {
24
+ error: new ComposioMCPDestinationError(`The ${role} is not a valid absolute URL`, {
25
+ meta: { role },
26
+ }),
27
+ };
28
+ }
29
+ if (parsed.origin === 'null') {
30
+ return {
31
+ error: new ComposioMCPDestinationError(`The ${role} has an opaque origin`, {
32
+ meta: { role },
33
+ }),
34
+ };
35
+ }
36
+ return { origin: parsed.origin };
37
+ };
38
+
39
+ /**
40
+ * Returns the error describing why the MCP URL must not receive the session
41
+ * credential, or `undefined` when it shares the API origin.
42
+ */
43
+ const destinationRejection = (
44
+ apiBaseURL: string,
45
+ mcpUrl: string
46
+ ): ComposioMCPDestinationError | undefined => {
47
+ const api = parseOrigin(apiBaseURL, 'API base URL');
48
+ if ('error' in api) {
49
+ return api.error;
50
+ }
51
+ const mcp = parseOrigin(mcpUrl, 'MCP URL');
52
+ if ('error' in mcp) {
53
+ return mcp.error;
54
+ }
55
+ if (mcp.origin === api.origin) {
56
+ return undefined;
57
+ }
58
+ return new ComposioMCPDestinationError(
59
+ `The session MCP endpoint origin ${mcp.origin} does not match the API origin ${api.origin}; the session credential was not attached`,
60
+ { meta: { mcpOrigin: mcp.origin, apiOrigin: api.origin } }
61
+ );
62
+ };
63
+
64
+ export type MCPServerConfigInput = {
65
+ type: MCPServerType;
66
+ /** The MCP URL returned by the API for this session. */
67
+ url: string;
68
+ /** The API base URL the session request was sent to. */
69
+ apiBaseURL: string;
70
+ /** The project API key the session request authenticated with, or `null` when disabled. */
71
+ apiKey: string | null | undefined;
72
+ /** The user API key the client resolved (`userApiKey` option or `COMPOSIO_USER_API_KEY`). */
73
+ userApiKey: string | null | undefined;
74
+ /** The default headers configured on the SDK instance; only `x-user-api-key` is consulted. */
75
+ defaultHeaders: ComposioRequestHeaders | undefined;
76
+ /** Organization nano ID the instance is scoped to, if any. */
77
+ orgId: string | undefined;
78
+ /** Project nano ID the instance is scoped to, if any. */
79
+ projectId: string | undefined;
80
+ /**
81
+ * Whether the caller asked for the MCP endpoint (`mcp: true`). Decides how
82
+ * a rejected destination is reported: as a thrown error when `true`, as a
83
+ * warning and an empty header set otherwise.
84
+ */
85
+ mcpRequested: boolean;
86
+ };
87
+
88
+ /**
89
+ * Builds the MCP server config exported on a session.
90
+ *
91
+ * The headers mirror the effective auth context of the session request: the
92
+ * project key as `x-api-key` when one is configured, otherwise the resolved
93
+ * user API key (the `userApiKey` option, then the `x-user-api-key` default
94
+ * header) as `x-user-api-key`, plus `x-org-id` / `x-project-id` when the
95
+ * instance carries an explicit scope. No other default header is copied and
96
+ * the environment is never re-read.
97
+ *
98
+ * The headers are only attached when the MCP URL has the same origin as the
99
+ * API base URL the session was created against, whatever scheme the caller
100
+ * configured: that origin already receives them on every SDK request. Any
101
+ * other destination (a different origin, an opaque origin, or a URL that does
102
+ * not parse) never receives the credential. When the caller asked for MCP
103
+ * (`mcpRequested`), that raises {@link ComposioMCPDestinationError} naming
104
+ * both origins; otherwise the session is returned with empty `headers` and a
105
+ * warning naming both origins is logged, so callers who only use the native
106
+ * tools are not blocked by an endpoint they never consume. The SDK itself
107
+ * never connects to the MCP URL and does not follow redirects for it; an MCP
108
+ * client consuming this config must not forward these headers to a different
109
+ * origin.
110
+ */
111
+ export const buildMCPServerConfig = (input: MCPServerConfigInput): ToolRouterMCPServerConfig => {
112
+ const rejection = destinationRejection(input.apiBaseURL, input.url);
113
+ if (rejection) {
114
+ if (input.mcpRequested) {
115
+ throw rejection;
116
+ }
117
+ logger.warn(
118
+ `${rejection.message}. session.mcp.headers was left empty; pass \`mcp: true\` to make this an error`
119
+ );
120
+ return { type: input.type, url: input.url, headers: {} };
121
+ }
122
+
123
+ const headers = resolveCredentialHeaders(input);
124
+ if (input.orgId) {
125
+ headers[ORG_ID_HEADER] = input.orgId;
126
+ }
127
+ if (input.projectId) {
128
+ headers[PROJECT_ID_HEADER] = input.projectId;
129
+ }
130
+
131
+ return { type: input.type, url: input.url, headers };
132
+ };
@@ -13,6 +13,9 @@ import {
13
13
  ToolRouterToolkitsDisabledConfigSchema,
14
14
  ToolRouterToolkitsEnabledConfigSchema,
15
15
  ToolRouterUpdateSessionConfig,
16
+ ToolRouterUpdateManageConnectionsConfig,
17
+ ToolRouterUpdateManageConnectionsSchema,
18
+ ToolRouterUpdateExperimentalConfig,
16
19
  ToolRouterSandboxConfig,
17
20
  } from '../types/toolRouter.types';
18
21
  import { ValidationError } from '../errors';
@@ -149,14 +152,58 @@ export const transformToolRouterWorkbenchParams = transformToolRouterSandboxPara
149
152
  * PATCH-safe variant of transformToolRouterManageConnectionsParams.
150
153
  * Does NOT apply defaults — only includes fields explicitly present in the input.
151
154
  */
155
+ /** Widens the listed keys of a generated request type so `null` can travel on the wire. */
156
+ type WithNull<T, K extends keyof T> = Omit<T, K> & { [P in K]?: NonNullable<T[P]> | null };
157
+
158
+ /**
159
+ * `manage_connections` as sent by `session.update()`. Only the supplied
160
+ * subfields travel; `callback_url: null` removes the stored callback, which
161
+ * the generated client types as string-only.
162
+ */
163
+ export type SessionPatchManageConnectionsBody = WithNull<
164
+ SessionPatchParams.ManageConnections,
165
+ 'callback_url'
166
+ >;
167
+
168
+ /** `multi_account` as sent by `session.update()`; `null` removes the stored maximum. */
169
+ export type SessionPatchMultiAccountBody = WithNull<
170
+ SessionPatchParams.MultiAccount,
171
+ 'max_accounts_per_toolkit'
172
+ >;
173
+
174
+ /** `experimental` as sent by `session.update()`; `null` removes a stored leaf. */
175
+ export type SessionPatchExperimentalBody = WithNull<
176
+ SessionPatchParams.Experimental,
177
+ 'permissions' | 'link_url_overwrite' | 'fast_mode' | 'submit_feedback'
178
+ >;
179
+
180
+ /**
181
+ * Request body of `session.update()`. Extends the generated `SessionPatchParams`
182
+ * with the nullable policy blocks (`null` removes the stored override) and the
183
+ * `expected_config_version` root precondition, none of which the generated
184
+ * client types yet.
185
+ */
186
+ export type SessionPatchBody = Omit<
187
+ WithNull<
188
+ SessionPatchParams,
189
+ 'toolkits' | 'tools' | 'tags' | 'auth_configs' | 'preload' | 'search' | 'execute'
190
+ >,
191
+ 'manage_connections' | 'multi_account' | 'experimental'
192
+ > & {
193
+ manage_connections?: SessionPatchManageConnectionsBody | null;
194
+ multi_account?: SessionPatchMultiAccountBody | null;
195
+ experimental?: SessionPatchExperimentalBody | null;
196
+ expected_config_version?: number;
197
+ };
198
+
152
199
  export const transformToolRouterUpdateManageConnectionsParams = (
153
- params: boolean | z.infer<typeof ToolRouterConfigManageConnectionsSchema>
154
- ): SessionPatchParams.ManageConnections => {
200
+ params: boolean | ToolRouterUpdateManageConnectionsConfig
201
+ ): SessionPatchManageConnectionsBody => {
155
202
  if (typeof params === 'boolean') {
156
203
  return { enable: params };
157
204
  }
158
205
 
159
- const parsedResult = ToolRouterConfigManageConnectionsSchema.safeParse(params);
206
+ const parsedResult = ToolRouterUpdateManageConnectionsSchema.safeParse(params);
160
207
  if (!parsedResult.success) {
161
208
  throw new ValidationError('Failed to parse manage connections config', {
162
209
  cause: parsedResult.error,
@@ -164,7 +211,7 @@ export const transformToolRouterUpdateManageConnectionsParams = (
164
211
  }
165
212
 
166
213
  const config = parsedResult.data;
167
- const result: Record<string, unknown> = {};
214
+ const result: SessionPatchManageConnectionsBody = {};
168
215
  if (config.enable !== undefined) {
169
216
  result.enable = config.enable;
170
217
  }
@@ -174,7 +221,32 @@ export const transformToolRouterUpdateManageConnectionsParams = (
174
221
  if (config.waitForConnections !== undefined) {
175
222
  result.enable_wait_for_connections = config.waitForConnections;
176
223
  }
177
- return result as SessionPatchParams.ManageConnections;
224
+ if (config.enableConnectionRemoval !== undefined) {
225
+ result.enable_connection_removal = config.enableConnectionRemoval;
226
+ }
227
+ return result;
228
+ };
229
+
230
+ const transformToolRouterUpdateExperimentalParams = (
231
+ config: ToolRouterUpdateExperimentalConfig
232
+ ): SessionPatchExperimentalBody => {
233
+ const result: SessionPatchExperimentalBody = {};
234
+ if (config.permissions !== undefined) {
235
+ result.permissions = config.permissions;
236
+ }
237
+ if (config.linkUrlOverwrite !== undefined) {
238
+ result.link_url_overwrite = config.linkUrlOverwrite;
239
+ }
240
+ if (config.fastMode !== undefined) {
241
+ result.fast_mode = config.fastMode;
242
+ }
243
+ if (config.submitFeedback !== undefined) {
244
+ result.submit_feedback = config.submitFeedback;
245
+ }
246
+ if (config.sessionConfigId !== undefined) {
247
+ result.session_config_id = config.sessionConfigId;
248
+ }
249
+ return result;
178
250
  };
179
251
 
180
252
  /**
@@ -244,63 +316,78 @@ export const transformToolRouterToolkitsParams = (
244
316
  return params as SessionCreateParams.Enable | SessionCreateParams.Disable;
245
317
  };
246
318
 
319
+ /**
320
+ * Request body of `session.update()`. Every key present in `config` is sent,
321
+ * including `null` (remove the stored override) and empty collections (an
322
+ * empty toolkit allowlist denies every app toolkit). The
323
+ * `expectedConfigVersion` option is not a body field here: the session
324
+ * resolves the precondition against its observed `configVersion`.
325
+ */
247
326
  export const transformToolRouterUpdateParams = (
248
327
  config: ToolRouterUpdateSessionConfig
249
- ): SessionPatchParams => {
250
- const params: SessionPatchParams = {};
328
+ ): SessionPatchBody => {
329
+ const params: SessionPatchBody = {};
251
330
 
252
331
  if (config.toolkits !== undefined) {
253
- params.toolkits = transformToolRouterToolkitsParams(config.toolkits);
332
+ params.toolkits =
333
+ config.toolkits === null ? null : transformToolRouterToolkitsParams(config.toolkits);
254
334
  }
255
335
  if (config.tools !== undefined) {
256
- params.tools = transformToolRouterToolsParams(config.tools);
336
+ params.tools = config.tools === null ? null : transformToolRouterToolsParams(config.tools);
257
337
  }
258
338
  if (config.tags !== undefined) {
259
- params.tags = transformToolRouterTagsParams(config.tags);
339
+ params.tags = config.tags === null ? null : transformToolRouterTagsParams(config.tags);
260
340
  }
261
341
  if (config.authConfigs !== undefined) {
262
342
  params.auth_configs = config.authConfigs;
263
343
  }
264
344
  if (config.connectedAccounts !== undefined) {
265
- const coerced: Record<string, string[]> = {};
266
- for (const [k, v] of Object.entries(config.connectedAccounts)) {
267
- coerced[k] = typeof v === 'string' ? [v] : v;
268
- }
269
- params.connected_accounts = coerced;
345
+ params.connected_accounts = config.connectedAccounts;
270
346
  }
271
347
  if (config.manageConnections !== undefined) {
272
- if (config.manageConnections === null) {
273
- params.manage_connections = null;
274
- } else {
275
- params.manage_connections = transformToolRouterUpdateManageConnectionsParams(
276
- config.manageConnections
277
- );
278
- }
348
+ params.manage_connections =
349
+ config.manageConnections === null
350
+ ? null
351
+ : transformToolRouterUpdateManageConnectionsParams(config.manageConnections);
279
352
  }
280
353
  const sandboxConfig = config.sandbox !== undefined ? config.sandbox : config.workbench;
281
354
  if (sandboxConfig !== undefined) {
282
- if (sandboxConfig === null) {
283
- params.workbench = null;
284
- } else {
285
- params.workbench = transformToolRouterUpdateSandboxParams(sandboxConfig);
286
- }
355
+ params.workbench =
356
+ sandboxConfig === null ? null : transformToolRouterUpdateSandboxParams(sandboxConfig);
287
357
  }
288
358
  if (config.multiAccount !== undefined) {
289
359
  if (config.multiAccount === null) {
290
360
  params.multi_account = null;
291
361
  } else {
292
- const ma: Record<string, unknown> = {};
362
+ const ma: SessionPatchMultiAccountBody = {};
293
363
  if (config.multiAccount.enable !== undefined) ma.enable = config.multiAccount.enable;
294
364
  if (config.multiAccount.maxAccountsPerToolkit !== undefined)
295
365
  ma.max_accounts_per_toolkit = config.multiAccount.maxAccountsPerToolkit;
296
366
  if (config.multiAccount.requireExplicitSelection !== undefined)
297
367
  ma.require_explicit_selection = config.multiAccount.requireExplicitSelection;
298
- params.multi_account = ma as SessionPatchParams.MultiAccount;
368
+ params.multi_account = ma;
299
369
  }
300
370
  }
301
371
  if (config.preload !== undefined) {
302
372
  params.preload = config.preload;
303
373
  }
374
+ if (config.search !== undefined) {
375
+ params.search = config.search;
376
+ }
377
+ if (config.execute !== undefined) {
378
+ params.execute =
379
+ config.execute === null
380
+ ? null
381
+ : config.execute.enableMultiExecute === undefined
382
+ ? {}
383
+ : { enable_multi_execute: config.execute.enableMultiExecute };
384
+ }
385
+ if (config.experimental !== undefined) {
386
+ params.experimental =
387
+ config.experimental === null
388
+ ? null
389
+ : transformToolRouterUpdateExperimentalParams(config.experimental);
390
+ }
304
391
 
305
392
  return params;
306
393
  };
@@ -5,7 +5,7 @@
5
5
  * @date 2025-05-05
6
6
  * @module ConnectedAccounts
7
7
  */
8
- import ComposioClient, { BadRequestError } from '@composio/client';
8
+ import ComposioClient, { BadRequestError, ConflictError } from '@composio/client';
9
9
  import {
10
10
  ConnectedAccountCreateResponse,
11
11
  ConnectedAccountDeleteResponse,
@@ -29,6 +29,10 @@ import {
29
29
  ConnectedAccountStatuses,
30
30
  ConnectedAccountRefreshOptions,
31
31
  ConnectedAccountRefreshOptionsSchema,
32
+ ConnectedAccountRevokeResponse,
33
+ ConnectedAccountCompleteAuthParams,
34
+ ConnectedAccountCompleteAuthParamsSchema,
35
+ ConnectedAccountCompleteAuthResponse,
32
36
  UpdateConnectedAccountAclParams,
33
37
  UpdateConnectedAccountParams,
34
38
  UpdateConnectedAccountParamsSchema,
@@ -45,9 +49,13 @@ import { telemetry } from '../telemetry/Telemetry';
45
49
  import {
46
50
  transformConnectedAccountListResponse,
47
51
  transformConnectedAccountResponse,
52
+ transformConnectedAccountRevokeResponse,
53
+ transformConnectedAccountCompleteAuthResponse,
48
54
  } from '../utils/transformers/connectedAccounts';
49
55
  import {
50
56
  ComposioAclOnlyForSharedError,
57
+ ComposioConnectedAccountNotRevokableError,
58
+ ComposioConnectedAccountRevocationNotSupportedError,
51
59
  ComposioFailedToCreateConnectedAccountLink,
52
60
  ComposioLegacyConnectedAccountsEndpointRetiredError,
53
61
  ComposioMultipleConnectedAccountsError,
@@ -554,6 +562,11 @@ export class ConnectedAccounts {
554
562
  * // Refresh a connected account's credentials
555
563
  * const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123');
556
564
  * ```
565
+ *
566
+ * @deprecated The `POST /connected_accounts/{id}/refresh` endpoint is deprecated by the
567
+ * Composio API. Re-initiate authentication instead: `composio.connectedAccounts.link(userId, authConfigId)`
568
+ * for a fresh connection, or `session.authorize(toolkit)` from a session. Behaviour is unchanged
569
+ * while the endpoint remains available; do not generate new code against `refresh`.
557
570
  */
558
571
  async refresh(
559
572
  nanoid: string,
@@ -570,9 +583,14 @@ export class ConnectedAccounts {
570
583
  });
571
584
  }
572
585
 
586
+ if (parsedOptions.data.validateCredentials !== undefined) {
587
+ logger.warn(
588
+ 'connectedAccounts.refresh(): the Composio API no longer accepts `validateCredentials`; the option is ignored.'
589
+ );
590
+ }
591
+
573
592
  params = {
574
593
  query_redirect_url: parsedOptions.data.redirectUrl,
575
- validate_credentials: parsedOptions.data.validateCredentials,
576
594
  };
577
595
  }
578
596
 
@@ -582,6 +600,104 @@ export class ConnectedAccounts {
582
600
  );
583
601
  }
584
602
 
603
+ /**
604
+ * Revoke a connected account at the upstream provider.
605
+ *
606
+ * Best-effort upstream revocation of the stored tokens/credentials; on
607
+ * success the connection status becomes `REVOKED`. Revoking an already
608
+ * revoked connection returns an empty `revokedTokens` list without an
609
+ * upstream call.
610
+ *
611
+ * @param {string} nanoid - The unique identifier of the connected account to revoke
612
+ * @returns {Promise<ConnectedAccountRevokeResponse>} Which tokens were revoked and the resulting status
613
+ * @throws {ComposioConnectedAccountRevocationNotSupportedError} If the toolkit does not support programmatic revocation (400)
614
+ * @throws {ComposioConnectedAccountNotRevokableError} If the connection is not in a revokable state (409)
615
+ *
616
+ * @example
617
+ * ```typescript
618
+ * const result = await composio.connectedAccounts.revoke('conn_abc123');
619
+ * console.log(result.connectedAccount.status); // 'REVOKED'
620
+ * console.log(result.revokedTokens); // e.g. ['access_token', 'refresh_token']
621
+ * ```
622
+ */
623
+ async revoke(
624
+ nanoid: string,
625
+ requestOptions?: ComposioRequestOptions
626
+ ): Promise<ConnectedAccountRevokeResponse> {
627
+ try {
628
+ const result = await withCancellation(
629
+ () => this.client.connectedAccounts.revoke(nanoid, requestOptions),
630
+ requestOptions?.signal
631
+ );
632
+ return transformConnectedAccountRevokeResponse(result);
633
+ } catch (error) {
634
+ if (error instanceof BadRequestError) {
635
+ throw new ComposioConnectedAccountRevocationNotSupportedError(
636
+ `Connected account ${nanoid} cannot be revoked programmatically: ${error.message}`,
637
+ { cause: error, meta: { nanoid } }
638
+ );
639
+ }
640
+ if (error instanceof ConflictError) {
641
+ throw new ComposioConnectedAccountNotRevokableError(
642
+ `Connected account ${nanoid} is not in a revokable state: ${error.message}`,
643
+ { cause: error, meta: { nanoid } }
644
+ );
645
+ }
646
+ throw error;
647
+ }
648
+ }
649
+
650
+ /**
651
+ * Complete a deferred OAuth connection once you have verified the user's
652
+ * identity.
653
+ *
654
+ * When your project has an OAuth callback verifier configured, Composio
655
+ * does not activate a new OAuth connection by itself: it redirects to your
656
+ * verifier with a single-use session URI. After confirming who the user is,
657
+ * redeem that session URI here; Composio checks that your project owns the
658
+ * pending connection and that `userId` is its owner, completes the token
659
+ * exchange, and the connection becomes `ACTIVE`.
660
+ *
661
+ * The session URI is single-use: redeeming it twice, or after it expires,
662
+ * fails with a 404 from the API.
663
+ *
664
+ * @param {ConnectedAccountCompleteAuthParams} params - `userId` the connection was initiated for and the verifier's `sessionUri`
665
+ * @returns {Promise<ConnectedAccountCompleteAuthResponse>} The completed connection's ID and toolkit
666
+ * @throws {ValidationError} If the params fail validation
667
+ *
668
+ * @example
669
+ * ```typescript
670
+ * // In your verifier route, after authenticating the user:
671
+ * const { connectedAccountId, toolkitSlug } = await composio.connectedAccounts.completeAuth({
672
+ * userId: 'user_123',
673
+ * sessionUri, // the session URI from the verifier redirect
674
+ * });
675
+ * ```
676
+ */
677
+ async completeAuth(
678
+ params: ConnectedAccountCompleteAuthParams,
679
+ requestOptions?: ComposioRequestOptions
680
+ ): Promise<ConnectedAccountCompleteAuthResponse> {
681
+ const parsedParams = ConnectedAccountCompleteAuthParamsSchema.safeParse(params);
682
+ if (!parsedParams.success) {
683
+ throw new ValidationError('Failed to parse connected account completeAuth params', {
684
+ cause: parsedParams.error,
685
+ });
686
+ }
687
+ const result = await withCancellation(
688
+ () =>
689
+ this.client.connectedAccounts.completeAuth(
690
+ {
691
+ user_id: parsedParams.data.userId,
692
+ session_uri: parsedParams.data.sessionUri,
693
+ },
694
+ requestOptions
695
+ ),
696
+ requestOptions?.signal
697
+ );
698
+ return transformConnectedAccountCompleteAuthResponse(result);
699
+ }
700
+
585
701
  /**
586
702
  * Update the status of a connected account
587
703
  * @param {string} nanoid - Unique identifier of the connected account
@@ -0,0 +1,169 @@
1
+ /**
2
+ * @fileoverview `composio.experimental.customToolkits`: register and manage
3
+ * project-owned custom toolkits.
4
+ * **Experimental — custom toolkits are in pilot; shape may change.**
5
+ *
6
+ * @module CustomToolkits
7
+ */
8
+ import ComposioClient from '@composio/client';
9
+ import {
10
+ CustomToolkitDeleteResponse,
11
+ CustomToolkitSyncParams,
12
+ CustomToolkitSyncParamsSchema,
13
+ CustomToolkitSyncResponse,
14
+ CustomToolkitUpsertParams,
15
+ CustomToolkitUpsertParamsSchema,
16
+ CustomToolkitUpsertResponse,
17
+ } from '../types/customToolkits.types';
18
+ import { ComposioRequestOptions } from '../types/requestOptions.types';
19
+ import { ValidationError } from '../errors/ValidationErrors';
20
+ import { telemetry } from '../telemetry/Telemetry';
21
+ import { withCancellation } from '../utils/cancellation';
22
+ import {
23
+ transformCustomToolkitDeleteResponse,
24
+ transformCustomToolkitSyncParams,
25
+ transformCustomToolkitSyncResponse,
26
+ transformCustomToolkitUpsertParams,
27
+ transformCustomToolkitUpsertResponse,
28
+ } from '../utils/transformers/customToolkits';
29
+
30
+ /**
31
+ * `composio.experimental.customToolkits` — toolkits your project registers
32
+ * from its own app or MCP server, with their own auth configs and connected
33
+ * accounts. **Experimental — custom toolkits are in pilot; shape may change.**
34
+ *
35
+ * These live on the Composio platform. They are unrelated to the in-process
36
+ * toolkits built with `experimental_createToolkit()`, which run inside your
37
+ * application.
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const { slug } = await composio.experimental.customToolkits.upsert({
42
+ * slug: 'MY_TOOLKIT',
43
+ * toolkitConfig: {
44
+ * name: 'My Toolkit',
45
+ * appUrl: 'https://mcp.example.com/mcp',
46
+ * authSchemes: [{ mode: 'DCR_OAUTH', discoveryUrl: 'https://mcp.example.com/.well-known/oauth-authorization-server' }],
47
+ * },
48
+ * });
49
+ * await composio.experimental.customToolkits.sync(slug);
50
+ * ```
51
+ */
52
+ export class CustomToolkits {
53
+ private client: ComposioClient;
54
+
55
+ constructor(client: ComposioClient) {
56
+ this.client = client;
57
+ telemetry.instrument(this, 'CustomToolkits');
58
+ }
59
+
60
+ /**
61
+ * Creates a custom toolkit, or updates its display metadata (name, API key
62
+ * field copy) when the project already owns a toolkit with this slug.
63
+ * **Experimental — custom toolkits are in pilot; shape may change.**
64
+ *
65
+ * `appUrl` and `authSchemes` cannot change on an existing toolkit:
66
+ * re-sending them unchanged is a no-op, and changing them fails with a 409.
67
+ * Delete and re-register the toolkit instead, which revokes its connections.
68
+ *
69
+ * @param {CustomToolkitUpsertParams} params - The slug and toolkit configuration
70
+ * @returns {Promise<CustomToolkitUpsertResponse>} The toolkit's slug
71
+ * @throws {ValidationError} If the params fail validation
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * await composio.experimental.customToolkits.upsert({
76
+ * slug: 'INTERNAL_API',
77
+ * toolkitConfig: {
78
+ * name: 'Internal API',
79
+ * appUrl: 'https://mcp.internal.example.com/mcp',
80
+ * authSchemes: [
81
+ * { mode: 'API_KEY', headers: { Authorization: 'Bearer {{generic_api_key}}' } },
82
+ * ],
83
+ * },
84
+ * });
85
+ * ```
86
+ */
87
+ async upsert(
88
+ params: CustomToolkitUpsertParams,
89
+ requestOptions?: ComposioRequestOptions
90
+ ): Promise<CustomToolkitUpsertResponse> {
91
+ const parsedParams = CustomToolkitUpsertParamsSchema.safeParse(params);
92
+ if (!parsedParams.success) {
93
+ throw new ValidationError('Failed to parse custom toolkit upsert params', {
94
+ cause: parsedParams.error,
95
+ });
96
+ }
97
+ const body = transformCustomToolkitUpsertParams(parsedParams.data);
98
+ const result = await withCancellation(
99
+ () => this.client.custom.upsert(body, requestOptions),
100
+ requestOptions?.signal
101
+ );
102
+ return transformCustomToolkitUpsertResponse(result);
103
+ }
104
+
105
+ /**
106
+ * Re-fetches the tool definitions of a custom toolkit from its remote MCP
107
+ * server. Call it when automatic sync fails or the remote tools change.
108
+ * **Experimental — custom toolkits are in pilot; shape may change.**
109
+ *
110
+ * @param {string} slug - The custom toolkit slug (`CUSTOM_...`)
111
+ * @param {CustomToolkitSyncParams} [params] - Optional connected account to fetch the definitions with
112
+ * @returns {Promise<CustomToolkitSyncResponse>} The toolkit version and number of tools synced
113
+ * @throws {ValidationError} If the params fail validation
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * const { version, syncedCount } = await composio.experimental.customToolkits.sync(
118
+ * 'CUSTOM_MY_TOOLKIT',
119
+ * { connectedAccountId: 'ca_abc123' }
120
+ * );
121
+ * ```
122
+ */
123
+ async sync(
124
+ slug: string,
125
+ params?: CustomToolkitSyncParams,
126
+ requestOptions?: ComposioRequestOptions
127
+ ): Promise<CustomToolkitSyncResponse> {
128
+ const parsedParams = CustomToolkitSyncParamsSchema.safeParse(params ?? {});
129
+ if (!parsedParams.success) {
130
+ throw new ValidationError('Failed to parse custom toolkit sync params', {
131
+ cause: parsedParams.error,
132
+ });
133
+ }
134
+ const body = transformCustomToolkitSyncParams(slug, parsedParams.data);
135
+ const result = await withCancellation(
136
+ () => this.client.custom.sync(body, requestOptions),
137
+ requestOptions?.signal
138
+ );
139
+ return transformCustomToolkitSyncResponse(result);
140
+ }
141
+
142
+ /**
143
+ * Deletes a custom toolkit owned by the project, with its tools, auth
144
+ * configs and connected accounts. The credentials behind those connected
145
+ * accounts are revoked in background jobs (`revokeJobIds`).
146
+ * **Experimental — custom toolkits are in pilot; shape may change.**
147
+ *
148
+ * Composio-managed toolkits cannot be deleted; the API answers 403.
149
+ *
150
+ * @param {string} slug - The custom toolkit slug (`CUSTOM_...`)
151
+ * @returns {Promise<CustomToolkitDeleteResponse>} What was deleted
152
+ *
153
+ * @example
154
+ * ```typescript
155
+ * const result = await composio.experimental.customToolkits.delete('CUSTOM_MY_TOOLKIT');
156
+ * console.log(result.connectedAccountsDeleted);
157
+ * ```
158
+ */
159
+ async delete(
160
+ slug: string,
161
+ requestOptions?: ComposioRequestOptions
162
+ ): Promise<CustomToolkitDeleteResponse> {
163
+ const result = await withCancellation(
164
+ () => this.client.custom.deleteToolkit(slug, requestOptions),
165
+ requestOptions?.signal
166
+ );
167
+ return transformCustomToolkitDeleteResponse(result);
168
+ }
169
+ }