@composio/core 0.15.0 → 0.17.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 (33) hide show
  1. package/dist/{CustomTool-zjeDpZ91.d.mts → CustomTool-Uip-fhPw.d.mts} +1 -1
  2. package/dist/{cancellation-BbJ-UQ__.mjs → cancellation-NVtGf3St.mjs} +69 -1
  3. package/dist/{composio-Bf8hnBBq.d.mts → composio-B27X6i6A.d.mts} +253 -247
  4. package/dist/{BaseProvider-BN2-Nktx.d.mts → customTool.types-B2Ava_j5.d.mts} +3020 -126
  5. package/dist/experimental/index.d.mts +2 -2
  6. package/dist/{fileUtils.node-BQ0fWge3.mjs → fileUtils.node-B1Wn848p.mjs} +2 -2
  7. package/dist/index.d.mts +18 -7
  8. package/dist/index.mjs +91 -120
  9. package/dist/models/Files.node.mjs +1 -1
  10. package/dist/{types-CePuCfD-.d.mts → types-DdZJuMm2.d.mts} +2 -2
  11. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  12. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  13. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  14. package/dist/utils/modifiers/FileToolModifier.node.mjs +2 -2
  15. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  16. package/dist/utils/ssrfGuard.node.d.mts +11 -1
  17. package/dist/utils/ssrfGuard.node.mjs +11 -1
  18. package/dist/utils/ssrfGuard.workerd.d.mts +13 -1
  19. package/dist/utils/ssrfGuard.workerd.mjs +13 -1
  20. package/package.json +3 -3
  21. package/src/index.ts +1 -0
  22. package/src/models/RemoteFile.ts +7 -2
  23. package/src/models/ToolRouterSessionFileMount.ts +14 -8
  24. package/src/models/Tools.ts +108 -77
  25. package/src/provider/BaseProvider.ts +53 -1
  26. package/src/provider/OpenAIProvider.ts +43 -15
  27. package/src/types/provider.types.ts +15 -0
  28. package/src/types/tool.types.ts +8 -2
  29. package/src/utils/fileUtils.node.ts +8 -2
  30. package/src/utils/jsonSchema.ts +86 -1
  31. package/src/utils/ssrfGuard.node.ts +11 -0
  32. package/src/utils/ssrfGuard.workerd.ts +16 -0
  33. package/dist/customTool.types-Bhom9a2R.d.mts +0 -2859
@@ -1,4 +1,4 @@
1
- import { gn as Tool, xn as ToolExecuteResponse, yn as ToolExecuteParams } from "../../BaseProvider-BN2-Nktx.mjs";
1
+ import { $i as ToolExecuteResponse, Ji as Tool, Zi as ToolExecuteParams } from "../../customTool.types-B2Ava_j5.mjs";
2
2
  import ComposioClient from "@composio/client";
3
3
  //#region src/utils/modifiers/FileToolModifier.workerd.d.ts
4
4
  declare class FileToolModifier {
@@ -18,5 +18,15 @@ declare const assertSafeFetchTarget: (rawUrl: string) => Promise<void>;
18
18
  * cancelled; non-redirect responses are returned unchanged.
19
19
  */
20
20
  declare const ssrfSafeFetch: (rawUrl: string, init?: RequestInit, maxRedirects?: number) => Promise<Response>;
21
+ /**
22
+ * {@link ssrfSafeFetch} for call sites that must keep working on every runtime.
23
+ *
24
+ * `ssrfSafeFetch` fails closed in edge runtimes, which is right for a URL the
25
+ * caller chose to upload — the alternative is fetching it unvalidated — but not
26
+ * for Tool Router session file transfers, where refusing would remove a working
27
+ * feature from Workers rather than close a hole reachable there. On Node this
28
+ * is the full guard; only the edge build differs.
29
+ */
30
+ declare const ssrfSafeFetchWhereSupported: (rawUrl: string, init?: RequestInit, maxRedirects?: number) => Promise<Response>;
21
31
  //#endregion
22
- export { assertSafeFetchTarget, isBlockedIp, ssrfSafeFetch };
32
+ export { assertSafeFetchTarget, isBlockedIp, ssrfSafeFetch, ssrfSafeFetchWhereSupported };
@@ -148,6 +148,16 @@ const ssrfSafeFetch = async (rawUrl, init = {}, maxRedirects = MAX_REDIRECTS) =>
148
148
  }
149
149
  throw new ComposioBlockedInternalUrlError(`Refusing to fetch: too many redirects (max ${maxRedirects})`, { url: rawUrl });
150
150
  };
151
+ /**
152
+ * {@link ssrfSafeFetch} for call sites that must keep working on every runtime.
153
+ *
154
+ * `ssrfSafeFetch` fails closed in edge runtimes, which is right for a URL the
155
+ * caller chose to upload — the alternative is fetching it unvalidated — but not
156
+ * for Tool Router session file transfers, where refusing would remove a working
157
+ * feature from Workers rather than close a hole reachable there. On Node this
158
+ * is the full guard; only the edge build differs.
159
+ */
160
+ const ssrfSafeFetchWhereSupported = ssrfSafeFetch;
151
161
 
152
162
  //#endregion
153
- export { assertSafeFetchTarget, isBlockedIp, ssrfSafeFetch };
163
+ export { assertSafeFetchTarget, isBlockedIp, ssrfSafeFetch, ssrfSafeFetchWhereSupported };
@@ -5,5 +5,17 @@
5
5
  * falling back to an unguarded fetch.
6
6
  */
7
7
  declare const ssrfSafeFetch: (rawUrl: string) => Promise<Response>;
8
+ /**
9
+ * Unguarded `fetch`, for the call sites that must keep working here.
10
+ *
11
+ * Failing closed is the right default for a URL the caller chose to upload, but
12
+ * applying it to Tool Router session file transfers would take a working
13
+ * feature away from Workers instead of closing a hole reachable there. The
14
+ * guard exists to stop a URL from reaching private address space the SDK's host
15
+ * can see; an edge worker has no such vantage point — it cannot resolve DNS to
16
+ * check, and its `fetch` does not originate inside the caller's network. The
17
+ * Node build applies the full guard.
18
+ */
19
+ declare const ssrfSafeFetchWhereSupported: (rawUrl: string, init?: RequestInit) => Promise<Response>;
8
20
  //#endregion
9
- export { ssrfSafeFetch };
21
+ export { ssrfSafeFetch, ssrfSafeFetchWhereSupported };
@@ -12,6 +12,18 @@ const ssrfSafeFetch = async (rawUrl) => {
12
12
  possibleFixes: ["Fetch the public URL yourself and pass a File or ArrayBuffer instead", "Run the URL upload in a Node.js or Bun runtime"]
13
13
  });
14
14
  };
15
+ /**
16
+ * Unguarded `fetch`, for the call sites that must keep working here.
17
+ *
18
+ * Failing closed is the right default for a URL the caller chose to upload, but
19
+ * applying it to Tool Router session file transfers would take a working
20
+ * feature away from Workers instead of closing a hole reachable there. The
21
+ * guard exists to stop a URL from reaching private address space the SDK's host
22
+ * can see; an edge worker has no such vantage point — it cannot resolve DNS to
23
+ * check, and its `fetch` does not originate inside the caller's network. The
24
+ * Node build applies the full guard.
25
+ */
26
+ const ssrfSafeFetchWhereSupported = async (rawUrl, init = {}) => fetch(rawUrl, init);
15
27
 
16
28
  //#endregion
17
- export { ssrfSafeFetch };
29
+ export { ssrfSafeFetch, ssrfSafeFetchWhereSupported };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@composio/core",
3
3
  "type": "module",
4
- "version": "0.15.0",
4
+ "version": "0.17.0",
5
5
  "description": "",
6
6
  "main": "dist/index.mjs",
7
7
  "publishConfig": {
@@ -92,7 +92,7 @@
92
92
  "@type-challenges/utils": "^0.1.1",
93
93
  "@types/semver": "^7.8.0",
94
94
  "tsdown": "^0.22.14",
95
- "tsx": "^4.23.5",
95
+ "tsx": "^4.23.12",
96
96
  "typedoc": "^0.28.20",
97
97
  "typescript": "npm:@typescript/typescript6@^6.0.2",
98
98
  "vitest": "^4.1.10",
@@ -110,7 +110,7 @@
110
110
  "pusher-js": "^8.6.0",
111
111
  "semver": "^7.8.5",
112
112
  "zod-to-json-schema": "^3.25.2",
113
- "@composio/json-schema-to-zod": "0.2.2"
113
+ "@composio/json-schema-to-zod": "0.3.0"
114
114
  },
115
115
  "gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064",
116
116
  "repository": {
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ export type { BaseComposioProvider } from './provider/BaseProvider';
7
7
  export {
8
8
  dereferenceJsonSchema,
9
9
  deduplicateJsonSchemaRequiredArrays,
10
+ ensureObjectTypeOnProperties,
10
11
  jsonSchemaToZodSchema,
11
12
  removeNonRequiredProperties,
12
13
  } from './utils/jsonSchema';
@@ -1,4 +1,5 @@
1
1
  import { platform } from '#platform';
2
+ import { ssrfSafeFetchWhereSupported } from '#ssrf_guard';
2
3
  import { COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME } from '../utils/constants';
3
4
 
4
5
  function getParentDir(filePath: string): string {
@@ -82,7 +83,10 @@ export class RemoteFile {
82
83
  * @throws RemoteFileDownloadError if the fetch fails
83
84
  */
84
85
  async buffer(): Promise<Uint8Array> {
85
- const response = await fetch(this.downloadUrl);
86
+ // SSRF guard: `downloadUrl` is set from an API response, so it is untrusted
87
+ // input like every other response field, and its bytes are handed straight
88
+ // back to the caller. See ssrfGuard.node.ts.
89
+ const response = await ssrfSafeFetchWhereSupported(this.downloadUrl);
86
90
  if (!response.ok) {
87
91
  throw new RemoteFileDownloadError(
88
92
  `Failed to download file: ${response.status} ${response.statusText}`,
@@ -116,7 +120,8 @@ export class RemoteFile {
116
120
  * @throws RemoteFileDownloadError if the fetch fails
117
121
  */
118
122
  async blob(): Promise<Blob> {
119
- const response = await fetch(this.downloadUrl);
123
+ // SSRF guard: see `buffer()`.
124
+ const response = await ssrfSafeFetchWhereSupported(this.downloadUrl);
120
125
  if (!response.ok) {
121
126
  throw new RemoteFileDownloadError(
122
127
  `Failed to download file: ${response.status} ${response.statusText}`,
@@ -18,7 +18,7 @@ import {
18
18
  import { RemoteFile } from './RemoteFile';
19
19
  import { ValidationError } from '../errors';
20
20
  import { platform } from '#platform';
21
- import { ssrfSafeFetch } from '#ssrf_guard';
21
+ import { ssrfSafeFetch, ssrfSafeFetchWhereSupported } from '#ssrf_guard';
22
22
  import { getExtensionFromMimeType } from '../utils/mime';
23
23
  import { readResponseBodyWithLimit } from '../utils/readResponseBody';
24
24
  import { getRandomShortId } from '../utils/uuid';
@@ -240,13 +240,19 @@ export class ToolRouterSessionFilesMount {
240
240
  ? (createUploadURLResponse as { body: unknown }).body
241
241
  : createUploadURLResponse;
242
242
 
243
- const uploadResponse = await fetch((uploadURLData as { upload_url: string }).upload_url, {
244
- method: 'PUT',
245
- body: await fileToUpload.arrayBuffer(),
246
- headers: {
247
- 'Content-Type': mimetype,
248
- },
249
- });
243
+ // SSRF guard: `upload_url` comes from the API response, so the target is
244
+ // validated before the file's bytes are sent to it — the same treatment the
245
+ // user-supplied URL above already gets. See ssrfGuard.node.ts.
246
+ const uploadResponse = await ssrfSafeFetchWhereSupported(
247
+ (uploadURLData as { upload_url: string }).upload_url,
248
+ {
249
+ method: 'PUT',
250
+ body: await fileToUpload.arrayBuffer(),
251
+ headers: {
252
+ 'Content-Type': mimetype,
253
+ },
254
+ }
255
+ );
250
256
 
251
257
  if (!uploadResponse.ok) {
252
258
  throw new Error(`Failed to upload file: ${uploadResponse.statusText}`);
@@ -470,14 +470,12 @@ export class Tools<
470
470
  'important' in queryParams.data ? queryParams.data.important : shouldAutoApplyImportant;
471
471
 
472
472
  // check if the query params contains atleast one of the following: tools, toolkits, search, authConfigIds
473
- if (
474
- !(
475
- 'tools' in queryParams.data ||
476
- 'toolkits' in queryParams.data ||
477
- 'search' in queryParams.data ||
478
- 'authConfigIds' in queryParams.data
479
- )
480
- ) {
473
+ if (!(
474
+ 'tools' in queryParams.data ||
475
+ 'toolkits' in queryParams.data ||
476
+ 'search' in queryParams.data ||
477
+ 'authConfigIds' in queryParams.data
478
+ )) {
481
479
  throw new ValidationError(
482
480
  'Invalid tool list parameters, atleast one of the following parameters is required: tools, toolkits, search, authConfigIds'
483
481
  );
@@ -766,33 +764,44 @@ export class Tools<
766
764
  const { signal: _, ...modifiers } = options ?? {};
767
765
 
768
766
  if (typeof arg2 === 'string') {
769
- const tool = await this.getRawComposioToolBySlug(
770
- arg2,
771
- {
772
- modifySchema: options?.modifySchema as TransformToolSchemaModifier,
773
- },
774
- requestOptions
775
- );
776
- return this.wrapToolsForProvider(
777
- userId,
778
- [tool],
779
- modifiers as ExecuteToolModifiers
780
- ) as TToolCollection;
767
+ const rawTool = await this.getRawComposioToolBySlug(arg2, undefined, requestOptions);
768
+ const [tool] = await this.applySchemaModifiers([rawTool], options?.modifySchema);
769
+ return this.wrapToolsForProvider(userId, [tool], modifiers as ExecuteToolModifiers, [
770
+ rawTool,
771
+ ]) as TToolCollection;
781
772
  } else {
782
- const tools = await this.getRawComposioTools(
783
- arg2,
784
- {
785
- modifySchema: options?.modifySchema as TransformToolSchemaModifier,
786
- },
787
- requestOptions
788
- );
773
+ const rawTools = await this.getRawComposioTools(arg2, undefined, requestOptions);
774
+ const tools = await this.applySchemaModifiers(rawTools, options?.modifySchema);
789
775
  return this.wrapToolsForProvider(
790
776
  userId,
791
777
  tools,
792
- modifiers as ExecuteToolModifiers
778
+ modifiers as ExecuteToolModifiers,
779
+ rawTools
793
780
  ) as TToolCollection;
794
781
  }
795
782
  }
783
+
784
+ private async applySchemaModifiers(
785
+ tools: Tool[],
786
+ modifier?: TransformToolSchemaModifier
787
+ ): Promise<Tool[]> {
788
+ if (modifier && typeof modifier !== 'function') {
789
+ throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
790
+ }
791
+ return Promise.all(
792
+ tools.map(tool => {
793
+ const schema = ToolSchema.parse(tool);
794
+ return modifier
795
+ ? modifier({
796
+ toolSlug: tool.slug,
797
+ toolkitSlug: tool.toolkit?.slug ?? 'unknown',
798
+ schema,
799
+ })
800
+ : schema;
801
+ })
802
+ );
803
+ }
804
+
796
805
  /**
797
806
  * @internal
798
807
  * Creates a global execute tool function.
@@ -817,14 +826,16 @@ export class Tools<
817
826
  * @param userId - The user id to get the tools for
818
827
  * @param tools - The tools to wrap
819
828
  * @param modifiers - The modifiers to be applied to the tools
829
+ * @param rawTools - The fetched schemas used during execution
820
830
  * @returns The wrapped tools
821
831
  */
822
832
  wrapToolsForProvider<T extends TProvider>(
823
833
  userId: string,
824
834
  tools: Tool[],
825
- modifiers?: ExecuteToolModifiers
835
+ modifiers?: ExecuteToolModifiers,
836
+ rawTools: Tool[] = tools.map(tool => ToolSchema.parse(tool))
826
837
  ): ReturnType<T['wrapTools']> {
827
- const executeToolFn = this.createExecuteToolFn(userId, modifiers);
838
+ const executeToolFn = this.createExecuteToolFn(userId, modifiers, rawTools);
828
839
  return this.provider.wrapTools(tools, executeToolFn) as ReturnType<T['wrapTools']>;
829
840
  }
830
841
 
@@ -854,21 +865,27 @@ export class Tools<
854
865
  *
855
866
  * @param {string} userId - The user id
856
867
  * @param {ExecuteToolModifiers} modifiers - The modifiers to be applied to the tool
868
+ * @param {Tool[]} tools - The fetched tools available to the provider
857
869
  * @returns {ExecuteToolFn} The execute tool function
858
870
  */
859
- private createExecuteToolFn(userId: string, modifiers?: ExecuteToolModifiers): ExecuteToolFn {
871
+ private createExecuteToolFn(
872
+ userId: string,
873
+ modifiers: ExecuteToolModifiers | undefined,
874
+ tools: Tool[]
875
+ ): ExecuteToolFn {
876
+ const toolBySlug = new Map(tools.map(tool => [tool.slug.toUpperCase(), tool]));
860
877
  const executeToolFn = async (toolSlug: string, input: Record<string, unknown>) => {
861
- return await this.execute(
862
- toolSlug,
863
- {
864
- userId,
865
- arguments: input,
866
- // dangerously skip version check for agentic tool execution via providers
867
- // this can be safe because most agentic flows users fetch latest version and then execute the tool
868
- dangerouslySkipVersionCheck: true,
869
- },
870
- modifiers
871
- );
878
+ const body: ToolExecuteParams = {
879
+ userId,
880
+ arguments: input,
881
+ // dangerously skip version check for agentic tool execution via providers
882
+ // this can be safe because most agentic flows users fetch latest version and then execute the tool
883
+ dangerouslySkipVersionCheck: true,
884
+ };
885
+ const tool = toolBySlug.get(toolSlug.toUpperCase());
886
+ return tool
887
+ ? this.executeWithTool(toolSlug, this.parseToolExecuteParams(body), modifiers, tool)
888
+ : this.execute(toolSlug, body, modifiers);
872
889
  };
873
890
  return executeToolFn;
874
891
  }
@@ -961,6 +978,52 @@ export class Tools<
961
978
  }
962
979
  }
963
980
 
981
+ private async executeWithTool(
982
+ slug: string,
983
+ body: ToolExecuteParams,
984
+ options: (ExecuteToolModifiers & ComposioRequestOptions) | undefined,
985
+ tool: Tool
986
+ ): Promise<ToolExecuteResponse> {
987
+ const requestOptions: ComposioRequestOptions | undefined =
988
+ options?.signal != null ? { signal: options.signal } : undefined;
989
+ const { signal: _, ...modifiers } = options ?? {};
990
+ const toolkitSlug = tool.toolkit?.slug ?? 'unknown';
991
+
992
+ const params = await this.applyBeforeExecuteModifiers(
993
+ tool,
994
+ {
995
+ toolSlug: slug,
996
+ toolkitSlug,
997
+ params: body,
998
+ },
999
+ modifiers as ExecuteToolModifiers,
1000
+ requestOptions
1001
+ );
1002
+
1003
+ let result = await this.executeComposioTool(tool, params, requestOptions);
1004
+
1005
+ result = await this.applyAfterExecuteModifiers(
1006
+ tool,
1007
+ {
1008
+ toolSlug: slug,
1009
+ toolkitSlug,
1010
+ result,
1011
+ },
1012
+ (modifiers as ExecuteToolModifiers).afterExecute,
1013
+ requestOptions
1014
+ );
1015
+
1016
+ return result;
1017
+ }
1018
+
1019
+ private parseToolExecuteParams(body: ToolExecuteParams): ToolExecuteParams {
1020
+ const executeParams = ToolExecuteParamsSchema.safeParse(body);
1021
+ if (!executeParams.success) {
1022
+ throw new ValidationError('Invalid tool execute parameters', { cause: executeParams.error });
1023
+ }
1024
+ return executeParams.data;
1025
+ }
1026
+
964
1027
  /**
965
1028
  * Executes a given tool with the provided parameters.
966
1029
  *
@@ -1046,51 +1109,19 @@ export class Tools<
1046
1109
  body: ToolExecuteParams,
1047
1110
  options?: ExecuteToolModifiers & ComposioRequestOptions
1048
1111
  ): Promise<ToolExecuteResponse> {
1049
- const executeParams = ToolExecuteParamsSchema.safeParse(body);
1050
- if (!executeParams.success) {
1051
- throw new ValidationError('Invalid tool execute parameters', { cause: executeParams.error });
1052
- }
1112
+ const executeParams = this.parseToolExecuteParams(body);
1053
1113
 
1054
1114
  const requestOptions: ComposioRequestOptions | undefined =
1055
1115
  options?.signal != null ? { signal: options.signal } : undefined;
1056
- const { signal: _, ...modifiers } = options ?? {};
1057
1116
 
1058
1117
  const tool = await this.getRawComposioToolBySlug(
1059
1118
  slug,
1060
1119
  {
1061
- version: body.version,
1062
- },
1063
- requestOptions
1064
- );
1065
- const toolkitSlug = tool.toolkit?.slug ?? 'unknown';
1066
-
1067
- // Apply before execute modifiers
1068
- const params = await this.applyBeforeExecuteModifiers(
1069
- tool,
1070
- {
1071
- toolSlug: slug,
1072
- toolkitSlug,
1073
- params: executeParams.data,
1120
+ version: executeParams.version,
1074
1121
  },
1075
- modifiers as ExecuteToolModifiers,
1076
1122
  requestOptions
1077
1123
  );
1078
-
1079
- let result = await this.executeComposioTool(tool, params, requestOptions);
1080
-
1081
- // Apply after execute modifiers
1082
- result = await this.applyAfterExecuteModifiers(
1083
- tool,
1084
- {
1085
- toolSlug: slug,
1086
- toolkitSlug,
1087
- result,
1088
- },
1089
- (modifiers as ExecuteToolModifiers).afterExecute,
1090
- requestOptions
1091
- );
1092
-
1093
- return result;
1124
+ return this.executeWithTool(slug, executeParams, options, tool);
1094
1125
  }
1095
1126
 
1096
1127
  /**
@@ -1,7 +1,12 @@
1
1
  import { ComposioGlobalExecuteToolFnNotSetError } from '../errors/ToolErrors';
2
2
  import { ExecuteToolModifiers } from '../types/modifiers.types';
3
3
  import type { Tool, ToolExecuteParams, ToolExecuteResponse } from '../types/tool.types';
4
- import { ExecuteToolFn, GlobalExecuteToolFn } from '../types/provider.types';
4
+ import {
5
+ ExecuteToolFn,
6
+ ExecuteToolFnOptions,
7
+ GlobalExecuteToolFn,
8
+ ToolCallExecutionTarget,
9
+ } from '../types/provider.types';
5
10
  import { McpUrlResponse, McpServerGetResponse } from '../types/mcp.types';
6
11
 
7
12
  /**
@@ -60,6 +65,53 @@ abstract class BaseProvider<TMcpResponse> {
60
65
  return this._globalExecuteToolFn(toolSlug, body, modifers);
61
66
  }
62
67
 
68
+ /** Reject direct-only configuration when execution is bound to a session. */
69
+ protected assertToolCallExecutionOptions(
70
+ target: ToolCallExecutionTarget,
71
+ options?: ExecuteToolFnOptions,
72
+ modifiers?: ExecuteToolModifiers
73
+ ): void {
74
+ if (typeof target !== 'string' && (options !== undefined || modifiers !== undefined)) {
75
+ throw new TypeError(
76
+ 'Direct execution options and modifiers cannot be used with a Tool Router session'
77
+ );
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Execute normalized provider arguments against either the direct tools API or
83
+ * the Tool Router session that produced the model-visible tools.
84
+ */
85
+ protected async executeToolForTarget(
86
+ target: ToolCallExecutionTarget,
87
+ toolSlug: string,
88
+ arguments_: Record<string, unknown>,
89
+ options?: ExecuteToolFnOptions,
90
+ modifiers?: ExecuteToolModifiers
91
+ ): Promise<ToolExecuteResponse> {
92
+ this.assertToolCallExecutionOptions(target, options, modifiers);
93
+
94
+ if (typeof target === 'string') {
95
+ return this.executeTool(
96
+ toolSlug,
97
+ {
98
+ arguments: arguments_,
99
+ connectedAccountId: options?.connectedAccountId,
100
+ customAuthParams: options?.customAuthParams,
101
+ customConnectionData: options?.customConnectionData,
102
+ userId: target,
103
+ },
104
+ modifiers
105
+ );
106
+ }
107
+
108
+ const result = await target.execute(toolSlug, arguments_);
109
+ return {
110
+ ...result,
111
+ successful: result.error === null,
112
+ };
113
+ }
114
+
63
115
  /**
64
116
  * @public
65
117
  * @deprecated: Will be removed in a future version, once the `experimental.mcp` flag is stabilized. Use `wrapMcpServers` instead.
@@ -10,10 +10,14 @@
10
10
  import { OpenAI } from 'openai';
11
11
  import { Stream } from 'openai/streaming';
12
12
  import { BaseNonAgenticProvider } from './BaseProvider';
13
- import { Tool, ToolExecuteParams } from '../types/tool.types';
13
+ import { Tool } from '../types/tool.types';
14
14
  import logger from '../utils/logger';
15
15
  import { ExecuteToolModifiers } from '../types/modifiers.types';
16
- import { ExecuteToolFnOptions } from '../types/provider.types';
16
+ import {
17
+ ExecuteToolFnOptions,
18
+ ToolCallExecutionTarget,
19
+ ToolCallSession,
20
+ } from '../types/provider.types';
17
21
  import { McpUrlResponse, McpServerGetResponse } from '../types/mcp.types';
18
22
  import { normalizeToolArguments } from '../utils/toolArguments';
19
23
  import { deduplicateJsonSchemaRequiredArrays } from '../utils/jsonSchema';
@@ -153,7 +157,7 @@ export class OpenAIProvider extends BaseNonAgenticProvider<
153
157
  * This method processes a tool call from OpenAI's chat completion API,
154
158
  * executes the corresponding Composio tool, and returns the result.
155
159
  *
156
- * @param {string} userId - The user ID for authentication and tracking
160
+ * @param {string | ToolCallSession} executionTarget - A user ID for direct tools or the session that produced session tools
157
161
  * @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool call from OpenAI
158
162
  * @param {ExecuteToolFnOptions} [options] - Optional execution options
159
163
  * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
@@ -179,22 +183,32 @@ export class OpenAIProvider extends BaseNonAgenticProvider<
179
183
  * console.log(JSON.parse(result));
180
184
  * ```
181
185
  */
186
+ async executeToolCall(
187
+ session: ToolCallSession,
188
+ tool: OpenAI.ChatCompletionMessageFunctionToolCall
189
+ ): Promise<string>;
182
190
  async executeToolCall(
183
191
  userId: string,
184
192
  tool: OpenAI.ChatCompletionMessageFunctionToolCall,
185
193
  options?: ExecuteToolFnOptions,
186
194
  modifiers?: ExecuteToolModifiers
195
+ ): Promise<string>;
196
+ async executeToolCall(
197
+ executionTarget: ToolCallExecutionTarget,
198
+ tool: OpenAI.ChatCompletionMessageFunctionToolCall,
199
+ options?: ExecuteToolFnOptions,
200
+ modifiers?: ExecuteToolModifiers
187
201
  ): Promise<string> {
188
- const payload: ToolExecuteParams = {
189
- // OpenAI always serializes tool arguments as a JSON string; normalize tolerates
190
- // empty / object-shaped payloads too (issue #2406).
191
- arguments: normalizeToolArguments(tool.function.arguments, tool.function.name),
192
- connectedAccountId: options?.connectedAccountId,
193
- customAuthParams: options?.customAuthParams,
194
- customConnectionData: options?.customConnectionData,
195
- userId: userId,
196
- };
197
- const result = await this.executeTool(tool.function.name, payload, modifiers);
202
+ // OpenAI always serializes tool arguments as a JSON string; normalize tolerates
203
+ // empty / object-shaped payloads too (issue #2406).
204
+ const arguments_ = normalizeToolArguments(tool.function.arguments, tool.function.name);
205
+ const result = await this.executeToolForTarget(
206
+ executionTarget,
207
+ tool.function.name,
208
+ arguments_,
209
+ options,
210
+ modifiers
211
+ );
198
212
  return JSON.stringify(result);
199
213
  }
200
214
 
@@ -204,7 +218,7 @@ export class OpenAIProvider extends BaseNonAgenticProvider<
204
218
  * This method processes tool calls from an OpenAI chat completion response,
205
219
  * executes each tool call, and returns the results.
206
220
  *
207
- * @param {string} userId - The user ID for authentication and tracking
221
+ * @param {string | ToolCallSession} executionTarget - A user ID for direct tools or the session that produced session tools
208
222
  * @param {OpenAI.ChatCompletion} chatCompletion - The chat completion response from OpenAI
209
223
  * @param {ExecuteToolFnOptions} [options] - Optional execution options
210
224
  * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
@@ -240,12 +254,23 @@ export class OpenAIProvider extends BaseNonAgenticProvider<
240
254
  * console.log(results); // Array of tool execution results
241
255
  * ```
242
256
  */
257
+ async handleToolCalls(
258
+ session: ToolCallSession,
259
+ chatCompletion: OpenAI.ChatCompletion
260
+ ): Promise<OpenAI.ChatCompletionToolMessageParam[]>;
243
261
  async handleToolCalls(
244
262
  userId: string,
245
263
  chatCompletion: OpenAI.ChatCompletion,
246
264
  options?: ExecuteToolFnOptions,
247
265
  modifiers?: ExecuteToolModifiers
266
+ ): Promise<OpenAI.ChatCompletionToolMessageParam[]>;
267
+ async handleToolCalls(
268
+ executionTarget: ToolCallExecutionTarget,
269
+ chatCompletion: OpenAI.ChatCompletion,
270
+ options?: ExecuteToolFnOptions,
271
+ modifiers?: ExecuteToolModifiers
248
272
  ): Promise<OpenAI.ChatCompletionToolMessageParam[]> {
273
+ this.assertToolCallExecutionOptions(executionTarget, options, modifiers);
249
274
  const outputs: OpenAI.ChatCompletionToolMessageParam[] = [];
250
275
  // Only the first choice is actionable: its tool results feed back into a
251
276
  // single assistant turn. With n > 1, iterating every choice would run each
@@ -259,7 +284,10 @@ export class OpenAIProvider extends BaseNonAgenticProvider<
259
284
  if (toolCall.type !== 'function') {
260
285
  continue;
261
286
  }
262
- const toolResult = await this.executeToolCall(userId, toolCall, options, modifiers);
287
+ const toolResult =
288
+ typeof executionTarget === 'string'
289
+ ? await this.executeToolCall(executionTarget, toolCall, options, modifiers)
290
+ : await this.executeToolCall(executionTarget, toolCall);
263
291
  outputs.push({
264
292
  role: 'tool',
265
293
  tool_call_id: toolCall.id,
@@ -8,6 +8,7 @@ import {
8
8
  ToolListParams,
9
9
  } from './tool.types';
10
10
  import { CustomConnectionData } from './connectedAccountAuthStates.types';
11
+ import type { ToolRouterSessionExecuteResponse } from './toolRouter.types';
11
12
 
12
13
  /**
13
14
  * Base provider implementation, which needs to be implemented by the extended class.
@@ -25,6 +26,20 @@ export type ExecuteToolFnOptions = {
25
26
  customConnectionData?: CustomConnectionData;
26
27
  };
27
28
 
29
+ /**
30
+ * Minimal public contract required to execute model tool calls through a Tool Router session.
31
+ * {@link ToolRouterSession} satisfies this interface.
32
+ */
33
+ export interface ToolCallSession {
34
+ execute(
35
+ toolSlug: string,
36
+ arguments_?: Record<string, unknown>
37
+ ): Promise<ToolRouterSessionExecuteResponse>;
38
+ }
39
+
40
+ /** Direct user execution or execution bound to a Tool Router session. */
41
+ export type ToolCallExecutionTarget = string | ToolCallSession;
42
+
28
43
  /**
29
44
  * This type is used to infer the wrapped tool type from the provider.
30
45
  * It checks if the provider has a method `_wrapTool` and infers the return type.