@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
@@ -1,5 +1,5 @@
1
- import { dr as BaseComposioProvider } from "./customTool.types-Bi6-keZC.mjs";
2
- import { n as ComposioConfig } from "./composio-B8AENilE.mjs";
1
+ import { Tr as BaseComposioProvider } from "./customTool.types-gX421uPT.mjs";
2
+ import { n as ComposioConfig } from "./composio-BUa10iB3.mjs";
3
3
  //#region src/utils/config-defaults/types.d.ts
4
4
  /**
5
5
  * Configuration defaults for Composio.
@@ -1,4 +1,4 @@
1
- import { t as ConfigDefaults } from "../../types-BGDMkEUl.mjs";
1
+ import { t as ConfigDefaults } from "../../types-DXxfzBX3.mjs";
2
2
  //#region src/utils/config-defaults/ConfigDefaults.node.d.ts
3
3
  export declare const CONFIG_DEFAULTS: ConfigDefaults;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { t as ConfigDefaults } from "../../types-BGDMkEUl.mjs";
1
+ import { t as ConfigDefaults } from "../../types-DXxfzBX3.mjs";
2
2
  //#region src/utils/config-defaults/ConfigDefaults.workerd.d.ts
3
3
  export declare const CONFIG_DEFAULTS: ConfigDefaults;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { Aa as ToolExecuteParams, Da as Tool, Ma as ToolExecuteResponse } from "../../customTool.types-Bi6-keZC.mjs";
1
+ import { Ka as ToolExecuteResponse, Va as Tool, Wa as ToolExecuteParams } from "../../customTool.types-gX421uPT.mjs";
2
2
  import ComposioClient from "@composio/client";
3
3
  //#region src/utils/modifiers/FileToolModifier.node.d.ts
4
4
  export declare class FileToolModifier {
@@ -2,7 +2,7 @@ import { i as logger } from "../../SsrfErrors-DiQldIdC.mjs";
2
2
  import { _ as ComposioRequestCancelledError } from "../../errors-Cly0vXFh.mjs";
3
3
  import { a as ComposioSensitiveFilePathBlockedError, i as ComposioFileUploadPathNotAllowedError, n as ComposioFileUploadAbortedError, r as ComposioFileUploadError, t as ComposioFileNotFoundError } from "../../FileModifierErrors-CdGSABoq.mjs";
4
4
  import { a as isEmptyFileValue, c as transformProperties, i as getSchemaVariants, l as walkFileUploadableLeaves, o as isPlainObject, r as findSchemaVariantWithFileProperty, t as DELETE_VALUE } from "../../FileToolModifier.utils.neutral-DWFpnsj2.mjs";
5
- import { r as dereferenceJsonSchema, t as withCancellation } from "../../cancellation-D-tMPk48.mjs";
5
+ import { r as dereferenceJsonSchema, t as withCancellation } from "../../cancellation-ZoRh6EJQ.mjs";
6
6
  import { n as getFileDataAfterUploadingToS3, r as isHttpUrl, t as downloadFileFromS3 } from "../../fileUtils.node-DNLhLg0W.mjs";
7
7
 
8
8
  //#region src/utils/modifiers/FileToolModifier.node.ts
@@ -1,4 +1,4 @@
1
- import { Aa as ToolExecuteParams, Da as Tool, Ma as ToolExecuteResponse } from "../../customTool.types-Bi6-keZC.mjs";
1
+ import { Ka as ToolExecuteResponse, Va as Tool, Wa as ToolExecuteParams } from "../../customTool.types-gX421uPT.mjs";
2
2
  import ComposioClient from "@composio/client";
3
3
  //#region src/utils/modifiers/FileToolModifier.workerd.d.ts
4
4
  export declare class FileToolModifier {
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "engines": {
5
5
  "node": ">=22.22.3"
6
6
  },
7
- "version": "0.25.0",
7
+ "version": "0.27.0",
8
8
  "description": "",
9
9
  "main": "dist/index.mjs",
10
10
  "publishConfig": {
@@ -128,7 +128,7 @@
128
128
  "zod": ">=3.25.76 <5"
129
129
  },
130
130
  "dependencies": {
131
- "@composio/client": "2.0.0-rc.17",
131
+ "@composio/client": "2.0.0-rc.19",
132
132
  "@types/json-schema": "^7.0.15",
133
133
  "is-fs-case-sensitive": "^2.0.0",
134
134
  "openai": "^7.32.0",
@@ -137,7 +137,7 @@
137
137
  "semver": "^7.8.5",
138
138
  "undici": "^7.30.0",
139
139
  "zod-to-json-schema": "^3.25.2",
140
- "@composio/json-schema-to-zod": "0.3.4"
140
+ "@composio/json-schema-to-zod": "0.4.0"
141
141
  },
142
142
  "gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064",
143
143
  "repository": {
package/src/composio.ts CHANGED
@@ -1,6 +1,7 @@
1
+ import { getEnvVariable } from './utils/env';
1
2
  import type { BaseComposioProvider } from './provider/BaseProvider';
2
- import ComposioClient from '@composio/client';
3
- import type { Logger as ClientLogger, LogLevel as ClientLogLevel } from '@composio/client';
3
+ import ComposioClient, { createFetchTransport } from '@composio/client';
4
+ import type { LogLevel as ClientLogLevel } from '@composio/client';
4
5
  import { Tools } from './models/Tools';
5
6
  import { Toolkits } from './models/Toolkits';
6
7
  import { Triggers } from './models/Triggers';
@@ -14,13 +15,13 @@ import { SessionConfigs } from './models/SessionConfigs';
14
15
  import { Keyring } from './models/Keyring';
15
16
  import { telemetry } from './telemetry/Telemetry';
16
17
  import {
17
- getScopeHeaders,
18
18
  getSDKConfig,
19
19
  getToolkitVersionsFromEnv,
20
- getUserApiKeyHeader,
20
+ resolveSDKCredentials,
21
21
  resolveSDKScope,
22
- resolveUserApiKey,
23
- USER_API_KEY_HEADER,
22
+ toClientAuth,
23
+ toClientScope,
24
+ withoutSDKOwnedHeaders,
24
25
  } from './utils/sdk';
25
26
  import logger from './utils/logger';
26
27
  import type { ComposioLogger, LogLevel } from './utils/logger';
@@ -37,6 +38,7 @@ import { ToolRouter } from './models/ToolRouter';
37
38
  import { Sessions } from './models/Sessions';
38
39
  import { CONFIG_DEFAULTS } from './utils/config-defaults';
39
40
  import { expandHomeAndResolve, expandHomeAndResolveMany } from './utils/fileDirs';
41
+ import { createToolkitDeprecationFetch } from './utils/toolkitDeprecation';
40
42
  export type ComposioConfig<
41
43
  TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider,
42
44
  > = {
@@ -49,8 +51,10 @@ export type ComposioConfig<
49
51
  * project key; the SDK throws instead of sending it.
50
52
  * - `null`: disables project-key authentication entirely, including both fallbacks. The SDK
51
53
  * then requires another credential (`userApiKey`, `orgApiKey`, or an `x-user-api-key`
52
- * entry in `defaultHeaders`) and sends no `x-api-key`; an `x-api-key` entry in
53
- * `defaultHeaders` is rejected, also on `createSession()` clones.
54
+ * or `x-org-api-key` entry in `defaultHeaders`) and sends no `x-api-key`; an `x-api-key` entry in
55
+ * `defaultHeaders` is rejected, also on `createSession()` clones. The user API key
56
+ * then authenticates every request; the organization API key does when it is the
57
+ * only credential held.
54
58
  *
55
59
  * @example 'ak_1234567890'
56
60
  */
@@ -71,7 +75,8 @@ export type ComposioConfig<
71
75
  * Sent as `x-org-api-key` only on operations whose security scheme accepts
72
76
  * it, never alongside the project key. Falls back to
73
77
  * `process.env['COMPOSIO_ORG_API_KEY']`; `null` disables that fallback.
74
- * Combine with `apiKey: null` to authenticate with the organization key alone.
78
+ * Combine with `apiKey: null` (and no user API key) to authenticate every
79
+ * request with the organization key alone.
75
80
  * @example 'oak_1234567890'
76
81
  */
77
82
  orgApiKey?: string | null;
@@ -168,10 +173,14 @@ export type ComposioConfig<
168
173
  /**
169
174
  * Default headers attached to every request made through this instance.
170
175
  *
171
- * `x-user-api-key` is the one header the SDK treats as a credential: together
172
- * with `apiKey: null` it authenticates requests with a Composio user API key
173
- * instead of a project key. The project key is only ever set from `apiKey`:
174
- * an `x-api-key` entry is rejected when `apiKey` is `null`.
176
+ * Credential and scope headers are not forwarded as headers: the SDK folds
177
+ * them into its own options, which `getConfig()` then reports.
178
+ * A non-empty `x-user-api-key` (or `x-org-api-key`) entry becomes the
179
+ * credential every request carries, in place of the configured keys; together
180
+ * with `apiKey: null` it authenticates with that key instead of a project key.
181
+ * An `x-api-key` entry replaces the project key, and is rejected when `apiKey`
182
+ * is `null`. At most one of the three may be set. `x-org-id` / `x-project-id`
183
+ * entries supply `orgId` / `projectId`.
175
184
  *
176
185
  * The SDK reports itself through the API client's identity headers
177
186
  * (`x-client-provenance`, `x-client-version`, `x-client-library`,
@@ -291,11 +300,11 @@ const toClientLogLevel = (level: LogLevel): ClientLogLevel => {
291
300
  * at call time so a later `logger.configure()` is honoured. The client's
292
301
  * `info` records (per-request lifecycle) are forwarded as SDK `debug`.
293
302
  */
294
- const clientLoggerAdapter: ClientLogger = {
295
- error: (...args) => logger.error(...args),
296
- warn: (...args) => logger.warn(...args),
297
- info: (...args) => logger.debug(...args),
298
- debug: (...args) => logger.debug(...args),
303
+ const clientLogForwarder: Pick<Console, 'debug' | 'info' | 'warn' | 'error'> = {
304
+ error: (...args: unknown[]) => logger.error(...args),
305
+ warn: (...args: unknown[]) => logger.warn(...args),
306
+ info: (...args: unknown[]) => logger.debug(...args),
307
+ debug: (...args: unknown[]) => logger.debug(...args),
299
308
  };
300
309
 
301
310
  /**
@@ -472,16 +481,20 @@ export class Composio<
472
481
  }
473
482
  );
474
483
 
475
- // The API client sends its user key only on operations whose security
476
- // scheme names it, which excludes sessions. With the project key disabled
477
- // the resolved user key is placed as the `x-user-api-key` default header
478
- // instead, so every request carries exactly that credential and clones,
479
- // the MCP export, and trigger subscriptions read the same header.
480
- const userApiKey = apiKeyParsed === null ? resolveUserApiKey(config?.userApiKey) : undefined;
481
- const defaultHeadersInput =
482
- userApiKey !== undefined && !getUserApiKeyHeader(config?.defaultHeaders)
483
- ? { ...config?.defaultHeaders, [USER_API_KEY_HEADER]: userApiKey }
484
- : config?.defaultHeaders;
484
+ // The SDK owns the credential: it resolves the keys (with their
485
+ // environment fallbacks) and folds a credential default header into them,
486
+ // so the API client receives one `auth` and never a credential header.
487
+ // The resolved keys are stored on the config, so clones, the MCP export
488
+ // and trigger subscriptions read the same values.
489
+ const credentials = resolveSDKCredentials({
490
+ apiKey: apiKeyParsed,
491
+ userApiKey: config?.userApiKey,
492
+ orgApiKey: config?.orgApiKey,
493
+ defaultHeaders: config?.defaultHeaders,
494
+ });
495
+ // Credential and scope entries travel as `auth` and `scope`; the client
496
+ // refuses them in `defaultHeaders`.
497
+ const defaultHeaders = withoutSDKOwnedHeaders(config?.defaultHeaders);
485
498
 
486
499
  if (config?.logger !== undefined || config?.logLevel !== undefined) {
487
500
  logger.configure({ level: config.logLevel, sink: config.logger });
@@ -503,8 +516,10 @@ export class Composio<
503
516
  this.config = {
504
517
  ...config,
505
518
  baseURL: baseURLParsed,
506
- apiKey: apiKeyParsed,
507
- defaultHeaders: defaultHeadersInput,
519
+ apiKey: credentials.apiKey,
520
+ userApiKey: credentials.userApiKey,
521
+ orgApiKey: credentials.orgApiKey,
522
+ defaultHeaders,
508
523
  toolkitVersions: getToolkitVersionsFromEnv(config?.toolkitVersions),
509
524
  allowTracking: config?.allowTracking ?? CONFIG_DEFAULTS.allowTracking,
510
525
  dangerouslyAllowAutoUploadDownloadFiles:
@@ -519,32 +534,33 @@ export class Composio<
519
534
  projectId: scope.projectId,
520
535
  };
521
536
 
522
- // The resolved scope is the single source of the x-org-id / x-project-id
523
- // headers: it travels via `this.config` to clones and to the MCP export.
524
- const defaultHeaders = { ...this.config.defaultHeaders, ...getScopeHeaders(scope) };
525
-
526
537
  /**
527
538
  * Initialize the Composio SDK client.
528
539
  * The client is used to make API calls to the Composio API. It sends the
529
- * SDK's identity headers from `identity`, and refuses them in `defaultHeaders`.
540
+ * credential from `auth`, the resolved org/project scope from `scope`, and
541
+ * the SDK's identity headers from `identity`, and refuses all three in
542
+ * `defaultHeaders`.
530
543
  */
531
544
  this.client = new ComposioClient({
532
- apiKey: apiKeyParsed,
533
- userApiKey: config?.userApiKey,
534
- orgApiKey: config?.orgApiKey,
545
+ auth: toClientAuth(credentials),
546
+ scope: toClientScope(scope),
535
547
  baseURL: baseURLParsed,
536
- defaultHeaders: defaultHeaders,
548
+ // The client stopped reading the process environment in rc.18; this
549
+ // opt-in for a plain-HTTP development origin is the one setting of its
550
+ // own that core forwards.
551
+ ...(getEnvVariable('COMPOSIO_ALLOW_INSECURE_HTTP') === '1'
552
+ ? { allowInsecureHTTP: true }
553
+ : {}),
554
+ defaultHeaders,
537
555
  identity: getClientIdentity(this.provider),
538
- logger: clientLoggerAdapter,
556
+ logger: clientLogForwarder,
539
557
  logLevel: toClientLogLevel(logger.getLevel()),
558
+ // Warns once per deprecated toolkit version reported through the
559
+ // `Composio-Deprecated-Toolkits` response header. `createSession()`
560
+ // clones go through this same constructor and inherit it.
561
+ transport: createFetchTransport({ fetch: createToolkitDeprecationFetch() }),
540
562
  });
541
563
 
542
- // Store the resolved values, as with `apiKey`, so `getConfig()` and the
543
- // `createSession()` clone carry whatever the client resolved from env
544
- // rather than re-reading the environment later.
545
- this.config.userApiKey = this.client.userApiKey;
546
- this.config.orgApiKey = this.client.orgApiKey;
547
-
548
564
  this.tools = new Tools(this.client, this.config);
549
565
  this.mcp = new MCP(this.client);
550
566
  this.toolkits = new Toolkits(this.client);
@@ -579,7 +595,7 @@ export class Composio<
579
595
  */
580
596
  if (this.config.allowTracking) {
581
597
  telemetry.setup({
582
- apiKey: apiKeyParsed ?? '',
598
+ apiKey: credentials.apiKey ?? '',
583
599
  baseUrl: baseURLParsed ?? '',
584
600
  isAgentic: this.provider?._isAgentic || false,
585
601
  version: version,
@@ -669,18 +685,13 @@ export class Composio<
669
685
  * ```
670
686
  */
671
687
  createSession(options?: { headers?: ComposioRequestHeaders }): Composio<TProvider> {
672
- // The clone inherits the resolved credentials: the project, user, and
673
- // organization keys travel via `this.config`; a user API key placed in the
674
- // default headers travels via its header unless the caller overrides it.
675
- const userApiKeyHeader = getUserApiKeyHeader(options?.headers)
676
- ? undefined
677
- : getUserApiKeyHeader(this.config.defaultHeaders);
678
- const sessionHeaders = userApiKeyHeader
679
- ? { [userApiKeyHeader.name]: userApiKeyHeader.value, ...options?.headers }
680
- : options?.headers;
688
+ // The clone inherits the resolved credentials and scope through
689
+ // `this.config`, where a credential or scope default header has already
690
+ // been folded in; `headers` replaces the default headers, and a
691
+ // credential or scope header in it is folded in the same way.
681
692
  return new Composio({
682
693
  ...this.config,
683
- defaultHeaders: sessionHeaders,
694
+ defaultHeaders: options?.headers,
684
695
  });
685
696
  }
686
697
 
@@ -71,6 +71,8 @@ export type MCPServerConfigInput = {
71
71
  apiKey: string | null | undefined;
72
72
  /** The user API key the client resolved (`userApiKey` option or `COMPOSIO_USER_API_KEY`). */
73
73
  userApiKey: string | null | undefined;
74
+ /** The organization API key the client resolved (`orgApiKey` option or `COMPOSIO_ORG_API_KEY`). */
75
+ orgApiKey?: string | null;
74
76
  /** The default headers configured on the SDK instance; only `x-user-api-key` is consulted. */
75
77
  defaultHeaders: ComposioRequestHeaders | undefined;
76
78
  /** Organization nano ID the instance is scoped to, if any. */
@@ -19,6 +19,7 @@ import {
19
19
  ToolRouterSandboxConfig,
20
20
  ToolRouterInstant,
21
21
  ToolRouterProxyExecute,
22
+ ToolRouterHook,
22
23
  } from '../types/toolRouter.types';
23
24
  import { ValidationError } from '../errors';
24
25
  import { z } from 'zod';
@@ -189,11 +190,29 @@ export type SessionPatchExperimentalBody = WithNull<
189
190
  'permissions' | 'link_url_overwrite' | 'fast_mode' | 'submit_feedback'
190
191
  >;
191
192
 
193
+ /** A hook as the API takes it, in snake_case. The generated client does not type `hooks` yet. */
194
+ export type SessionHookBody = {
195
+ type: 'before_execute' | 'after_execute';
196
+ id: string;
197
+ name?: string;
198
+ applies_to: 'all' | { toolkits: string[] };
199
+ handler:
200
+ | { type: 'condition_check'; condition: string; action: 'block' }
201
+ | { type: 'prompt_injection_check'; action: 'block' };
202
+ };
203
+
204
+ /** Request body of `sessions.create()`: the generated `SessionCreateParams` plus `hooks`. */
205
+ export type SessionCreateBody = SessionCreateParams & { hooks?: SessionHookBody[] };
206
+
207
+ /** `hooks` as sent on create and update: `appliesTo` becomes `applies_to`. */
208
+ export const transformToolRouterHooksParams = (hooks: ToolRouterHook[]): SessionHookBody[] =>
209
+ hooks.map(({ appliesTo, ...hook }) => ({ ...hook, applies_to: appliesTo }));
210
+
192
211
  /**
193
212
  * Request body of `session.update()`. Extends the generated `SessionPatchParams`
194
- * with the nullable policy blocks (`null` removes the stored override) and the
195
- * `expected_config_version` root precondition, none of which the generated
196
- * client types yet.
213
+ * with the nullable policy blocks (`null` removes the stored override), `hooks`
214
+ * and the `expected_config_version` root precondition, none of which the
215
+ * generated client types yet.
197
216
  */
198
217
  export type SessionPatchBody = Omit<
199
218
  WithNull<
@@ -205,6 +224,7 @@ export type SessionPatchBody = Omit<
205
224
  manage_connections?: SessionPatchManageConnectionsBody | null;
206
225
  multi_account?: SessionPatchMultiAccountBody | null;
207
226
  experimental?: SessionPatchExperimentalBody | null;
227
+ hooks?: SessionHookBody[] | null;
208
228
  expected_config_version?: number;
209
229
  };
210
230
 
@@ -419,6 +439,9 @@ export const transformToolRouterUpdateParams = (
419
439
  ? null
420
440
  : transformToolRouterProxyExecuteParams(config.proxyExecute);
421
441
  }
442
+ if (config.hooks !== undefined) {
443
+ params.hooks = config.hooks === null ? null : transformToolRouterHooksParams(config.hooks);
444
+ }
422
445
  if (config.preload !== undefined) {
423
446
  params.preload = config.preload;
424
447
  }
@@ -6,6 +6,7 @@
6
6
  * @module ConnectedAccounts
7
7
  */
8
8
  import ComposioClient, { BadRequestError, ConflictError } from '@composio/client';
9
+ import type { APIPromise } from '@composio/client';
9
10
  import {
10
11
  ConnectedAccountCreateResponse,
11
12
  ConnectedAccountDeleteResponse,
@@ -126,11 +127,7 @@ export class ConnectedAccounts {
126
127
  cursor: parsedQuery.data.cursor?.toString(),
127
128
  limit: parsedQuery.data.limit,
128
129
  order_by: parsedQuery.data.orderBy,
129
- // Cast widens to match the Stainless-generated client params, which
130
- // lag behind the live API enum. Apollo accepts the union value at
131
- // runtime (`z.nativeEnum(ConnectionStatusEnum)` on the query param);
132
- // remove the cast once `@composio/client` is regenerated.
133
- statuses: parsedQuery.data.statuses as ConnectedAccountListParamsRaw['statuses'],
130
+ statuses: parsedQuery.data.statuses,
134
131
  toolkit_slugs: parsedQuery.data.toolkitSlugs,
135
132
  user_ids: parsedQuery.data.userIds,
136
133
  ...(parsedQuery.data.accountType !== undefined && {
@@ -271,18 +268,12 @@ export class ConnectedAccounts {
271
268
  // caller needs to migrate. Custom auth configs and non-OAuth schemes
272
269
  // never see the header, eliminating the false-positive warning that
273
270
  // an `auth_scheme`-only check produced for `link()`-unaffected callers.
274
- const apiCall = this.client.connectedAccounts.create(createParams, requestOptions);
275
- if (typeof (apiCall as { withResponse?: unknown }).withResponse === 'function') {
271
+ const apiCall: APIPromise<ConnectedAccountCreateResponse> =
272
+ this.client.connectedAccounts.create(createParams, requestOptions);
273
+ // Checked at runtime: test mocks may return a plain Promise.
274
+ if (typeof apiCall.withResponse === 'function') {
276
275
  const resolved = await withCancellation(
277
- () =>
278
- (
279
- apiCall as unknown as {
280
- withResponse: () => Promise<{
281
- data: ConnectedAccountCreateResponse;
282
- response: Response;
283
- }>;
284
- }
285
- ).withResponse(),
276
+ () => apiCall.withResponse(),
286
277
  requestOptions?.signal
287
278
  );
288
279
  response = resolved.data;
@@ -24,8 +24,8 @@ import {
24
24
  executeCustomTool,
25
25
  } from './customToolExecution';
26
26
  import {
27
- assertNotInputRequired,
28
27
  transformExecuteResponse,
28
+ transformProxyExecuteResponse,
29
29
  } from '../utils/transformers/toolRouterResponseTransform';
30
30
  import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
31
31
  import { inlineCustomToolsExperimental } from './inlineCustomToolsPayload';
@@ -144,24 +144,9 @@ export class SessionContextImpl implements SessionContext {
144
144
  requestOptions?.signal
145
145
  );
146
146
 
147
- assertNotInputRequired(
147
+ return transformProxyExecuteResponse(
148
148
  response,
149
149
  `${validated.data.method} proxy call for toolkit ${validated.data.toolkit}`
150
150
  );
151
- return {
152
- status: response.status,
153
- data: response.data,
154
- headers: response.headers,
155
- ...(response.binary_data
156
- ? {
157
- binaryData: {
158
- contentType: response.binary_data.content_type,
159
- size: response.binary_data.size,
160
- url: response.binary_data.url,
161
- expiresAt: response.binary_data.expires_at,
162
- },
163
- }
164
- : {}),
165
- };
166
151
  }
167
152
  }
@@ -52,6 +52,8 @@ import {
52
52
  transformToolRouterMultiAccountParams,
53
53
  transformToolRouterInstantParams,
54
54
  transformToolRouterProxyExecuteParams,
55
+ transformToolRouterHooksParams,
56
+ type SessionCreateBody,
55
57
  resolveToolRouterSandboxConfig,
56
58
  } from '../lib/toolRouterParams';
57
59
  import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
@@ -139,7 +141,8 @@ export class ToolRouter<
139
141
  /**
140
142
  * Derives the MCP config for a session from the auth context the session
141
143
  * request was made with: the project key when one is configured, otherwise
142
- * the resolved user API key, plus the org/project scope when configured.
144
+ * the resolved user API key, otherwise the organization API key, plus the
145
+ * org/project scope when configured.
143
146
  * Headers are only attached when the MCP URL shares the client's API
144
147
  * origin. Any other destination throws when the caller passed `mcp: true`
145
148
  * and otherwise yields empty headers plus a warning; see
@@ -155,6 +158,7 @@ export class ToolRouter<
155
158
  apiBaseURL: this.client.baseURL,
156
159
  apiKey: this.config?.apiKey,
157
160
  userApiKey: this.config?.userApiKey,
161
+ orgApiKey: this.config?.orgApiKey,
158
162
  defaultHeaders: this.config?.defaultHeaders,
159
163
  orgId: this.config?.orgId,
160
164
  projectId: this.config?.projectId,
@@ -273,7 +277,7 @@ export class ToolRouter<
273
277
  ])
274
278
  );
275
279
 
276
- const payload: SessionCreateParams = {
280
+ const payload: SessionCreateBody = {
277
281
  user_id: userId,
278
282
  auth_configs: routerConfig.authConfigs,
279
283
  connected_accounts: connectedAccountsPayload,
@@ -291,6 +295,9 @@ export class ToolRouter<
291
295
  ...(routerConfig.proxyExecute !== undefined && {
292
296
  proxy_execute: transformToolRouterProxyExecuteParams(routerConfig.proxyExecute),
293
297
  }),
298
+ ...(routerConfig.hooks !== undefined && {
299
+ hooks: transformToolRouterHooksParams(routerConfig.hooks),
300
+ }),
294
301
  preload: routerConfig.preload,
295
302
  ...(isDirectToolsPreset && {
296
303
  search: { enable: false },
@@ -39,9 +39,9 @@ import {
39
39
  type ToolRouterSessionDeleteResponse,
40
40
  } from '../types/toolRouter.types';
41
41
  import {
42
- assertNotInputRequired,
43
42
  transformSearchResponse,
44
43
  transformExecuteResponse,
44
+ transformProxyExecuteResponse,
45
45
  } from '../utils/transformers/toolRouterResponseTransform';
46
46
  import { SessionMetaToolOptions } from '../types/modifiers.types';
47
47
  import { ConnectionRequest } from '../types/connectionRequest.types';
@@ -697,7 +697,7 @@ export class ToolRouterSession<
697
697
  * @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.
698
698
  * @param options.inputResponses - Experimental. The user's answers to an earlier `ComposioToolInputRequiredError`, keyed by the IDs in its `inputRequests`. Repeat the same call with them.
699
699
  * @param options.requestState - Experimental. The `requestState` of that error, sent back unchanged.
700
- * @returns The tool execution result
700
+ * @returns The tool execution result. `resultType: 'blocked'` means a session hook blocked the call; `error` then holds the hook's message
701
701
  * @throws {ComposioToolInputRequiredError} If the tool needs input from the user (for example an approval) before it can run
702
702
  */
703
703
  async execute(
@@ -815,7 +815,7 @@ export class ToolRouterSession<
815
815
  * The backend resolves the connected account from the toolkit within the session.
816
816
  *
817
817
  * @param params - Proxy request parameters (toolkit, endpoint, method, body, headers/query params)
818
- * @returns The proxied API response with status, data, headers
818
+ * @returns The proxied API response with status, data and headers (`resultType: 'completed'`), or `resultType: 'blocked'` with the hook's message when a session hook blocked the request
819
819
  * @throws {ComposioToolInputRequiredError} If the call needs input from the user before it can run
820
820
  */
821
821
  async proxyExecute(
@@ -838,25 +838,10 @@ export class ToolRouterSession<
838
838
  requestOptions?.signal
839
839
  );
840
840
 
841
- assertNotInputRequired(
841
+ return transformProxyExecuteResponse(
842
842
  response,
843
843
  `${validated.data.method} proxy call for toolkit ${validated.data.toolkit}`
844
844
  );
845
- return {
846
- status: response.status,
847
- data: response.data,
848
- headers: response.headers,
849
- ...(response.binary_data
850
- ? {
851
- binaryData: {
852
- contentType: response.binary_data.content_type,
853
- size: response.binary_data.size,
854
- url: response.binary_data.url,
855
- expiresAt: response.binary_data.expires_at,
856
- },
857
- }
858
- : {}),
859
- };
860
845
  }
861
846
 
862
847
  /**
@@ -992,8 +992,7 @@ export class Tools<
992
992
  * @deprecated The `customConnectionData` execute param is deprecated and will be
993
993
  * removed in a future release. Use `customAuthParams` instead.
994
994
  */
995
- custom_connection_data:
996
- body.customConnectionData as ComposioToolExecuteParams['custom_connection_data'],
995
+ custom_connection_data: body.customConnectionData,
997
996
  arguments: body.arguments,
998
997
  user_id: body.userId,
999
998
  version: toolkitVersion,
@@ -1390,8 +1389,6 @@ export class Tools<
1390
1389
  * @deprecated The `customConnectionData` proxy param is deprecated and will be
1391
1390
  * removed in a future release. Use `customAuthParams` instead.
1392
1391
  */
1393
- // oxlint-disable-next-line typescript/ban-ts-comment -- generated client versions disagree about this deprecated field
1394
- // @ts-ignore
1395
1392
  custom_connection_data: toolProxyParams.data.customConnectionData,
1396
1393
  } as ComposioToolProxyParams;
1397
1394
  return withCancellation(
@@ -158,7 +158,12 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
158
158
 
159
159
  constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) {
160
160
  this.client = client;
161
- this.pusherService = new PusherService(client, { defaultHeaders: config?.defaultHeaders });
161
+ this.pusherService = new PusherService(client, {
162
+ apiKey: config?.apiKey,
163
+ userApiKey: config?.userApiKey,
164
+ orgApiKey: config?.orgApiKey,
165
+ defaultHeaders: config?.defaultHeaders,
166
+ });
162
167
  this.toolkitVersions = config?.toolkitVersions ?? CONFIG_DEFAULTS.toolkitVersions;
163
168
  telemetry.instrument(this, 'Triggers');
164
169
  }
@@ -24,10 +24,9 @@ export class InternalService {
24
24
  * @returns {SDKRealtimeCredentialsResponse} The SDK realtime credentials
25
25
  */
26
26
  async getSDKRealtimeCredentials(): Promise<SDKRealtimeCredentialsResponse> {
27
- const response = await this.client.request<ComposioSDKRealtimeCredentialsResponse>({
28
- method: 'get',
29
- path: SDK_REALTIME_CREDENTIALS_ENDPOINT,
30
- });
27
+ const response = await this.client.get<ComposioSDKRealtimeCredentialsResponse>(
28
+ SDK_REALTIME_CREDENTIALS_ENDPOINT
29
+ );
31
30
 
32
31
  const parsedResponse = SDKRealtimeCredentialsResponseSchema.safeParse({
33
32
  pusherKey: response.pusher_key,
@@ -14,6 +14,12 @@ import { resolveCredentialHeaders } from '../../utils/sdk';
14
14
  import type { ComposioRequestHeaders } from '../../types/composio.types';
15
15
 
16
16
  export type PusherServiceOptions = {
17
+ /** The project API key the owning SDK instance resolved, or `null` when disabled. */
18
+ apiKey?: string | null;
19
+ /** The user API key the owning SDK instance resolved, or `null`. */
20
+ userApiKey?: string | null;
21
+ /** The organization API key the owning SDK instance resolved, or `null`. */
22
+ orgApiKey?: string | null;
17
23
  /** Default headers of the owning SDK instance; only `x-user-api-key` is consulted. */
18
24
  defaultHeaders?: ComposioRequestHeaders;
19
25
  };
@@ -57,11 +63,12 @@ export class PusherService {
57
63
  constructor(client: ComposioClient, options: PusherServiceOptions = {}) {
58
64
  this.composioClient = client;
59
65
  this.pusherBaseURL = client.baseURL;
60
- // Channel authorization mirrors the client's effective auth; the
61
- // environment is never consulted here.
66
+ // Channel authorization mirrors the SDK instance's effective auth, from the
67
+ // keys the SDK resolved; the environment is never consulted here.
62
68
  this.authHeaders = resolveCredentialHeaders({
63
- apiKey: client.apiKey,
64
- userApiKey: client.userApiKey,
69
+ apiKey: options.apiKey,
70
+ userApiKey: options.userApiKey,
71
+ orgApiKey: options.orgApiKey,
65
72
  defaultHeaders: options.defaultHeaders,
66
73
  });
67
74
  telemetry.instrument(this, 'PusherService');
@@ -222,7 +222,8 @@ const S2SOauth2ConnectionDataSchema = z.discriminatedUnion('status', [
222
222
  }).catchall(z.unknown()),
223
223
  ]);
224
224
  const CustomS2SOauth2ConnectionDataSchema = BaseSchemeRaw.extend({
225
- access_token: z.string().optional(),
225
+ // Required by the API: custom connection data supplies the token itself.
226
+ access_token: z.string(),
226
227
  id_token: z.string().optional(),
227
228
  token_type: z.string().optional(),
228
229
  refresh_token: z.string().nullish().optional(),