@composio/core 0.25.0 → 0.27.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 (37) hide show
  1. package/dist/{CustomTool-DZY1yLHN.d.mts → CustomTool-CqPoLUD6.d.mts} +1 -1
  2. package/dist/{cancellation-D-tMPk48.mjs → cancellation-ZoRh6EJQ.mjs} +54 -2
  3. package/dist/{composio-B8AENilE.d.mts → composio-BUa10iB3.d.mts} +65 -57
  4. package/dist/{customTool.types-Bi6-keZC.d.mts → customTool.types-gX421uPT.d.mts} +789 -33
  5. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +3 -3
  6. package/dist/docs/reference/sdk-reference/typescript/session.mdx +2 -1
  7. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +5 -1
  8. package/dist/experimental/index.d.mts +2 -2
  9. package/dist/index.d.mts +18 -13
  10. package/dist/index.mjs +6787 -6316
  11. package/dist/{types-BGDMkEUl.d.mts → types-DXxfzBX3.d.mts} +2 -2
  12. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  13. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  14. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  15. package/dist/utils/modifiers/FileToolModifier.node.mjs +1 -1
  16. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  17. package/package.json +3 -3
  18. package/src/composio.ts +68 -57
  19. package/src/lib/toolRouterMcp.ts +2 -0
  20. package/src/lib/toolRouterParams.ts +26 -3
  21. package/src/models/ConnectedAccounts.ts +7 -16
  22. package/src/models/SessionContext.ts +2 -17
  23. package/src/models/ToolRouter.ts +9 -2
  24. package/src/models/ToolRouterSession.ts +4 -19
  25. package/src/models/Tools.ts +1 -4
  26. package/src/models/Triggers.ts +6 -1
  27. package/src/services/internal/InternalService.ts +3 -4
  28. package/src/services/pusher/Pusher.ts +11 -4
  29. package/src/types/connectedAccountAuthStates.types.ts +2 -1
  30. package/src/types/requestOptions.types.ts +1 -10
  31. package/src/types/toolRouter.types.ts +156 -11
  32. package/src/utils/jsonSchema.ts +76 -4
  33. package/src/utils/sdk.ts +172 -11
  34. package/src/utils/toolkitDeprecation.ts +271 -0
  35. package/src/utils/transformers/connectedAccounts.ts +9 -20
  36. package/src/utils/transformers/mcp.ts +3 -10
  37. package/src/utils/transformers/toolRouterResponseTransform.ts +123 -5
package/src/utils/sdk.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { z } from 'zod/v3';
2
+ import { Auth } from '@composio/client';
3
+ import type { Scope } from '@composio/client';
2
4
  import {
3
5
  ComposioAPIKeyKindError,
4
6
  ComposioNoAPIKeyError,
@@ -29,12 +31,29 @@ const USER_API_KEY_PREFIX = 'uak_';
29
31
  */
30
32
  export const PROJECT_API_KEY_HEADER = 'x-api-key';
31
33
 
34
+ /** Header that carries the organization API key (`oak_...`). */
35
+ export const ORG_API_KEY_HEADER = 'x-org-api-key';
36
+
32
37
  /** Header carrying the organization nano ID that scopes user-key requests. */
33
38
  export const ORG_ID_HEADER = 'x-org-id';
34
39
 
35
40
  /** Header carrying the project nano ID that scopes user-key requests. */
36
41
  export const PROJECT_ID_HEADER = 'x-project-id';
37
42
 
43
+ /**
44
+ * Header names the SDK owns: the API client sends a credential from its
45
+ * `auth` and the scope from its `scope`, and refuses these names in its
46
+ * `defaultHeaders`. The SDK folds caller-supplied entries into its own
47
+ * credential and scope options instead of forwarding them.
48
+ */
49
+ const SDK_OWNED_HEADERS = [
50
+ PROJECT_API_KEY_HEADER,
51
+ USER_API_KEY_HEADER,
52
+ ORG_API_KEY_HEADER,
53
+ ORG_ID_HEADER,
54
+ PROJECT_ID_HEADER,
55
+ ];
56
+
38
57
  // File path helpers
39
58
  export const userDataPath = () => {
40
59
  try {
@@ -138,8 +157,13 @@ const findHeader = (
138
157
  */
139
158
  export const getUserApiKeyHeader = (
140
159
  headers: ComposioRequestHeaders | undefined
160
+ ): { name: string; value: string } | undefined => getCredentialHeader(headers, USER_API_KEY_HEADER);
161
+
162
+ const getCredentialHeader = (
163
+ headers: ComposioRequestHeaders | undefined,
164
+ name: string
141
165
  ): { name: string; value: string } | undefined => {
142
- const header = findHeader(headers, USER_API_KEY_HEADER);
166
+ const header = findHeader(headers, name);
143
167
  return header && typeof header.value === 'string' && header.value.length > 0 ? header : undefined;
144
168
  };
145
169
 
@@ -148,6 +172,8 @@ export type CredentialHeaderInput = {
148
172
  apiKey: string | null | undefined;
149
173
  /** The user API key the client resolved (`userApiKey` option or `COMPOSIO_USER_API_KEY`). */
150
174
  userApiKey: string | null | undefined;
175
+ /** The organization API key the client resolved (`orgApiKey` option or `COMPOSIO_ORG_API_KEY`). */
176
+ orgApiKey?: string | null;
151
177
  /** The default headers configured on the SDK instance; only `x-user-api-key` is consulted. */
152
178
  defaultHeaders: ComposioRequestHeaders | undefined;
153
179
  };
@@ -158,8 +184,9 @@ export type CredentialHeaderInput = {
158
184
  * headers wins: the client treats a caller-placed credential header as the
159
185
  * credential and suppresses the configured keys. Otherwise the project key
160
186
  * travels as `x-api-key`, otherwise the resolved user API key as
161
- * `x-user-api-key`. Empty when no credential is held. The environment is
162
- * never consulted here.
187
+ * `x-user-api-key`, otherwise the organization API key as `x-org-api-key`
188
+ * (the order {@link toClientAuth} picks them in). Empty when no credential is
189
+ * held. The environment is never consulted here.
163
190
  */
164
191
  export const resolveCredentialHeaders = (input: CredentialHeaderInput): Record<string, string> => {
165
192
  const userApiKeyHeader = getUserApiKeyHeader(input.defaultHeaders);
@@ -172,6 +199,9 @@ export const resolveCredentialHeaders = (input: CredentialHeaderInput): Record<s
172
199
  if (hasValue(input.userApiKey)) {
173
200
  return { [USER_API_KEY_HEADER]: input.userApiKey };
174
201
  }
202
+ if (hasValue(input.orgApiKey)) {
203
+ return { [ORG_API_KEY_HEADER]: input.orgApiKey };
204
+ }
175
205
  return {};
176
206
  };
177
207
 
@@ -242,11 +272,29 @@ export function resolveSDKScope(options: SDKScopeOptions): SDKScope {
242
272
  return orgId === undefined || projectId === undefined ? {} : { orgId, projectId };
243
273
  }
244
274
 
245
- /** The `x-org-id` / `x-project-id` headers for a resolved scope. */
246
- export const getScopeHeaders = (scope: SDKScope): ComposioRequestHeaders =>
275
+ /**
276
+ * The API client `scope` for a resolved SDK scope: the organization and
277
+ * project nano IDs the client sends as `x-org-id` / `x-project-id`, or
278
+ * `undefined` when the instance is unscoped.
279
+ */
280
+ export const toClientScope = (scope: SDKScope): Scope | undefined =>
247
281
  scope.orgId && scope.projectId
248
- ? { [ORG_ID_HEADER]: scope.orgId, [PROJECT_ID_HEADER]: scope.projectId }
249
- : {};
282
+ ? { organizationId: scope.orgId, projectId: scope.projectId }
283
+ : undefined;
284
+
285
+ /**
286
+ * `headers` without the credential and scope entries the SDK owns (matched
287
+ * case-insensitively). Those travel through the API client's `auth` and
288
+ * `scope`, which refuse the same names in `defaultHeaders`.
289
+ */
290
+ export const withoutSDKOwnedHeaders = (
291
+ headers: ComposioRequestHeaders | undefined
292
+ ): ComposioRequestHeaders | undefined =>
293
+ headers === undefined
294
+ ? undefined
295
+ : Object.fromEntries(
296
+ Object.entries(headers).filter(([name]) => !SDK_OWNED_HEADERS.includes(name.toLowerCase()))
297
+ );
250
298
 
251
299
  export type SDKConfigOptions = {
252
300
  /** Default headers the SDK will attach to every request. */
@@ -297,15 +345,127 @@ const resolveAlternateCredential = (
297
345
  export const resolveUserApiKey = (userApiKey: string | null | undefined): string | undefined =>
298
346
  resolveAlternateCredential(userApiKey, 'COMPOSIO_USER_API_KEY');
299
347
 
348
+ /**
349
+ * The organization API key the instance holds: the `orgApiKey` option when it
350
+ * was passed (including `null`, which disables the fallback), otherwise
351
+ * `COMPOSIO_ORG_API_KEY`.
352
+ */
353
+ export const resolveOrgApiKey = (orgApiKey: string | null | undefined): string | undefined =>
354
+ resolveAlternateCredential(orgApiKey, 'COMPOSIO_ORG_API_KEY');
355
+
300
356
  /**
301
357
  * Whether the instance holds a credential other than the project key: a user
302
358
  * or organization API key (explicit or environment-resolved, as the API client
303
- * will see it), or a user API key placed in the default headers.
359
+ * will see it), or a user or organization API key placed in the default
360
+ * headers, which {@link resolveSDKCredentials} folds in.
304
361
  */
305
362
  const hasAlternateCredential = (options: SDKConfigOptions): boolean =>
306
363
  resolveUserApiKey(options.userApiKey) !== undefined ||
307
- resolveAlternateCredential(options.orgApiKey, 'COMPOSIO_ORG_API_KEY') !== undefined ||
308
- getUserApiKeyHeader(options.defaultHeaders) !== undefined;
364
+ resolveOrgApiKey(options.orgApiKey) !== undefined ||
365
+ getUserApiKeyHeader(options.defaultHeaders) !== undefined ||
366
+ getCredentialHeader(options.defaultHeaders, ORG_API_KEY_HEADER) !== undefined;
367
+
368
+ /**
369
+ * The credentials an SDK instance authenticates with, after the environment
370
+ * fallbacks and the credential default headers are applied. `null` is a
371
+ * credential the instance does not hold.
372
+ */
373
+ export type SDKCredentials = {
374
+ /** The project API key, or `null` when project-key auth is disabled. */
375
+ apiKey: string | null;
376
+ /** The user API key (`uak_...`), or `null`. */
377
+ userApiKey: string | null;
378
+ /** The organization API key (`oak_...`), or `null`. */
379
+ orgApiKey: string | null;
380
+ };
381
+
382
+ export type SDKCredentialsInput = {
383
+ /** The project API key {@link getSDKConfig} resolved. */
384
+ apiKey: string | null;
385
+ /** The `userApiKey` option as passed: `undefined` falls back to `COMPOSIO_USER_API_KEY`. */
386
+ userApiKey?: string | null;
387
+ /** The `orgApiKey` option as passed: `undefined` falls back to `COMPOSIO_ORG_API_KEY`. */
388
+ orgApiKey?: string | null;
389
+ /** Default headers the caller configured; only the credential headers are read. */
390
+ defaultHeaders?: ComposioRequestHeaders;
391
+ };
392
+
393
+ const CREDENTIAL_HEADERS = [PROJECT_API_KEY_HEADER, USER_API_KEY_HEADER, ORG_API_KEY_HEADER];
394
+
395
+ /**
396
+ * Resolves the credentials of an SDK instance.
397
+ *
398
+ * The user and organization keys fall back to `COMPOSIO_USER_API_KEY` and
399
+ * `COMPOSIO_ORG_API_KEY` when their option is omitted. A non-empty credential
400
+ * header in `defaultHeaders` (any letter case) is folded in as the credential
401
+ * it names, and it is the credential the instance sends, as it was when the
402
+ * header itself went on the wire: an `x-user-api-key` or `x-org-api-key` entry
403
+ * disables the project key and takes the place of the configured user or
404
+ * organization key, and an `x-api-key` entry takes the place of the project
405
+ * key. At most one credential header may be set: the API rejects a request
406
+ * that carries two.
407
+ */
408
+ export function resolveSDKCredentials(input: SDKCredentialsInput): SDKCredentials {
409
+ const headers = CREDENTIAL_HEADERS.flatMap(name => {
410
+ const header = findHeader(input.defaultHeaders, name);
411
+ return header && hasValue(header.value) ? [{ ...header, canonical: name }] : [];
412
+ });
413
+ if (headers.length > 1) {
414
+ throw new ComposioError('`defaultHeaders` carries more than one credential header', {
415
+ cause: `The API accepts exactly one credential per request, and \`defaultHeaders\` sets ${headers
416
+ .map(header => `\`${header.name}\``)
417
+ .join(' and ')}`,
418
+ possibleFixes: [
419
+ 'Pass credentials through `apiKey`, `userApiKey` and `orgApiKey` instead of default headers',
420
+ 'Keep at most one of `x-api-key`, `x-user-api-key` and `x-org-api-key` in `defaultHeaders`',
421
+ ],
422
+ });
423
+ }
424
+ const userApiKey = resolveUserApiKey(input.userApiKey) ?? null;
425
+ const orgApiKey = resolveOrgApiKey(input.orgApiKey) ?? null;
426
+ const [header] = headers;
427
+ switch (header?.canonical) {
428
+ case USER_API_KEY_HEADER:
429
+ return { apiKey: null, userApiKey: header.value, orgApiKey };
430
+ case ORG_API_KEY_HEADER:
431
+ return { apiKey: null, userApiKey: null, orgApiKey: header.value };
432
+ case PROJECT_API_KEY_HEADER:
433
+ return { apiKey: header.value, userApiKey, orgApiKey };
434
+ default:
435
+ return { apiKey: input.apiKey, userApiKey, orgApiKey };
436
+ }
437
+ }
438
+
439
+ /**
440
+ * The API client `auth` for the credentials of an SDK instance.
441
+ *
442
+ * - A project key alone authenticates every request with it.
443
+ * - A project key with a user and/or organization key selects one per
444
+ * operation: the project key wherever the operation accepts it, otherwise
445
+ * the first declared scheme a key is held for.
446
+ * - Without a project key, the user key authenticates every request (sessions
447
+ * included, whose operations declare no scheme), and the organization key
448
+ * does when it is the only one held.
449
+ */
450
+ export const toClientAuth = (credentials: SDKCredentials): Auth => {
451
+ const { apiKey, userApiKey, orgApiKey } = credentials;
452
+ if (apiKey !== null) {
453
+ return userApiKey === null && orgApiKey === null
454
+ ? Auth.project(apiKey)
455
+ : Auth.auto({
456
+ project: apiKey,
457
+ user: userApiKey ?? undefined,
458
+ organization: orgApiKey ?? undefined,
459
+ });
460
+ }
461
+ if (userApiKey !== null) {
462
+ return Auth.user(userApiKey);
463
+ }
464
+ if (orgApiKey !== null) {
465
+ return Auth.organization(orgApiKey);
466
+ }
467
+ throw new ComposioNoAPIKeyError();
468
+ };
309
469
 
310
470
  /**
311
471
  * Resolves the base URL and project API key the SDK will use.
@@ -318,7 +478,8 @@ const hasAlternateCredential = (options: SDKConfigOptions): boolean =>
318
478
  * `api_key` is read, and the resolver only succeeds when the instance holds
319
479
  * another credential: a `userApiKey` or `orgApiKey` (explicit, or resolved
320
480
  * from `COMPOSIO_USER_API_KEY` / `COMPOSIO_ORG_API_KEY` the way the API
321
- * client does), or a non-empty `x-user-api-key` entry in `defaultHeaders`.
481
+ * client does), or a non-empty `x-user-api-key` or `x-org-api-key` entry in
482
+ * `defaultHeaders`.
322
483
  * An `x-api-key` entry in `defaultHeaders` (any letter case) is rejected in
323
484
  * that mode: the project credential is only ever set from `apiKey`.
324
485
  *
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Toolkit version deprecation warnings.
3
+ *
4
+ * When a request resolves to a deprecated toolkit version, the API adds a
5
+ * `Composio-Deprecated-Toolkits` response header (an RFC 9651 structured-field
6
+ * list). This module parses that header below the generated client, through a
7
+ * `fetch` wrapper, and warns once per process for each deprecated toolkit
8
+ * version it sees. The response itself is never read, cloned or altered.
9
+ *
10
+ * Example header:
11
+ *
12
+ * "GMAIL";version="20250114_00";deprecated=@1779840000;sunset=@1787788800;reason="lifecycle"
13
+ */
14
+ import { z } from 'zod';
15
+ import logger from './logger';
16
+ import { normalizeToolkitSlug } from './toolkitVersion';
17
+
18
+ /** Response header name. `Headers.get` is case-insensitive. */
19
+ export const TOOLKIT_DEPRECATION_HEADER = 'composio-deprecated-toolkits';
20
+
21
+ /** Anchor of the docs section every warning points at. */
22
+ export const TOOLKIT_DEPRECATION_DOCS_URL =
23
+ 'https://docs.composio.dev/docs/tools-direct/toolkit-versioning#deprecation-and-sunset';
24
+
25
+ /** Versions named per toolkit before the formatter collapses the rest into "and N more". */
26
+ const MAX_VERSIONS_PER_LINE = 5;
27
+
28
+ /**
29
+ * The three limits below mirror the `@composio/client` deprecation module,
30
+ * which reads the same kind of server-controlled header.
31
+ */
32
+ /** A header longer than this is ignored whole rather than parsed. */
33
+ const MAX_HEADER_LENGTH = 2048;
34
+ /** A header holding any of these is ignored whole, so nothing partially cleaned reaches the log. */
35
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/;
36
+ /** Keys the process will ever record; past this, new versions are neither recorded nor warned about. */
37
+ const MAX_TRACKED_VERSIONS = 1024;
38
+
39
+ const DeprecatedToolkitEntrySchema = z.object({
40
+ slug: z.string().min(1),
41
+ version: z.string().min(1),
42
+ deprecatedAt: z.date().optional(),
43
+ sunsetAt: z.date().optional(),
44
+ reason: z.string().min(1).optional(),
45
+ });
46
+
47
+ export type DeprecatedToolkitEntry = z.infer<typeof DeprecatedToolkitEntrySchema>;
48
+
49
+ /** Keys (`UPPER(slug)@version`) already warned about in this process. */
50
+ const warnedToolkitVersions = new Set<string>();
51
+
52
+ const dedupeKey = (entry: Pick<DeprecatedToolkitEntry, 'slug' | 'version'>): string =>
53
+ `${entry.slug.toUpperCase()}@${entry.version}`;
54
+
55
+ /**
56
+ * Splits `value` on `delimiter` characters that sit outside double-quoted
57
+ * strings, honouring backslash escapes inside the quotes. Empty pieces are
58
+ * dropped and the rest are trimmed.
59
+ */
60
+ const splitOutsideQuotes = (value: string, delimiter: string): string[] => {
61
+ const pieces: string[] = [];
62
+ let current = '';
63
+ let inString = false;
64
+ for (let index = 0; index < value.length; index++) {
65
+ const char = value[index];
66
+ if (inString) {
67
+ current += char;
68
+ if (char === '\\' && index + 1 < value.length) {
69
+ index += 1;
70
+ current += value[index];
71
+ } else if (char === '"') {
72
+ inString = false;
73
+ }
74
+ } else if (char === '"') {
75
+ inString = true;
76
+ current += char;
77
+ } else if (char === delimiter) {
78
+ pieces.push(current);
79
+ current = '';
80
+ } else {
81
+ current += char;
82
+ }
83
+ }
84
+ pieces.push(current);
85
+ return pieces.map(piece => piece.trim()).filter(piece => piece.length > 0);
86
+ };
87
+
88
+ /**
89
+ * Decodes an sf-string (`"..."` with `\"` and `\\` escapes). Returns
90
+ * `undefined` for anything that is not a complete, validly escaped sf-string.
91
+ */
92
+ const decodeSfString = (raw: string): string | undefined => {
93
+ const match = /^"((?:[^"\\]|\\.)*)"$/.exec(raw);
94
+ if (match === null) return undefined;
95
+ let invalidEscape = false;
96
+ const decoded = match[1].replace(/\\(.)/g, (_whole, escaped: string) => {
97
+ if (escaped === '"' || escaped === '\\') return escaped;
98
+ invalidEscape = true;
99
+ return '';
100
+ });
101
+ return invalidEscape ? undefined : decoded;
102
+ };
103
+
104
+ /** Decodes an sf-date (`@` followed by Unix seconds). */
105
+ const decodeSfDate = (raw: string): Date | undefined => {
106
+ const match = /^@(-?\d{1,15})$/.exec(raw);
107
+ if (match === null) return undefined;
108
+ const date = new Date(Number(match[1]) * 1000);
109
+ return Number.isNaN(date.getTime()) ? undefined : date;
110
+ };
111
+
112
+ /** Header parameters the SDK understands, by wire name. */
113
+ const KNOWN_PARAMETERS = new Map<
114
+ string,
115
+ { name: Exclude<keyof DeprecatedToolkitEntry, 'slug'>; kind: 'string' | 'date' }
116
+ >([
117
+ ['version', { name: 'version', kind: 'string' }],
118
+ ['reason', { name: 'reason', kind: 'string' }],
119
+ ['deprecated', { name: 'deprecatedAt', kind: 'date' }],
120
+ ['sunset', { name: 'sunsetAt', kind: 'date' }],
121
+ ]);
122
+
123
+ /**
124
+ * Parses one list item: an sf-string slug followed by `;key=value` parameters.
125
+ * Unknown parameters are ignored; a known parameter with the wrong type drops
126
+ * the item.
127
+ */
128
+ const parseItem = (item: string): DeprecatedToolkitEntry | undefined => {
129
+ const [head, ...params] = splitOutsideQuotes(item, ';');
130
+ if (head === undefined) return undefined;
131
+ const candidate: Record<string, unknown> = { slug: decodeSfString(head) };
132
+ for (const param of params) {
133
+ const separator = param.indexOf('=');
134
+ if (separator === -1) continue;
135
+ const key = param.slice(0, separator).trim();
136
+ const rawValue = param.slice(separator + 1).trim();
137
+ const field = KNOWN_PARAMETERS.get(key);
138
+ if (field === undefined) continue;
139
+ const decoded = field.kind === 'string' ? decodeSfString(rawValue) : decodeSfDate(rawValue);
140
+ if (decoded === undefined) return undefined;
141
+ candidate[field.name] = decoded;
142
+ }
143
+ const parsed = DeprecatedToolkitEntrySchema.safeParse(candidate);
144
+ return parsed.success ? parsed.data : undefined;
145
+ };
146
+
147
+ /**
148
+ * Parses a `Composio-Deprecated-Toolkits` header value. Items that fail to
149
+ * parse are dropped silently; garbage input yields an empty array. Never throws.
150
+ */
151
+ export function parseDeprecatedToolkitsHeader(value: string): DeprecatedToolkitEntry[] {
152
+ try {
153
+ const entries: DeprecatedToolkitEntry[] = [];
154
+ for (const item of splitOutsideQuotes(value, ',')) {
155
+ const entry = parseItem(item);
156
+ if (entry !== undefined) entries.push(entry);
157
+ }
158
+ return entries;
159
+ } catch {
160
+ return [];
161
+ }
162
+ }
163
+
164
+ const isoDate = (date: Date): string => date.toISOString().slice(0, 10);
165
+
166
+ const pinHint = (slug: string, docsUrl: string): string => {
167
+ const configKey = normalizeToolkitSlug(slug);
168
+ const envVar = `COMPOSIO_TOOLKIT_VERSION_${slug.toUpperCase()}`;
169
+ return `Pin a newer version with toolkitVersions: { ${configKey}: '<version>' } or ${envVar}. See ${docsUrl}.`;
170
+ };
171
+
172
+ const formatSingle = (entry: DeprecatedToolkitEntry, docsUrl: string): string => {
173
+ let sentence = `[Deprecation] Toolkit ${entry.slug.toUpperCase()} version ${entry.version} was deprecated`;
174
+ if (entry.deprecatedAt !== undefined) sentence += ` on ${isoDate(entry.deprecatedAt)}`;
175
+ if (entry.reason !== undefined) sentence += ` (${entry.reason})`;
176
+ if (entry.sunsetAt !== undefined)
177
+ sentence += ` and will stop working on ${isoDate(entry.sunsetAt)}`;
178
+ return `${sentence}. ${pinHint(entry.slug, docsUrl)}`;
179
+ };
180
+
181
+ const formatGroup = (slug: string, entries: DeprecatedToolkitEntry[], docsUrl: string): string => {
182
+ const versions = entries.map(entry => entry.version);
183
+ const named = versions.slice(0, MAX_VERSIONS_PER_LINE).join(', ');
184
+ const remaining = versions.length - MAX_VERSIONS_PER_LINE;
185
+ const list = remaining > 0 ? `${named} and ${remaining} more` : named;
186
+ let sentence = `[Deprecation] Toolkit ${slug} versions ${list} are deprecated`;
187
+ const sunsets = entries
188
+ .map(entry => entry.sunsetAt)
189
+ .filter((date): date is Date => date !== undefined)
190
+ .sort((a, b) => a.getTime() - b.getTime());
191
+ if (sunsets.length > 0) {
192
+ sentence += ` and the earliest will stop working on ${isoDate(sunsets[0])}`;
193
+ }
194
+ return `${sentence}. ${pinHint(slug, docsUrl)}`;
195
+ };
196
+
197
+ /**
198
+ * Renders one warning line per toolkit slug. A slug with a single deprecated
199
+ * version gets the full sentence with its dates and reason; a slug with several
200
+ * names at most five versions and collapses the rest into "and N more".
201
+ */
202
+ export function formatToolkitDeprecationWarnings(
203
+ entries: DeprecatedToolkitEntry[],
204
+ docsUrl: string = TOOLKIT_DEPRECATION_DOCS_URL
205
+ ): string[] {
206
+ const groups = new Map<string, DeprecatedToolkitEntry[]>();
207
+ for (const entry of entries) {
208
+ const slug = entry.slug.toUpperCase();
209
+ const group = groups.get(slug);
210
+ if (group === undefined) groups.set(slug, [entry]);
211
+ else group.push(entry);
212
+ }
213
+ return Array.from(groups, ([slug, group]) =>
214
+ group.length === 1 ? formatSingle(group[0], docsUrl) : formatGroup(slug, group, docsUrl)
215
+ );
216
+ }
217
+
218
+ /**
219
+ * Parses the header on `response`, drops versions already warned about in this
220
+ * process, records the new ones and warns once per formatted line.
221
+ */
222
+ const warnDeprecatedToolkits = (response: Response): void => {
223
+ const value = response.headers.get(TOOLKIT_DEPRECATION_HEADER);
224
+ if (value === null || value.length === 0) return;
225
+ if (value.length > MAX_HEADER_LENGTH || CONTROL_CHARACTERS.test(value)) return;
226
+ if (warnedToolkitVersions.size >= MAX_TRACKED_VERSIONS) return;
227
+ const fresh: DeprecatedToolkitEntry[] = [];
228
+ for (const entry of parseDeprecatedToolkitsHeader(value)) {
229
+ const key = dedupeKey(entry);
230
+ if (warnedToolkitVersions.has(key) || warnedToolkitVersions.size >= MAX_TRACKED_VERSIONS)
231
+ continue;
232
+ warnedToolkitVersions.add(key);
233
+ fresh.push(entry);
234
+ }
235
+ for (const line of formatToolkitDeprecationWarnings(fresh)) {
236
+ logger.warn(line);
237
+ }
238
+ };
239
+
240
+ /**
241
+ * Wraps a `fetch` implementation so every response is checked for the
242
+ * `Composio-Deprecated-Toolkits` header. The wrapper is `this`-independent,
243
+ * returns the response unchanged on every path and never fails a call over
244
+ * the header: any error while inspecting it is logged at debug and swallowed.
245
+ *
246
+ * When no `baseFetch` is given, `globalThis.fetch` is resolved per call so a
247
+ * runtime that installs or replaces `fetch` after construction still works.
248
+ */
249
+ export function createToolkitDeprecationFetch(
250
+ baseFetch?: typeof globalThis.fetch
251
+ ): typeof globalThis.fetch {
252
+ return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
253
+ const target = baseFetch ?? globalThis.fetch;
254
+ const response = await target(input, init);
255
+ try {
256
+ warnDeprecatedToolkits(response);
257
+ } catch (error) {
258
+ try {
259
+ logger.debug('Failed to inspect the toolkit deprecation header', error);
260
+ } catch {
261
+ // The fallback is best-effort too: a sink that throws must not fail the call.
262
+ }
263
+ }
264
+ return response;
265
+ };
266
+ }
267
+
268
+ /** Clears the once-per-process record. Tests only. */
269
+ export function _resetToolkitDeprecationWarningsForTests(): void {
270
+ warnedToolkitVersions.clear();
271
+ }
@@ -23,13 +23,6 @@ import { ConnectionDataSchema } from '../../types/connectedAccountAuthStates.typ
23
23
  import logger from '../logger';
24
24
  import { transform } from '../transform';
25
25
 
26
- type RawConnectedAccountResponseWithLabels = (
27
- RawConnectedAccountRetrieveResponse | RawConnectedAccountListResponse['items'][0]
28
- ) & {
29
- word_id?: string | null;
30
- alias?: string | null;
31
- };
32
-
33
26
  /**
34
27
  * Transforms the raw connected account response from the Composio API to the SDK format.
35
28
  *
@@ -45,8 +38,6 @@ type RawConnectedAccountResponseWithLabels = (
45
38
  export function transformConnectedAccountResponse(
46
39
  response: RawConnectedAccountRetrieveResponse | RawConnectedAccountListResponse['items'][0]
47
40
  ): ConnectedAccountRetrieveResponse {
48
- const responseWithLabels = response as RawConnectedAccountResponseWithLabels;
49
-
50
41
  // Safely parse the state field, filtering out unsupported auth schemes
51
42
  const parseState = (state: unknown) => {
52
43
  try {
@@ -70,9 +61,9 @@ export function transformConnectedAccountResponse(
70
61
  isComposioManaged: response.auth_config.is_composio_managed,
71
62
  isDisabled: response.auth_config.is_disabled,
72
63
  },
73
- wordId: responseWithLabels.word_id ?? null,
74
- alias: responseWithLabels.alias ?? null,
75
- data: (response as unknown as ConnectedAccountRetrieveResponse).data ?? undefined,
64
+ wordId: response.word_id ?? null,
65
+ alias: response.alias ?? null,
66
+ data: response.data ?? undefined,
76
67
  state: parseState(response.state),
77
68
  status: response.status,
78
69
  statusReason: response.status_reason,
@@ -86,17 +77,15 @@ export function transformConnectedAccountResponse(
86
77
  // caller isn't authorised to see the ACL), so distinguish "I can't
87
78
  // see the ACL" from "ACL is the default deny-by-default state" by
88
79
  // checking field presence.
89
- experimental: responseWithLabels.experimental
80
+ experimental: response.experimental
90
81
  ? {
91
- accountType: responseWithLabels.experimental.account_type,
92
- aclConfigForShared: responseWithLabels.experimental.acl_config_for_shared
82
+ accountType: response.experimental.account_type,
83
+ aclConfigForShared: response.experimental.acl_config_for_shared
93
84
  ? {
94
- allowAllUsers:
95
- responseWithLabels.experimental.acl_config_for_shared.allow_all_users,
96
- allowedUserIds:
97
- responseWithLabels.experimental.acl_config_for_shared.allowed_user_ids,
85
+ allowAllUsers: response.experimental.acl_config_for_shared.allow_all_users,
86
+ allowedUserIds: response.experimental.acl_config_for_shared.allowed_user_ids,
98
87
  notAllowedUserIds:
99
- responseWithLabels.experimental.acl_config_for_shared.not_allowed_user_ids,
88
+ response.experimental.acl_config_for_shared.not_allowed_user_ids,
100
89
  }
101
90
  : undefined,
102
91
  }
@@ -32,9 +32,6 @@ export function transformMcpCreateResponse(
32
32
  const result = CustomCreateResponseSchema.safeParse({
33
33
  id: response.id,
34
34
  name: response.name,
35
- createdAt: (response as unknown as Record<string, unknown>).created_at,
36
- updatedAt: (response as unknown as Record<string, unknown>).updated_at,
37
- status: (response as unknown as Record<string, unknown>).status,
38
35
  });
39
36
 
40
37
  if (!result.success) {
@@ -55,7 +52,6 @@ export function transformMcpListResponse(response: McpListResponseRaw): McpListR
55
52
  name: item.name,
56
53
  createdAt: item.created_at,
57
54
  updatedAt: item.updated_at,
58
- status: (item as unknown as Record<string, unknown>).status,
59
55
  }));
60
56
 
61
57
  const result = McpListResponseSchema.safeParse({
@@ -82,7 +78,6 @@ export function transformMcpRetrieveResponse(
82
78
  name: response.name,
83
79
  createdAt: response.created_at,
84
80
  updatedAt: response.updated_at,
85
- status: (response as unknown as Record<string, unknown>).status,
86
81
  toolkits: response.toolkits,
87
82
  tools: response.allowed_tools,
88
83
  managedAuthViaComposio: response.managed_auth_via_composio,
@@ -105,9 +100,8 @@ export function transformMcpRetrieveResponse(
105
100
  */
106
101
  export function transformMcpDeleteResponse(response: McpDeleteResponseRaw): McpDeleteResponse {
107
102
  const result = McpDeleteResponseSchema.safeParse({
108
- id: (response as unknown as Record<string, unknown>).id,
109
- deleted: (response as unknown as Record<string, unknown>).deleted,
110
- message: (response as unknown as Record<string, unknown>).message,
103
+ id: response.id,
104
+ deleted: response.deleted,
111
105
  });
112
106
 
113
107
  if (!result.success) {
@@ -128,9 +122,8 @@ export function transformMcpUpdateResponse(response: McpUpdateResponseRaw): McpU
128
122
  name: response.name,
129
123
  createdAt: response.created_at,
130
124
  updatedAt: response.updated_at,
131
- status: (response as unknown as Record<string, unknown>).status,
132
125
  toolkits: response.toolkits,
133
- tools: (response as unknown as Record<string, unknown>).tools,
126
+ tools: response.allowed_tools,
134
127
  });
135
128
 
136
129
  if (!result.success) {