@devries-cameron20 / composio Mirror · read-only / commits / 027004231
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 03:15 UTC

feat: align custom tools API with backend refactor, add toolkits and extension tools

- Signature: `experimental_createTool(slug, opts)` / `experimental_createToolkit(slug, opts)` - Three tool types: standalone (LOCAL_<SLUG>), extension (LOCAL_<TOOLKIT>_<SLUG>), custom toolkit - Move customTools/customToolkits under `experimental` in session config - Backend payload: `extends_toolkit` (not `toolkit`), omitted for standalone - Slug validation: regex, no LOCAL_ prefix, max 60 chars prefixed - Add `serializeCustomToolkits()`, `buildCustomToolsMap(tools, toolkits?)` - Export `experimental_createTool`/`experimental_createToolkit` from `@composio/core` - Add agent example with all 3 tool types (standalone, extension, custom toolkit) - Update tool-router docs with custom tools section, session.execute/search/proxyExecute - Update E2E fixtures and tests to new API Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 17, 2026 at 11:12 UTC 0270042316b3969a7dd07b1b1cedd4d922d7ba29
18 files changed +1279 -596
pnpm-lock.yaml
+65 -89
@@ -703,16 +703,16 @@ importers:
703 version: link:../../packages/providers/llamaindex
704 '@llamaindex/openai':
705 specifier: ^0.4.20
706 - version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@4.3.6)
706 + version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@3.25.76)
707 '@llamaindex/workflow':
708 specifier: ^1.1.24
709 - version: 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
709 + version: 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
710 dotenv:
711 specifier: ^16.4.1
712 version: 16.6.1
713 llamaindex:
714 specifier: ^0.12.0
715 - version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
715 + version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@3.25.76)
716 devDependencies:
717 '@types/bun':
718 specifier: ^1.2.9
@@ -882,8 +882,8 @@ importers:
882 specifier: ^1.1.3
883 version: 1.2.8(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.19.0)(zod@4.3.6)))(ws@8.19.0)
884 '@openai/agents':
885 - specifier: ^0.3.3
886 - version: 0.3.9(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)
885 + specifier: ^0.1.3
886 + version: 0.1.11(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)
887 ai:
888 specifier: 'catalog:'
889 version: 6.0.90(zod@4.3.6)
@@ -893,12 +893,18 @@ importers:
893 langchain:
894 specifier: ^1.1.1
895 version: 1.2.24(@langchain/core@1.1.25(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.19.0)(zod@4.3.6)))(@opentelemetry/api@1.9.0)(openai@6.22.0(ws@8.19.0)(zod@4.3.6))(zod-to-json-schema@3.25.1(zod@4.3.6))
896 + openai:
897 + specifier: ^6.22.0
898 + version: 6.22.0(ws@8.19.0)(zod@4.3.6)
899 ora:
900 specifier: ^9.0.0
901 version: 9.3.0
902 pnpm:
903 specifier: 'catalog:'
904 version: 10.30.0
905 + zod:
906 + specifier: 'catalog:'
907 + version: 4.3.6
908 devDependencies:
909 '@types/bun':
910 specifier: ^1.2.9
@@ -1312,7 +1318,7 @@ importers:
1318 dependencies:
1319 llamaindex:
1320 specifier: ^0.12.0
1315 - version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1321 + version: 0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1322 devDependencies:
1323 '@composio/core':
1324 specifier: workspace:*
@@ -2825,44 +2831,21 @@ packages:
2831 zod:
2832 optional: true
2833
2828 - '@openai/agents-core@0.3.9':
2829 - resolution: {integrity: sha512-6Fr/VkA3lMaTT9EV2+OsmkMX9Yx+/PeWtlmaWNKDRG8D15IWuK13NOC9eFklTsa7otbuwbw/Xmjes+h4Z+CwSQ==}
2830 - peerDependencies:
2831 - zod: ^3.25.40 || ^4.0
2832 - peerDependenciesMeta:
2833 - zod:
2834 - optional: true
2835 -
2834 '@openai/agents-openai@0.1.11':
2835 resolution: {integrity: sha512-TYYbY7o1cNxtOIO4F1a20qkqDT1Iwr9ZEi0MO2sEaeioK8rGB/Ux54iFvsA3IblUYyK+5fD25vr4vXFasvg2Kg==}
2836 peerDependencies:
2837 zod: ^3.25.40
2838
2841 - '@openai/agents-openai@0.3.9':
2842 - resolution: {integrity: sha512-duXUt0xU6K/+c7ae4m8BrJIUzZal6Pzln8V0frnJfNyfYO4SvHMV4qwPRzVDvv/ANj4DQXWI2L1JdPxKJeSHkw==}
2843 - peerDependencies:
2844 - zod: ^3.25.40 || ^4.0
2845 -
2839 '@openai/agents-realtime@0.1.11':
2840 resolution: {integrity: sha512-8jaNuYU1acra28i7bYrZIPubI6s2ziY2ZudqAVK2ad+giopXcrNSiJTuZ2S3z+ESnIejwMiYLfnY2Le8W0SJ7A==}
2841 peerDependencies:
2842 zod: ^3.25.40
2843
2851 - '@openai/agents-realtime@0.3.9':
2852 - resolution: {integrity: sha512-51zHO/zao/LHv70gseU1otTvXyS81tuVaewHlUBiNMXvqSZNkYViiO69hpXMoTYn5c3gCjUrXPxxI+NlHUtaHg==}
2853 - peerDependencies:
2854 - zod: ^3.25.40 || ^4.0
2855 -
2844 '@openai/agents@0.1.11':
2845 resolution: {integrity: sha512-jnaFt54iP71vYDXvpG3EGX2kVRYIU2xBdCT3uFqdXm4KqFAP9JQFNGiKKBEeE5rbXARpqAQpKH+5HfoANndpcQ==}
2846 peerDependencies:
2847 zod: ^3.25.40
2848
2861 - '@openai/agents@0.3.9':
2862 - resolution: {integrity: sha512-YaKnqv0M6bCVvn47pThkFfyHz8xWJ+0Ll9ZnhvwJZ5gyPX0UxHIUeUs9SMG9BSvNuJNJHlc5uvfUDGYAmKJClw==}
2863 - peerDependencies:
2864 - zod: ^3.25.40 || ^4.0
2865 -
2849 '@opentelemetry/api@1.9.0':
2850 resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==}
2851 engines: {node: '>=8.0.0'}
@@ -7478,7 +7461,7 @@ snapshots:
7461 mustache: 4.2.0
7462 p-queue: 6.6.2
7463 uuid: 10.0.0
7481 - zod: 4.3.6
7464 + zod: 3.25.76
7465 transitivePeerDependencies:
7466 - '@opentelemetry/api'
7467 - '@opentelemetry/exporter-trace-otlp-proto'
@@ -7574,26 +7557,43 @@ snapshots:
7557 tree-sitter: 0.22.4
7558 web-tree-sitter: 0.24.7
7559
7577 - '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@4.3.6)':
7560 + '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.19.0)(zod@3.25.76)':
7561 dependencies:
7562 '@llamaindex/core': 0.6.22
7563 '@llamaindex/env': 0.1.30
7581 - openai: 5.23.2(ws@8.19.0)(zod@4.3.6)
7564 + openai: 5.23.2(ws@8.19.0)(zod@3.25.76)
7565 transitivePeerDependencies:
7566 - ws
7567 - zod
7568
7586 - '@llamaindex/workflow-core@1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)':
7569 + '@llamaindex/workflow-core@1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)':
7570 optionalDependencies:
7588 - '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6)
7571 + '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)
7572 hono: 4.11.9
7573 + zod: 3.25.76
7574 +
7575 + '@llamaindex/workflow-core@1.3.3(zod@4.3.6)':
7576 + optionalDependencies:
7577 zod: 4.3.6
7578
7592 - '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)':
7579 + '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)':
7580 dependencies:
7581 '@llamaindex/core': 0.6.22
7582 '@llamaindex/env': 0.1.30
7596 - '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
7583 + '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
7584 + transitivePeerDependencies:
7585 + - '@modelcontextprotocol/sdk'
7586 + - hono
7587 + - next
7588 + - p-retry
7589 + - rxjs
7590 + - zod
7591 +
7592 + '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(zod@4.3.6)':
7593 + dependencies:
7594 + '@llamaindex/core': 0.6.22
7595 + '@llamaindex/env': 0.1.30
7596 + '@llamaindex/workflow-core': 1.3.3(zod@4.3.6)
7597 transitivePeerDependencies:
7598 - '@modelcontextprotocol/sdk'
7599 - hono
@@ -7875,18 +7875,6 @@ snapshots:
7875 - supports-color
7876 - ws
7877
7878 - '@openai/agents-core@0.3.9(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)':
7879 - dependencies:
7880 - debug: 4.4.3(supports-color@10.2.2)
7881 - openai: 6.22.0(ws@8.19.0)(zod@4.3.6)
7882 - optionalDependencies:
7883 - '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6)
7884 - zod: 4.3.6
7885 - transitivePeerDependencies:
7886 - - '@cfworker/json-schema'
7887 - - supports-color
7888 - - ws
7889 -
7878 '@openai/agents-openai@0.1.11(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)':
7879 dependencies:
7880 '@openai/agents-core': 0.1.11(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)
@@ -7898,17 +7886,6 @@ snapshots:
7886 - supports-color
7887 - ws
7888
7901 - '@openai/agents-openai@0.3.9(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)':
7902 - dependencies:
7903 - '@openai/agents-core': 0.3.9(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)
7904 - debug: 4.4.3(supports-color@10.2.2)
7905 - openai: 6.22.0(ws@8.19.0)(zod@4.3.6)
7906 - zod: 4.3.6
7907 - transitivePeerDependencies:
7908 - - '@cfworker/json-schema'
7909 - - supports-color
7910 - - ws
7911 -
7889 '@openai/agents-realtime@0.1.11(@cfworker/json-schema@4.1.1)(zod@4.3.6)':
7890 dependencies:
7891 '@openai/agents-core': 0.1.11(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)
@@ -7922,19 +7899,6 @@ snapshots:
7899 - supports-color
7900 - utf-8-validate
7901
7925 - '@openai/agents-realtime@0.3.9(@cfworker/json-schema@4.1.1)(zod@4.3.6)':
7926 - dependencies:
7927 - '@openai/agents-core': 0.3.9(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)
7928 - '@types/ws': 8.18.1
7929 - debug: 4.4.3(supports-color@10.2.2)
7930 - ws: 8.19.0
7931 - zod: 4.3.6
7932 - transitivePeerDependencies:
7933 - - '@cfworker/json-schema'
7934 - - bufferutil
7935 - - supports-color
7936 - - utf-8-validate
7937 -
7902 '@openai/agents@0.1.11(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)':
7903 dependencies:
7904 '@openai/agents-core': 0.1.11(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)
@@ -7950,21 +7914,6 @@ snapshots:
7914 - utf-8-validate
7915 - ws
7916
7953 - '@openai/agents@0.3.9(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)':
7954 - dependencies:
7955 - '@openai/agents-core': 0.3.9(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)
7956 - '@openai/agents-openai': 0.3.9(@cfworker/json-schema@4.1.1)(ws@8.19.0)(zod@4.3.6)
7957 - '@openai/agents-realtime': 0.3.9(@cfworker/json-schema@4.1.1)(zod@4.3.6)
7958 - debug: 4.4.3(supports-color@10.2.2)
7959 - openai: 6.22.0(ws@8.19.0)(zod@4.3.6)
7960 - zod: 4.3.6
7961 - transitivePeerDependencies:
7962 - - '@cfworker/json-schema'
7963 - - bufferutil
7964 - - supports-color
7965 - - utf-8-validate
7966 - - ws
7967 -
7917 '@opentelemetry/api@1.9.0': {}
7918
7919 '@oxc-project/types@0.103.0': {}
@@ -9974,12 +9923,34 @@ snapshots:
9923 rfdc: 1.4.1
9924 wrap-ansi: 9.0.2
9925
9977 - llamaindex@0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6):
9926 + llamaindex@0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@3.25.76):
9927 dependencies:
9928 '@llamaindex/core': 0.6.22
9929 '@llamaindex/env': 0.1.30
9930 '@llamaindex/node-parser': 2.0.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)
9982 - '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
9931 + '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
9932 + '@types/lodash': 4.17.23
9933 + '@types/node': 24.10.13
9934 + lodash: 4.17.23
9935 + magic-bytes.js: 1.13.0
9936 + transitivePeerDependencies:
9937 + - '@huggingface/transformers'
9938 + - '@modelcontextprotocol/sdk'
9939 + - gpt-tokenizer
9940 + - hono
9941 + - next
9942 + - p-retry
9943 + - rxjs
9944 + - tree-sitter
9945 + - web-tree-sitter
9946 + - zod
9947 +
9948 + llamaindex@0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6):
9949 + dependencies:
9950 + '@llamaindex/core': 0.6.22
9951 + '@llamaindex/env': 0.1.30
9952 + '@llamaindex/node-parser': 2.0.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)
9953 + '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(zod@4.3.6)
9954 '@types/lodash': 4.17.23
9955 '@types/node': 24.10.13
9956 lodash: 4.17.23
@@ -10259,6 +10230,11 @@ snapshots:
10230 is-inside-container: 1.0.0
10231 wsl-utils: 0.1.0
10232
10233 + openai@5.23.2(ws@8.19.0)(zod@3.25.76):
10234 + optionalDependencies:
10235 + ws: 8.19.0
10236 + zod: 3.25.76
10237 +
10238 openai@5.23.2(ws@8.19.0)(zod@4.3.6):
10239 optionalDependencies:
10240 ws: 8.19.0
ts/docs/api/tool-router.md
+131 -1
@@ -245,6 +245,8 @@ const session = await composio.create('user_123', {
245
246 Configure experimental features for the session. These features are not stable and may be modified or removed in future versions.
247
248 +#### Assistive Prompt
249 +
250 ```typescript
251 const session = await composio.create('user_123', {
252 toolkits: ['gmail'],
@@ -263,6 +265,86 @@ if (session.experimental?.assistivePrompt) {
265
266 The `userTimezone` field accepts an IANA timezone identifier (e.g., 'America/New_York', 'Europe/London') which is used to generate a timezone-aware system prompt for optimal tool router usage.
267
268 +#### Custom Tools & Custom Toolkits
269 +
270 +Add user-defined tools that execute locally (in-process) alongside Composio's remote tools. Custom tools are indexed by the backend for search and returned to the LLM with the correct `LOCAL_` prefixed slug.
271 +
272 +There are three ways to define custom tools:
273 +
274 +**1. Standalone tool** — no auth, passed in `customTools`:
275 +
276 +```typescript
277 +import { experimental_createTool } from '@composio/core';
278 +import { z } from 'zod/v3';
279 +
280 +const grep = experimental_createTool('GREP', {
281 + name: 'Grep Search',
282 + description: 'Search for patterns in files',
283 + inputParams: z.object({ pattern: z.string(), path: z.string() }),
284 + execute: async (input) => ({ matches: [] }),
285 +});
286 +```
287 +
288 +Slug format: `LOCAL_GREP`
289 +
290 +**2. Extension tool** — extends a Composio toolkit (inherits auth), passed in `customTools`:
291 +
292 +```typescript
293 +const getImportant = experimental_createTool('GET_IMPORTANT_EMAILS', {
294 + name: 'Get Important Emails',
295 + description: 'Fetch high-priority emails',
296 + extendsToolkit: 'gmail',
297 + inputParams: z.object({ limit: z.number().default(10) }),
298 + execute: async (input, session) => {
299 + const result = await session.execute('GMAIL_SEARCH', { query: 'is:important' });
300 + return { emails: result.data };
301 + },
302 +});
303 +```
304 +
305 +Slug format: `LOCAL_GMAIL_GET_IMPORTANT_EMAILS`
306 +
307 +**3. Custom toolkit** — groups no-auth tools, passed in `customToolkits`:
308 +
309 +```typescript
310 +import { experimental_createToolkit } from '@composio/core';
311 +
312 +const sed = experimental_createTool('SED', {
313 + name: 'Sed Replace',
314 + description: 'Find and replace in files',
315 + inputParams: z.object({ pattern: z.string(), replacement: z.string() }),
316 + execute: async (input) => ({ replaced: 0 }),
317 +});
318 +
319 +const devTools = experimental_createToolkit('DEV_TOOLS', {
320 + name: 'Dev Tools',
321 + description: 'Local dev utilities',
322 + tools: [sed],
323 +});
324 +```
325 +
326 +Slug format: `LOCAL_DEV_TOOLS_SED`
327 +
328 +**Using in a session:**
329 +
330 +```typescript
331 +const session = await composio.create('user_123', {
332 + toolkits: ['gmail'],
333 + experimental: {
334 + customTools: [grep, getImportant],
335 + customToolkits: [devTools],
336 + },
337 +});
338 +
339 +// Execute locally via session.execute()
340 +const result = await session.execute('GREP', { pattern: 'TODO', path: '/src' });
341 +
342 +// Also works with prefixed slug
343 +const result2 = await session.execute('LOCAL_DEV_TOOLS_SED', { pattern: 'foo', replacement: 'bar' });
344 +```
345 +
346 +Custom tools are searched alongside Composio tools. When an LLM calls a custom tool via `COMPOSIO_MULTI_EXECUTE_TOOL`, the SDK intercepts it and executes locally — remote tools in the same batch are sent to the backend in parallel.
347 +
348 ## Session Properties
349
350 A Tool Router session provides the following properties and methods:
@@ -347,6 +429,49 @@ Meta tools allow you to:
429
430 This method is useful when you need direct access to the underlying meta tools without creating a full session object.
431
432 +### `execute()`
433 +
434 +Execute a tool within the session. Custom tools run locally in-process; remote tools are sent to the Composio backend. Accepts both the original slug and the `LOCAL_`-prefixed slug for custom tools.
435 +
436 +```typescript
437 +// Execute a custom tool
438 +const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
439 +console.log(result.data); // { preferences: { ... } }
440 +console.log(result.error); // null on success
441 +console.log(result.logId); // 'local' for custom tools, backend log ID for remote tools
442 +
443 +// Execute a remote Composio tool
444 +const weather = await session.execute('WEATHERMAP_WEATHER', { location: 'Tokyo' });
445 +```
446 +
447 +### `search()`
448 +
449 +Search for tools by semantic use case. Returns relevant tools with schemas and guidance.
450 +
451 +```typescript
452 +const results = await session.search({ query: 'send an email via gmail' });
453 +
454 +for (const result of results.results) {
455 + console.log(result.useCase);
456 + console.log(result.primaryToolSlugs); // e.g. ['GMAIL_SEND_EMAIL']
457 +}
458 +```
459 +
460 +### `proxyExecute()`
461 +
462 +Proxy an API call through Composio's auth layer using the session's connected account. The backend resolves the connected account from the toolkit within the session.
463 +
464 +```typescript
465 +const result = await session.proxyExecute({
466 + toolkit: 'github',
467 + endpoint: 'https://api.github.com/user',
468 + method: 'GET',
469 + parameters: [
470 + { in: 'header', name: 'X-Custom', value: 'value' },
471 + ],
472 +});
473 +```
474 +
475 ### `authorize()`
476
477 Initiate an authorization flow for a toolkit.
@@ -802,6 +927,8 @@ interface ToolRouterCreateSessionConfig {
927 assistivePrompt?: {
928 userTimezone?: string; // IANA timezone identifier for timezone-aware assistive prompts
929 };
930 + customTools?: CustomTool[]; // Standalone or extension tools (from experimental_createTool)
931 + customToolkits?: CustomToolkit[]; // Grouped no-auth tools (from experimental_createToolkit)
932 };
933 }
934 ```
@@ -817,8 +944,11 @@ interface ToolRouterSession {
944 headers?: Record<string, string>; // Authentication headers (includes x-api-key if configured)
945 };
946 tools: (modifiers?: ProviderOptions) => Promise<Tools>;
947 + execute: (toolSlug: string, arguments?: Record<string, unknown>) => Promise<ToolRouterSessionExecuteResponse>;
948 + search: (params: { query: string; toolkits?: string[] }) => Promise<ToolRouterSessionSearchResponse>;
949 + proxyExecute: (params: SessionProxyExecuteParams) => Promise<ToolRouterSessionExecuteResponse>;
950 authorize: (toolkit: string, options?: { callbackUrl?: string }) => Promise<ConnectionRequest>;
821 - toolkits: (options?: {
951 + toolkits: (options?: {
952 toolkits?: string[]; // Filter by specific toolkit slugs
953 nextCursor?: string; // Pagination cursor
954 limit?: number; // Number of items per page
ts/e2e-tests/README.md
+1 -1
@@ -27,7 +27,7 @@ ts/e2e-tests/
27 ├── runtimes/
28 ├── node/ # Node.js runtime tests
29 │ ├── cjs-basic/ # CommonJS compatibility tests
30 - │ ├── custom-tools/ # Custom local tools execution (session.execute, localTools, Zod validation)
30 + │ ├── custom-tools/ # Custom local tools execution (session.execute, proxyExecute, Zod validation)
31 │ ├── esm-basic/ # ESM compatibility tests
32 │ ├── json-schema-to-zod-v3/ # @composio/json-schema-to-zod + Zod v3 tests
33 │ ├── json-schema-to-zod-v4/ # @composio/json-schema-to-zod + Zod v4 tests
ts/e2e-tests/runtimes/node/custom-tools/e2e.test.ts
-4
@@ -74,10 +74,6 @@ e2e(import.meta.url, {
74 expect(result.stdout).toContain('NONEXISTENT_TOOL_OK');
75 });
76
77 - it('localTools() method works', () => {
78 - expect(result.stdout).toContain('LOCAL_TOOLS_METHOD_OK');
79 - });
80 -
77 it('session.tools() wrapping works', () => {
78 expect(result.stdout).toContain('TOOLS_WRAPPING_OK');
79 });
ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs
+8 -29
@@ -18,8 +18,7 @@ if (!apiKey) {
18
19 // ── Define custom tools ──────────────────────────────────────
20
21 -const getUserContext = createCustomTool({
22 - slug: 'GET_USER_CONTEXT',
21 +const getUserContext = createCustomTool('GET_USER_CONTEXT', {
22 name: 'Get user context',
23 description: 'Retrieve user preferences and history',
24 inputParams: z.object({
@@ -30,8 +29,7 @@ const getUserContext = createCustomTool({
29 },
30 });
31
33 -const enrichedSearch = createCustomTool({
34 - slug: 'ENRICHED_SEARCH',
32 +const enrichedSearch = createCustomTool('ENRICHED_SEARCH', {
33 name: 'Enriched search',
34 description: 'Search and enrich results with user context',
35 inputParams: z.object({
@@ -45,8 +43,7 @@ const enrichedSearch = createCustomTool({
43 },
44 });
45
48 -const throwingTool = createCustomTool({
49 - slug: 'THROWING_TOOL',
46 +const throwingTool = createCustomTool('THROWING_TOOL', {
47 name: 'Throwing tool',
48 description: 'A tool that always throws an error',
49 inputParams: z.object({}),
@@ -56,8 +53,7 @@ const throwingTool = createCustomTool({
53 });
54
55 // Tool with strict numeric schema — for Zod validation failure test
59 -const strictTool = createCustomTool({
60 - slug: 'STRICT_TOOL',
56 +const strictTool = createCustomTool('STRICT_TOOL', {
57 name: 'Strict tool',
58 description: 'Tool with strict numeric input',
59 inputParams: z.object({
@@ -69,8 +65,7 @@ const strictTool = createCustomTool({
65 });
66
67 // Tool that chains into a remote tool via SessionContext.execute()
72 -const weatherChain = createCustomTool({
73 - slug: 'WEATHER_CHAIN',
68 +const weatherChain = createCustomTool('WEATHER_CHAIN', {
69 name: 'Weather chain',
70 description: 'Fetches weather via remote tool and enriches with local context',
71 inputParams: z.object({
@@ -100,7 +95,9 @@ async function main() {
95 const session = await composio.create(userId, {
96 toolkits: ['weathermap'],
97 manageConnections: false,
103 - customTools: [getUserContext, enrichedSearch, throwingTool, strictTool, weatherChain],
98 + experimental: {
99 + customTools: [getUserContext, enrichedSearch, throwingTool, strictTool, weatherChain],
100 + },
101 });
102
103 // ── Test 1: Single local tool execution ──
@@ -232,24 +229,6 @@ async function main() {
229 console.log('NONEXISTENT_TOOL_OK');
230 }
231
235 - // ── Test 11: localTools() method ──
236 - {
237 - try {
238 - const localTool = await session.localTools();
239 - if (!localTool) {
240 - throw new Error('localTools() returned falsy value');
241 - }
242 - console.log('LOCAL_TOOLS_METHOD_OK');
243 - } catch (err) {
244 - // Expected — no provider configured in this fixture
245 - if (err.message?.includes('provider')) {
246 - console.log('LOCAL_TOOLS_METHOD_OK');
247 - } else {
248 - throw err;
249 - }
250 - }
251 - }
252 -
232 // ── Test 12: session.tools() wrapping ──
233 {
234 try {
ts/examples/tool-router/package.json
+3 -1
@@ -27,7 +27,9 @@
27 "@langchain/anthropic": "^1.1.3",
28 "@langchain/mcp-adapters": "^1.0.1",
29 "@langchain/openai": "^1.1.3",
30 - "@openai/agents": "^0.3.3",
30 + "@openai/agents": "^0.1.3",
31 + "openai": "^6.22.0",
32 + "zod": "catalog:",
33 "ai": "catalog:",
34 "dotenv": "^16.4.1",
35 "langchain": "^1.1.1",
ts/examples/tool-router/src/custom-tools-agent.ts new
+216
@@ -0,0 +1,216 @@
1 +/**
2 + * Custom Tools + Tool Router Agent
3 + *
4 + * Uses @composio/openai-agents provider with session.tools() for a proper
5 + * multi-turn agent that has both remote Composio tools (via tool router) and
6 + * custom local tools executing in-process.
7 + *
8 + * Demonstrates all three custom tool types:
9 + * 1. Standalone tools (no auth) — GET_USER_DETAILS, LIST_USER_KEYS
10 + * 2. Extension tool (inherits gmail auth) — FORMAT_GMAIL_EMAIL
11 + * 3. Custom toolkit (USER_MANAGEMENT) — SET_USER_ROLE, UPDATE_USER_STATUS
12 + *
13 + * Usage:
14 + * COMPOSIO_API_KEY=... OPENAI_API_KEY=... bun src/custom-tools-agent.ts
15 + */
16 +import "dotenv/config";
17 +import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
18 +import { OpenAIAgentsProvider } from "@composio/openai-agents";
19 +import { Agent, run } from "@openai/agents";
20 +import { z } from "zod/v3";
21 +
22 +// ── In-memory user store (shared across tools) ───────────────────
23 +
24 +const userStore: Record<string, Record<string, unknown>> = {
25 + "user-1": {
26 + id: "user-1",
27 + name: "Alice Johnson",
28 + email: "alice@acme.com",
29 + role: "admin",
30 + status: "active",
31 + created_at: "2024-01-15",
32 + },
33 + "user-2": {
34 + id: "user-2",
35 + name: "Bob Smith",
36 + email: "bob@acme.com",
37 + role: "developer",
38 + status: "active",
39 + created_at: "2024-03-22",
40 + },
41 + "user-3": {
42 + id: "user-3",
43 + name: "Carol Williams",
44 + email: "carol@acme.com",
45 + role: "viewer",
46 + status: "suspended",
47 + created_at: "2025-06-10",
48 + },
49 +};
50 +
51 +// ── 1. Standalone tools (no auth) → LOCAL_<SLUG> ─────────────────
52 +
53 +const getUserDetails = experimental_createTool("GET_USER_DETAILS", {
54 + name: "Get user details",
55 + description:
56 + "Retrieve user profile information including name, email, role, and account status by user ID",
57 + inputParams: z.object({
58 + user_id: z.string().describe("The unique user identifier"),
59 + }),
60 + execute: async (input) => {
61 + const user = userStore[input.user_id];
62 + if (!user) throw new Error(`User "${input.user_id}" not found`);
63 + return user;
64 + },
65 +});
66 +
67 +const listUserKeys = experimental_createTool("LIST_USER_KEYS", {
68 + name: "List user API keys",
69 + description:
70 + "List all active API keys for a given user, including creation date and last used timestamp",
71 + inputParams: z.object({
72 + user_id: z.string().describe("The user whose keys to list"),
73 + include_expired: z.boolean().default(false).describe("Whether to include expired keys"),
74 + }),
75 + execute: async (input) => {
76 + const allKeys: Record<string, Array<Record<string, unknown>>> = {
77 + "user-1": [
78 + { key_id: "key_abc", prefix: "sk-***abc", created_at: "2025-01-01", last_used: "2026-03-15", expired: false },
79 + { key_id: "key_old", prefix: "sk-***old", created_at: "2024-01-01", last_used: "2024-06-01", expired: true },
80 + ],
81 + "user-2": [
82 + { key_id: "key_xyz", prefix: "sk-***xyz", created_at: "2025-06-01", last_used: "2026-03-14", expired: false },
83 + ],
84 + };
85 + const keys = allKeys[input.user_id] ?? [];
86 + const filtered = input.include_expired ? keys : keys.filter((k) => !k.expired);
87 + return { user_id: input.user_id, api_keys: filtered, total: filtered.length };
88 + },
89 +});
90 +
91 +// ── 2. Extension tool (inherits gmail auth) → LOCAL_GMAIL_<SLUG> ──
92 +
93 +const formatGmailEmail = experimental_createTool("FORMAT_GMAIL_EMAIL", {
94 + name: "Format Gmail email",
95 + description: "Format and prepare an email draft with proper HTML formatting for sending via Gmail",
96 + extendsToolkit: "gmail",
97 + inputParams: z.object({
98 + to: z.string().describe("Recipient email address"),
99 + subject: z.string().describe("Email subject line"),
100 + body: z.string().describe("Email body content in markdown"),
101 + }),
102 + execute: async (input, session) => {
103 + const htmlBody = input.body
104 + .replace(/\*\*(.*?)\*\*/g, "<b>$1</b>")
105 + .replace(/\*(.*?)\*/g, "<i>$1</i>")
106 + .replace(/\n/g, "<br>");
107 + return {
108 + formatted: true,
109 + to: input.to,
110 + subject: input.subject,
111 + html_body: htmlBody,
112 + plain_body: input.body,
113 + user_id: session.userId,
114 + };
115 + },
116 +});
117 +
118 +// ── 3. Custom toolkit (USER_MANAGEMENT) → LOCAL_USER_MANAGEMENT_<SLUG> ──
119 +
120 +const setUserRole = experimental_createTool("SET_USER_ROLE", {
121 + name: "Set user role",
122 + description: "Change the role of an existing user (admin, developer, viewer)",
123 + inputParams: z.object({
124 + user_id: z.string().describe("The user to update"),
125 + role: z.enum(["admin", "developer", "viewer"]).describe("The new role to assign"),
126 + }),
127 + execute: async (input) => {
128 + const user = userStore[input.user_id];
129 + if (!user) throw new Error(`User "${input.user_id}" not found`);
130 + const previousRole = user.role;
131 + user.role = input.role;
132 + return { user_id: input.user_id, previous_role: previousRole, new_role: input.role };
133 + },
134 +});
135 +
136 +const updateUserStatus = experimental_createTool("UPDATE_USER_STATUS", {
137 + name: "Update user status",
138 + description: "Activate or suspend a user account",
139 + inputParams: z.object({
140 + user_id: z.string().describe("The user to update"),
141 + status: z.enum(["active", "suspended"]).describe("The new account status"),
142 + reason: z.string().optional().describe("Reason for the status change"),
143 + }),
144 + execute: async (input) => {
145 + const user = userStore[input.user_id];
146 + if (!user) throw new Error(`User "${input.user_id}" not found`);
147 + const previousStatus = user.status;
148 + user.status = input.status;
149 + return {
150 + user_id: input.user_id,
151 + previous_status: previousStatus,
152 + new_status: input.status,
153 + reason: input.reason ?? "No reason provided",
154 + };
155 + },
156 +});
157 +
158 +const userManagement = experimental_createToolkit("USER_MANAGEMENT", {
159 + name: "User Management",
160 + description: "Tools for managing user profiles, roles, and account status",
161 + tools: [setUserRole, updateUserStatus],
162 +});
163 +
164 +// ── Agent ─────────────────────────────────────────────────────────
165 +
166 +const composio = new Composio({
167 + apiKey: process.env.COMPOSIO_API_KEY,
168 + baseURL: process.env.COMPOSIO_BASE_URL || undefined,
169 + provider: new OpenAIAgentsProvider(),
170 +});
171 +
172 +const session = await composio.create(`agent-e2e-${Date.now()}`, {
173 + toolkits: ["weathermap", "gmail"],
174 + manageConnections: false,
175 + experimental: {
176 + customTools: [getUserDetails, listUserKeys, formatGmailEmail],
177 + customToolkits: [userManagement],
178 + },
179 +});
180 +
181 +console.log(`Session: ${session.sessionId}\n`);
182 +const tools = await session.tools();
183 +
184 +const agent = new Agent({
185 + name: "Custom Tools Agent",
186 + instructions: "You are a helpful assistant. Use Composio tools to execute tasks.",
187 + model: "gpt-5.2",
188 + tools,
189 +});
190 +
191 +const MAX = 3000;
192 +function trunc(obj: unknown): string {
193 + const json = JSON.stringify(obj, null, 2);
194 + return json.length > MAX ? json.slice(0, MAX) + "\n ... (truncated)" : json;
195 +}
196 +
197 +agent.on("agent_tool_start", (_ctx, tool, details: any) => {
198 + const input = details.toolCall?.arguments ?? {};
199 + console.log(`\n ┌─ ${tool.name}`);
200 + console.log(` │ INPUT:\n${trunc(input)}`);
201 +});
202 +agent.on("agent_tool_end", (_ctx, tool, result: any) => {
203 + let output: unknown;
204 + try { output = typeof result === "string" ? JSON.parse(result) : result; } catch { output = result; }
205 + console.log(` │ OUTPUT:\n${trunc(output)}`);
206 + console.log(` └─ ${tool.name} done`);
207 +});
208 +
209 +const prompt = `Do the following tasks:
210 +1. Get user-1's profile details and list their API keys
211 +2. Promote user-3 (Carol) to developer role and reactivate her account (she was suspended by mistake)
212 +3. Get the current weather in Tokyo`;
213 +
214 +console.log(`User: ${prompt}\n`);
215 +const result = await run(agent, prompt);
216 +console.log(`\nAssistant: ${result.finalOutput}`);
ts/packages/core/src/experimental/index.ts
+3 -1
@@ -7,10 +7,12 @@
7 */
8
9 // Custom tools
10 -export { createCustomTool } from '../models/CustomTool';
10 +export { createCustomTool, createCustomToolkit } from '../models/CustomTool';
11 export type {
12 CustomTool,
13 CreateCustomToolParams,
14 CustomToolExecuteFn,
15 SessionContext,
16 + CustomToolkit,
17 + CreateCustomToolkitParams,
18 } from '../types/customTool.types';
ts/packages/core/src/index.ts
+5
@@ -29,5 +29,10 @@ export * from './types/ToolRouterSessionFilesMount.types';
29 export * as constants from './utils/constants';
30
31 export { default as logger } from './utils/logger';
32 +
33 +// Experimental custom tools — exported with experimental_ prefix for top-level import
34 +export { createCustomTool as experimental_createTool } from './models/CustomTool';
35 +export { createCustomToolkit as experimental_createToolkit } from './models/CustomTool';
36 +
37 // Error handling exports
38 export * from './errors';
ts/packages/core/src/models/CustomTool.ts
+210 -60
@@ -1,16 +1,23 @@
1 /**
2 - * @fileoverview Standalone factory function for creating custom tools.
2 + * @fileoverview Factory functions for creating custom tools and toolkits.
3 *
4 * Usage:
5 * ```typescript
6 - * import { createCustomTool } from '@composio/core/experimental';
7 - *
8 - * const myTool = createCustomTool({
9 - * slug: 'GET_USER_CONTEXT',
10 - * name: 'Get user context',
11 - * description: 'Retrieve what we know about a user',
12 - * inputParams: z.object({ category: z.string() }),
13 - * execute: async (input) => ({ preferences: await db.find(input.category) }),
6 + * import { experimental_createTool, experimental_createToolkit } from '@composio/core';
7 + * // or
8 + * import { createCustomTool, createCustomToolkit } from '@composio/core/experimental';
9 + *
10 + * const grep = createCustomTool('GREP', {
11 + * name: 'Grep Search',
12 + * description: 'Search for patterns in files',
13 + * inputParams: z.object({ pattern: z.string() }),
14 + * execute: async (input) => ({ matches: [] }),
15 + * });
16 + *
17 + * const devTools = createCustomToolkit('DEV_TOOLS', {
18 + * name: 'Dev Tools',
19 + * description: 'Local dev utilities',
20 + * tools: [grep],
21 * });
22 * ```
23 */
@@ -18,79 +25,74 @@ import * as zodToJsonSchema from 'zod-to-json-schema';
25 import { z } from 'zod/v3';
26 import {
27 CreateCustomToolBaseSchema,
28 + CreateCustomToolkitBaseSchema,
29 + CustomToolSlugSchema,
30 type CreateCustomToolParams,
31 + type CreateCustomToolkitParams,
32 type CustomTool,
33 + type CustomToolkit,
34 type CustomToolExecuteFn,
35 type CustomToolsMap,
36 type CustomToolsMapEntry,
37 type CustomToolDefinition,
38 + type CustomToolkitDefinition,
39 type InputParamsSchema,
40 } from '../types/customTool.types';
41
42 /** Prefix applied by the backend to local tool slugs for disambiguation. */
43 export const LOCAL_TOOL_PREFIX = 'LOCAL_';
44
45 +/** Maximum allowed length for the final prefixed slug. */
46 +const MAX_PREFIXED_SLUG_LENGTH = 60;
47 +
48 /**
49 * Create a custom tool for use in tool router sessions.
50 *
51 * The returned object is a lightweight reference containing the tool's metadata
37 - * and execute function. Pass it to `composio.create(userId, { customTools: [...] })`
52 + * and execute function. Pass it to `composio.create(userId, { experimental: { customTools: [...] } })`
53 * to bind it to a session.
54 *
55 * Just return the result data from `execute`, or throw an error.
56 * The SDK wraps it into the standard response format internally.
57 *
43 - * @param options - Tool definition including slug, schema, and execute function
58 + * @param slug - Unique tool identifier (alphanumeric, underscores, hyphens; no LOCAL_ prefix)
59 + * @param options - Tool definition including name, schema, and execute function
60 * @returns A CustomTool to pass to session creation
61 *
46 - * @example No-auth tool (no session needed)
62 + * @example Standalone tool (no auth)
63 * ```typescript
48 - * const getUserContext = createCustomTool({
49 - * slug: 'GET_USER_CONTEXT',
50 - * name: 'Get user context',
51 - * description: 'Retrieve user preferences and history',
52 - * inputParams: z.object({ category: z.string().default('all') }),
53 - * execute: async (input) => {
54 - * const prefs = await db.userContext.find(input.category);
55 - * return { preferences: prefs };
56 - * },
64 + * const grep = createCustomTool('GREP', {
65 + * name: 'Grep Search',
66 + * description: 'Search for patterns in files',
67 + * inputParams: z.object({ pattern: z.string(), path: z.string() }),
68 + * execute: async (input) => ({ matches: [] }),
69 * });
70 * ```
71 *
60 - * @example Tool using session to call other tools
72 + * @example Tool extending a Composio toolkit (inherits auth)
73 * ```typescript
62 - * const enrichedSearch = createCustomTool({
63 - * slug: 'ENRICHED_SEARCH',
64 - * name: 'Enriched search',
65 - * description: 'Search and enrich results with user context',
66 - * inputParams: z.object({ query: z.string() }),
74 + * const getImportant = createCustomTool('GET_IMPORTANT_EMAILS', {
75 + * name: 'Get Important Emails',
76 + * description: 'Fetch high-priority emails',
77 + * extendsToolkit: 'gmail',
78 + * inputParams: z.object({ limit: z.number().default(10) }),
79 * execute: async (input, session) => {
68 - * const results = await session.execute('GOOGLE_SEARCH', { query: input.query });
69 - * return { enriched: results.data, userId: session.userId };
70 - * },
71 - * });
72 - * ```
73 - *
74 - * @example Auth tool with toolkit (requires Composio connection)
75 - * ```typescript
76 - * const getAdAccounts = createCustomTool({
77 - * slug: 'GET_AD_ACCOUNTS',
78 - * name: 'Get ad accounts',
79 - * description: 'Get Meta ad account IDs for the authenticated user',
80 - * toolkit: 'meta_ads',
81 - * inputParams: z.object({ fields: z.string().default('id,name') }),
82 - * execute: async (input, session) => {
83 - * const result = await session.execute('META_ADS_GET_AD_ACCOUNTS', {
84 - * fields: input.fields,
85 - * });
86 - * return result.data;
80 + * const result = await session.execute('GMAIL_SEARCH', { query: 'is:important' });
81 + * return { emails: result.data };
82 * },
83 * });
84 * ```
85 */
86 export function createCustomTool<T extends z.ZodType>(
87 + slug: string,
88 options: CreateCustomToolParams<T>
89 ): CustomTool {
90 + // Validate slug separately
91 + const slugResult = CustomToolSlugSchema.safeParse(slug);
92 + if (!slugResult.success) {
93 + throw new Error(`createCustomTool: ${slugResult.error.issues[0].message}`);
94 + }
95 +
96 // Validate string/scalar fields via Zod schema
97 const validated = CreateCustomToolBaseSchema.parse(options);
98
@@ -104,7 +106,7 @@ export function createCustomTool<T extends z.ZodType>(
106
107 const { inputParams, execute } = options;
108
107 - // Convert Zod schema → JSON Schema (reuses same pattern as legacy CustomTools.createTool)
109 + // Convert Zod input schema → JSON Schema
110 const paramsSchema = zodToJsonSchema.default(inputParams, {
111 name: 'input',
112 }) as InputParamsSchema;
@@ -116,41 +118,162 @@ export function createCustomTool<T extends z.ZodType>(
118 ...(paramsSchemaJson.required ? { required: paramsSchemaJson.required } : {}),
119 };
120
121 + // Convert Zod output schema → JSON Schema (if provided)
122 + let outputSchema: Record<string, unknown> | undefined;
123 + if (options.outputParams) {
124 + const outSchema = zodToJsonSchema.default(options.outputParams, {
125 + name: 'output',
126 + }) as { definitions: { output: { type: string; properties: Record<string, unknown>; required?: string[] } } };
127 + const outJson = outSchema.definitions.output;
128 + outputSchema = {
129 + type: 'object',
130 + properties: outJson.properties,
131 + ...(outJson.required ? { required: outJson.required } : {}),
132 + };
133 + }
134 +
135 return {
120 - slug: validated.slug,
136 + slug: slugResult.data,
137 name: validated.name,
138 description: validated.description,
123 - toolkit: validated.toolkit,
139 + extendsToolkit: validated.extendsToolkit,
140 inputSchema,
141 + outputSchema,
142 inputParams,
143 execute: execute as CustomToolExecuteFn<z.ZodType>,
144 };
145 }
146
147 /**
131 - * Build a CustomToolsMap from an array of custom tools.
148 + * Create a custom toolkit that groups related tools.
149 + *
150 + * Tools in a toolkit get prefixed as `LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>`.
151 + * Tools passed here must NOT have `extendsToolkit` set — they inherit the toolkit identity instead.
152 + *
153 + * @param slug - Unique toolkit identifier (alphanumeric, underscores, hyphens; no LOCAL_ prefix)
154 + * @param options - Toolkit definition including name, description, and tools
155 + * @returns A CustomToolkit to pass to session creation
156 + *
157 + * @example
158 + * ```typescript
159 + * const devTools = createCustomToolkit('DEV_TOOLS', {
160 + * name: 'Dev Tools',
161 + * description: 'Local dev utilities',
162 + * tools: [grepTool, sedTool],
163 + * });
164 + * ```
165 + */
166 +export function createCustomToolkit(
167 + slug: string,
168 + options: CreateCustomToolkitParams
169 +): CustomToolkit {
170 + // Validate slug
171 + const slugResult = CustomToolSlugSchema.safeParse(slug);
172 + if (!slugResult.success) {
173 + throw new Error(`createCustomToolkit: ${slugResult.error.issues[0].message}`);
174 + }
175 +
176 + // Validate name/description
177 + const validated = CreateCustomToolkitBaseSchema.parse(options);
178 +
179 + // Non-empty tools required
180 + if (!options.tools?.length) {
181 + throw new Error('createCustomToolkit: at least one tool is required');
182 + }
183 +
184 + // Reject tools with extendsToolkit
185 + for (const tool of options.tools) {
186 + if (tool.extendsToolkit) {
187 + throw new Error(
188 + `createCustomToolkit: tool "${tool.slug}" has extendsToolkit set. ` +
189 + `Tools in a custom toolkit must not use extendsToolkit — they inherit the toolkit identity instead.`
190 + );
191 + }
192 + }
193 +
194 + return {
195 + slug: slugResult.data,
196 + name: validated.name,
197 + description: validated.description,
198 + tools: options.tools,
199 + };
200 +}
201 +
202 +/**
203 + * Build a CustomToolsMap from custom tools and toolkits.
204 * Used internally by ToolRouter.create() to construct the per-session routing map.
205 *
206 + * Prefix rules:
207 + * - Standalone (no extendsToolkit): `LOCAL_<SLUG>`
208 + * - Extends toolkit: `LOCAL_<EXTENDS_TOOLKIT>_<SLUG>`
209 + * - Toolkit tool: `LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>`
210 + *
211 * @internal
135 - * @param tools - The custom tools to include in the session
212 + * @param tools - Standalone custom tools
213 + * @param toolkits - Custom toolkits containing grouped tools
214 * @returns Maps for O(1) lookup by both prefixed and original slug
137 - * @throws If duplicate slugs are detected
215 + * @throws If duplicate slugs, slug too long, or cross-group collisions
216 */
139 -export function buildCustomToolsMap(tools: CustomTool[]): CustomToolsMap {
217 +export function buildCustomToolsMap(
218 + tools: CustomTool[],
219 + toolkits?: CustomToolkit[]
220 +): CustomToolsMap {
221 const byPrefixed = new Map<string, CustomToolsMapEntry>();
222 const byOriginal = new Map<string, CustomToolsMapEntry>();
223
143 - for (const handle of tools) {
144 - const upperSlug = handle.slug.toUpperCase();
145 - const prefixedSlug = `${LOCAL_TOOL_PREFIX}${upperSlug}`;
224 + const addEntry = (handle: CustomTool, prefixedSlug: string) => {
225 + const originalSlug = handle.slug.toUpperCase();
226 +
227 + // Validate final prefixed slug length
228 + if (prefixedSlug.length > MAX_PREFIXED_SLUG_LENGTH) {
229 + const prefix = prefixedSlug.substring(0, prefixedSlug.length - originalSlug.length);
230 + const available = MAX_PREFIXED_SLUG_LENGTH - prefix.length;
231 + throw new Error(
232 + `Custom tool slug "${handle.slug}" is too long. ` +
233 + `With prefix "${prefix}", the final slug "${prefixedSlug}" exceeds ${MAX_PREFIXED_SLUG_LENGTH} characters. ` +
234 + `Shorten the slug to at most ${available} characters.`
235 + );
236 + }
237
147 - if (byOriginal.has(upperSlug)) {
148 - throw new Error(`createCustomTool: duplicate slug "${handle.slug}"`);
238 + // Check cross-group collisions on prefixed slug
239 + if (byPrefixed.has(prefixedSlug)) {
240 + throw new Error(`Custom tool slug collision: "${prefixedSlug}" is already registered.`);
241 + }
242 +
243 + // Check cross-group collisions on original slug
244 + if (byOriginal.has(originalSlug)) {
245 + throw new Error(
246 + `Custom tool slug collision: original slug "${handle.slug}" maps to multiple prefixed slugs. ` +
247 + `"${byOriginal.get(originalSlug)!.prefixedSlug}" and "${prefixedSlug}" both resolve from "${originalSlug}".`
248 + );
249 }
250
251 const entry: CustomToolsMapEntry = { handle, prefixedSlug };
252 byPrefixed.set(prefixedSlug, entry);
153 - byOriginal.set(upperSlug, entry);
253 + byOriginal.set(originalSlug, entry);
254 + };
255 +
256 + // Process standalone tools
257 + for (const handle of tools) {
258 + const upperSlug = handle.slug.toUpperCase();
259 + if (handle.extendsToolkit) {
260 + // LOCAL_<EXTENDS_TOOLKIT>_<SLUG>
261 + addEntry(handle, `LOCAL_${handle.extendsToolkit.toUpperCase()}_${upperSlug}`);
262 + } else {
263 + // LOCAL_<SLUG>
264 + addEntry(handle, `LOCAL_${upperSlug}`);
265 + }
266 + }
267 +
268 + // Process toolkit tools
269 + if (toolkits) {
270 + for (const toolkit of toolkits) {
271 + const tkSlug = toolkit.slug.toUpperCase();
272 + for (const handle of toolkit.tools) {
273 + // LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>
274 + addEntry(handle, `LOCAL_${tkSlug}_${handle.slug.toUpperCase()}`);
275 + }
276 + }
277 }
278
279 return { byPrefixed, byOriginal };
@@ -159,6 +282,8 @@ export function buildCustomToolsMap(tools: CustomTool[]): CustomToolsMap {
282 /**
283 * Serialize custom tools into the format expected by the backend session creation API.
284 *
285 + * Maps `extendsToolkit` → `extends_toolkit` for backend. Omitted for standalone tools.
286 + *
287 * @internal
288 * @param tools - The custom tools to serialize
289 * @returns Array of CustomToolDefinition for the API payload
@@ -171,6 +296,31 @@ export function serializeCustomTools(
296 name: handle.name,
297 description: handle.description,
298 input_schema: handle.inputSchema,
174 - ...(handle.toolkit ? { toolkit: handle.toolkit } : {}),
299 + ...(handle.outputSchema ? { output_schema: handle.outputSchema } : {}),
300 + ...(handle.extendsToolkit ? { extends_toolkit: handle.extendsToolkit } : {}),
301 + }));
302 +}
303 +
304 +/**
305 + * Serialize custom toolkits into the format expected by the backend session creation API.
306 + *
307 + * @internal
308 + * @param toolkits - The custom toolkits to serialize
309 + * @returns Array of CustomToolkitDefinition for the API payload
310 + */
311 +export function serializeCustomToolkits(
312 + toolkits: CustomToolkit[]
313 +): CustomToolkitDefinition[] {
314 + return toolkits.map(tk => ({
315 + slug: tk.slug,
316 + name: tk.name,
317 + description: tk.description,
318 + tools: tk.tools.map(t => ({
319 + slug: t.slug,
320 + name: t.name,
321 + description: t.description,
322 + input_schema: t.inputSchema,
323 + ...(t.outputSchema ? { output_schema: t.outputSchema } : {}),
324 + })),
325 }));
326 }
ts/packages/core/src/models/SessionContext.ts
+23 -10
@@ -3,7 +3,10 @@
3 */
4 import { Composio as ComposioClient } from '@composio/client';
5 import type { SessionContext } from '../types/customTool.types';
6 -import type { ToolExecuteResponse, ToolProxyParams } from '../types/tool.types';
6 +import type { ToolExecuteResponse } from '../types/tool.types';
7 +import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
8 +import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';
9 +import { transformProxyParams } from './proxyParamsTransform';
10
11 /**
12 * Callback that attempts local tool execution.
@@ -66,16 +69,26 @@ export class SessionContextImpl implements SessionContext {
69
70 /**
71 * Proxy API calls through Composio's auth layer.
69 - * The session-scoped backend endpoint resolves the connected account automatically.
70 - *
71 - * TODO: Wire to session-scoped proxy endpoint (proxyExecuteForSessionRPC).
72 - * Currently a skeleton — will be connected to backend API.
72 + * The backend resolves the connected account from the toolkit within the session.
73 */
74 - async proxyExecute(_params: ToolProxyParams): Promise<ToolExecuteResponse> {
75 - // TODO: Call session-scoped proxy endpoint that resolves connected account from session.
76 - // Backend API: apps/apollo/src/lib/toolRouterV2/features/execution/proxyExecuteForSessionRPC.ts
77 - throw new Error(
78 - 'proxyExecute is not yet implemented. Session-scoped proxy endpoint pending backend support.'
74 + async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolExecuteResponse> {
75 + const validated = SessionProxyExecuteParamsSchema.safeParse(params);
76 + if (!validated.success) {
77 + throw new Error(`Invalid proxy execute parameters: ${validated.error.message}`);
78 + }
79 +
80 + const body = transformProxyParams(validated.data);
81 +
82 + // TODO: Replace with client.toolRouter.session.proxyExecute() when @composio/client is updated
83 + const response = await (this.client as unknown as { post: (path: string, opts: { body: unknown }) => Promise<{ data: Record<string, unknown>; error: string | null; log_id: string }> }).post(
84 + `/api/v3/tool_router/session/${this.sessionId}/proxy_execute`,
85 + { body }
86 );
87 +
88 + return {
89 + data: response.data ?? {},
90 + error: response.error,
91 + successful: !response.error,
92 + };
93 }
94 }
ts/packages/core/src/models/ToolRouter.ts
+30 -21
@@ -38,8 +38,8 @@ import {
38 transformToolRouterToolkitsParams,
39 } from '../lib/toolRouterParams';
40 import { ToolRouterSession } from './ToolRouterSession';
41 -import { buildCustomToolsMap, serializeCustomTools } from './CustomTool';
42 -import type { CustomToolsMap, CustomToolDefinition } from '../types/customTool.types';
41 +import { buildCustomToolsMap, serializeCustomTools, serializeCustomToolkits } from './CustomTool';
42 +import type { CustomToolsMap } from '../types/customTool.types';
43
44 export class ToolRouter<
45 TToolCollection,
@@ -78,15 +78,17 @@ export class ToolRouter<
78 *
79 * @example
80 * ```typescript
81 - * import { Composio } from '@composio/core';
82 - * import { CustomTool } from '@composio/core/experimental';
81 + * import { Composio, experimental_createTool } from '@composio/core';
82 *
83 * const composio = new Composio();
84 *
85 * const session = await composio.create('user_123', {
86 * toolkits: ['gmail'],
87 * manageConnections: true,
89 - * customTools: [myCustomTool],
88 + * experimental: {
89 + * customTools: [myCustomTool],
90 + * customToolkits: [myToolkit],
91 + * },
92 * });
93 * ```
94 */
@@ -96,11 +98,29 @@ export class ToolRouter<
98 ): Promise<Session<TToolCollection, TTool, TProvider>> {
99 const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});
100
99 - // Build custom tools map and backend payload from custom tool handles
101 + // Extract custom tools/toolkits from experimental config
102 + const customTools = routerConfig.experimental?.customTools;
103 + const customToolkits = routerConfig.experimental?.customToolkits;
104 let customToolsMap: CustomToolsMap | undefined;
101 - const customTools = routerConfig.customTools;
105
103 - const payload: SessionCreateParams & { custom_tools?: CustomToolDefinition[] } = {
106 + // Build the experimental payload for the backend
107 + const experimentalPayload: Record<string, unknown> = {};
108 +
109 + if (routerConfig.experimental?.assistivePrompt?.userTimezone) {
110 + experimentalPayload.assistive_prompt_config = {
111 + user_timezone: routerConfig.experimental.assistivePrompt.userTimezone,
112 + };
113 + }
114 +
115 + if (customTools?.length || customToolkits?.length) {
116 + customToolsMap = buildCustomToolsMap(customTools ?? [], customToolkits);
117 + experimentalPayload.custom_tools = serializeCustomTools(customTools ?? []);
118 + if (customToolkits?.length) {
119 + experimentalPayload.custom_toolkits = serializeCustomToolkits(customToolkits);
120 + }
121 + }
122 +
123 + const payload: SessionCreateParams = {
124 user_id: userId,
125 auth_configs: routerConfig.authConfigs,
126 connected_accounts: routerConfig.connectedAccounts,
@@ -111,22 +131,11 @@ export class ToolRouter<
131 routerConfig.manageConnections
132 ),
133 workbench: transformToolRouterWorkbenchParams(routerConfig.workbench),
114 - experimental: routerConfig.experimental?.assistivePrompt?.userTimezone
115 - ? {
116 - assistive_prompt_config: {
117 - user_timezone: routerConfig.experimental.assistivePrompt.userTimezone,
118 - },
119 - }
134 + experimental: Object.keys(experimentalPayload).length > 0
135 + ? experimentalPayload
136 : undefined,
137 };
138
123 - if (customTools?.length) {
124 - customToolsMap = buildCustomToolsMap(customTools);
125 - // Send definitions to backend for search indexing
126 - // Type assertion: @composio/client doesn't have custom_tools yet
127 - payload.custom_tools = serializeCustomTools(customTools);
128 - }
129 -
139 const session = await this.client.toolRouter.session.create(
140 payload as SessionCreateParams
141 );
ts/packages/core/src/models/ToolRouterSession.ts
+41 -106
@@ -26,12 +26,14 @@ import { ValidationError } from '../errors';
26 import { Tools } from './Tools';
27 import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';
28 import type { CustomToolsMap, CustomToolsMapEntry, SessionContext } from '../types/customTool.types';
29 -import type { Tool, ToolExecuteResponse } from '../types/tool.types';
29 +import type { ToolExecuteResponse } from '../types/tool.types';
30 +import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
31 +import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';
32 import { SessionContextImpl } from './SessionContext';
33 import { findCustomTool, executeCustomTool } from './customToolExecution';
34 +import { transformProxyParams } from './proxyParamsTransform';
35
36 const COMPOSIO_MULTI_EXECUTE_TOOL = 'COMPOSIO_MULTI_EXECUTE_TOOL';
34 -const COMPOSIO_EXECUTE_LOCAL_TOOL = 'COMPOSIO_EXECUTE_LOCAL_TOOL';
37
38 export class ToolRouterSession<
39 TToolCollection,
@@ -86,19 +88,6 @@ export class ToolRouterSession<
88 if (toolSlug === COMPOSIO_MULTI_EXECUTE_TOOL) {
89 return this.routeMultiExecute(input, ToolsModel, modifiers);
90 }
89 - if (toolSlug === COMPOSIO_EXECUTE_LOCAL_TOOL) {
90 - const slug = String(input.tool_slug ?? '');
91 - const args = (input.arguments as Record<string, unknown> | undefined) ?? {};
92 - const entry = findCustomTool(this.customToolsMap, slug);
93 - if (!entry) {
94 - return {
95 - data: {},
96 - error: `Custom tool "${slug}" not found. If this is a remote tool, execute it via COMPOSIO_MULTI_EXECUTE_TOOL.`,
97 - successful: false,
98 - };
99 - }
100 - return executeCustomTool(entry, args, this.buildSessionContext());
101 - }
91 // Non-multi-execute meta tools always go to backend
92 return ToolsModel.executeMetaTool(
93 toolSlug,
@@ -123,90 +112,6 @@ export class ToolRouterSession<
112 return wrappedTools as ReturnType<TProvider['wrapTools']>;
113 }
114
126 - /**
127 - * Returns a dispatcher tool that exposes custom tools for execution.
128 - * Primarily used in MCP flows where remote tools are served via an MCP server
129 - * and custom tools need to be added alongside.
130 - *
131 - * Not included in `session.tools()` — must be explicitly added to the agent's tool set.
132 - *
133 - * @example
134 - * ```typescript
135 - * // MCP flow: remote tools via MCP server, local tools via localTools()
136 - * const localTool = await session.localTools();
137 - * const agent = new Agent({
138 - * tools: [
139 - * hostedMcpTool(session.mcp.url), // remote tools from MCP
140 - * ...localTool, // custom tools
141 - * ],
142 - * });
143 - * ```
144 - */
145 - async localTools(): Promise<ReturnType<TProvider['wrapTools']>> {
146 - if (!this.hasCustomTools()) {
147 - throw new Error('No custom tools are bound to this session.');
148 - }
149 - if (!this.config?.provider) {
150 - throw new Error(
151 - 'A provider is required for session.localTools(). ' +
152 - 'Pass a provider in the Composio constructor.'
153 - );
154 - }
155 -
156 - // Collect local tool slugs and descriptions for the schema
157 - const toolEntries = Array.from(this.customToolsMap!.byOriginal.entries());
158 - const slugDescriptions = toolEntries
159 - .map(([_slug, entry]) => `- ${entry.prefixedSlug}: ${entry.handle.description}`)
160 - .join('\n');
161 -
162 - // Build a synthetic Tool schema for COMPOSIO_EXECUTE_LOCAL_TOOL
163 - const tool: Tool = {
164 - slug: COMPOSIO_EXECUTE_LOCAL_TOOL,
165 - name: 'Execute Local Tool',
166 - description: `Execute a custom tool by slug.\n\nAvailable tools:\n${slugDescriptions}`,
167 - inputParameters: {
168 - type: 'object',
169 - properties: {
170 - tool_slug: {
171 - type: 'string',
172 - description: 'The slug of the local tool to execute',
173 - enum: toolEntries.map(([, entry]) => entry.prefixedSlug),
174 - },
175 - arguments: {
176 - type: 'object',
177 - description: 'Arguments to pass to the tool',
178 - properties: {},
179 - additionalProperties: true,
180 - },
181 - },
182 - required: ['tool_slug'],
183 - },
184 - };
185 -
186 - const executeFn = async (
187 - _toolSlug: string,
188 - input: Record<string, unknown>
189 - ): Promise<ToolExecuteResponse> => {
190 - const slug = String(input.tool_slug ?? '');
191 - const args = (input.arguments as Record<string, unknown> | undefined) ?? {};
192 -
193 - const entry = findCustomTool(this.customToolsMap, slug);
194 - if (!entry) {
195 - return {
196 - data: {},
197 - error: `Custom tool "${slug}" not found. Available: ${toolEntries.map(([, e]) => e.prefixedSlug).join(', ')}. If this is a remote tool, execute it via COMPOSIO_MULTI_EXECUTE_TOOL.`,
198 - successful: false,
199 - };
200 - }
201 -
202 - return executeCustomTool(entry, args, this.buildSessionContext());
203 - };
204 -
205 - return this.config.provider.wrapTools([tool], executeFn) as ReturnType<
206 - TProvider['wrapTools']
207 - >;
208 - }
209 -
115 /**
116 * Initiate an authorization flow for a toolkit.
117 * Returns a ConnectionRequest with a redirect URL for the user.
@@ -331,6 +236,34 @@ export class ToolRouterSession<
236 return ToolRouterSessionExecuteResponseSchema.parse(transformed);
237 }
238
239 + /**
240 + * Proxy an API call through Composio's auth layer using the session's connected account.
241 + * The backend resolves the connected account from the toolkit within the session.
242 + *
243 + * @param params - Proxy request parameters (toolkit, endpoint, method, body, headers/query params)
244 + * @returns The proxied API response
245 + */
246 + async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionExecuteResponse> {
247 + const validated = SessionProxyExecuteParamsSchema.safeParse(params);
248 + if (!validated.success) {
249 + throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });
250 + }
251 +
252 + const body = transformProxyParams(validated.data);
253 +
254 + // TODO: Replace with client.toolRouter.session.proxyExecute() when @composio/client is updated
255 + const response = await (this.client as unknown as { post: (path: string, opts: { body: unknown }) => Promise<{ data: Record<string, unknown>; error: string | null; log_id: string }> }).post(
256 + `/api/v3/tool_router/session/${this.sessionId}/proxy_execute`,
257 + { body }
258 + );
259 +
260 + return ToolRouterSessionExecuteResponseSchema.parse({
261 + data: response.data,
262 + error: response.error,
263 + logId: response.log_id,
264 + });
265 + }
266 +
267 // ── Private helpers ──────────────────────────────────────────
268
269 /** Check if this session has any custom tools bound. */
@@ -457,18 +390,20 @@ export class ToolRouterSession<
390 }));
391
392 // Merge and re-index sequentially so there are no collisions
460 - const allResults = [...remoteResults, ...localEntries].map(
461 - (entry: Record<string, unknown>, i) => ({
462 - ...entry,
463 - index: i,
464 - })
465 - );
393 + const merged: Array<Record<string, unknown>> = [
394 + ...(remoteResults as Array<Record<string, unknown>>),
395 + ...localEntries,
396 + ];
397 + const allResults = merged.map((entry, i): Record<string, unknown> => ({
398 + ...entry,
399 + index: i,
400 + }));
401 const hasAnyError = localResults.some(r => r.result.error) || !!remoteResult?.error;
402
403 return {
404 data: { ...remoteData, results: allResults },
405 error: hasAnyError
471 - ? `${allResults.filter((r: Record<string, unknown>) => r.error).length} out of ${allResults.length} tools failed`
406 + ? `${allResults.filter(r => r.error).length} out of ${allResults.length} tools failed`
407 : null,
408 successful: !hasAnyError,
409 };
ts/packages/core/src/models/proxyParamsTransform.ts new
+34
@@ -0,0 +1,34 @@
1 +/**
2 + * @fileoverview Shared transform for converting SDK SessionProxyExecuteParams
3 + * to the backend proxy execute request format.
4 + */
5 +import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
6 +
7 +/** Backend session proxy execute request body shape. */
8 +export interface SessionProxyExecuteRequestBody {
9 + toolkit_slug: string;
10 + endpoint: string;
11 + method: string;
12 + body?: unknown;
13 + parameters?: Array<{ name: string; type: 'header' | 'query'; value: string }>;
14 +}
15 +
16 +/**
17 + * Transform SDK session proxy params to the backend request format.
18 + * Converts `in` (query/header) to `type` and stringifies values.
19 + */
20 +export function transformProxyParams(params: SessionProxyExecuteParams): SessionProxyExecuteRequestBody {
21 + const parameters = params.parameters?.map(p => ({
22 + name: p.name,
23 + type: p.in as 'header' | 'query',
24 + value: p.value.toString(),
25 + }));
26 +
27 + return {
28 + toolkit_slug: params.toolkit,
29 + endpoint: params.endpoint,
30 + method: params.method,
31 + ...(params.body !== undefined ? { body: params.body } : {}),
32 + ...(parameters?.length ? { parameters } : {}),
33 + };
34 +}
ts/packages/core/src/types/customTool.types.ts
+77 -20
@@ -1,5 +1,6 @@
1 import { z } from 'zod/v3';
2 import { Tool, ToolProxyParams, ToolExecuteResponse as SdkToolExecuteResponse } from './tool.types';
3 +import type { SessionProxyExecuteParams } from './toolRouter.types';
4 import { ToolExecuteResponse } from '@composio/client/resources/tools';
5 import { ConnectionData } from './connectedAccountAuthStates.types';
6
@@ -74,11 +75,8 @@ export interface SessionContext {
75 toolSlug: string,
76 arguments_: Record<string, unknown>
77 ): Promise<SdkToolExecuteResponse>;
77 - /**
78 - * Proxy API calls through Composio's auth layer (resolved from session).
79 - * @todo Not yet implemented — pending backend session-scoped proxy endpoint.
80 - */
81 - proxyExecute(params: ToolProxyParams): Promise<SdkToolExecuteResponse>;
78 + /** Proxy API calls through Composio's auth layer (resolved from session toolkit). */
79 + proxyExecute(params: SessionProxyExecuteParams): Promise<SdkToolExecuteResponse>;
80 }
81
82 /**
@@ -94,26 +92,37 @@ export type CustomToolExecuteFn<T extends z.ZodType> = (
92 session: SessionContext
93 ) => Promise<Record<string, unknown>>;
94
95 +/**
96 + * Zod schema for validating a custom tool slug.
97 + * Alphanumeric, underscores, and hyphens only. No `LOCAL_` prefix.
98 + * Length is validated later in `buildCustomToolsMap` with contextual error.
99 + */
100 +export const CustomToolSlugSchema = z
101 + .string()
102 + .min(1, 'slug is required')
103 + .regex(
104 + /^[A-Za-z0-9_-]+$/,
105 + 'slug must only contain alphanumeric characters, underscores, and hyphens'
106 + )
107 + .refine(s => !s.toUpperCase().startsWith('LOCAL_'), {
108 + message:
109 + 'slug must not start with "LOCAL_" — this prefix is reserved for internal routing.',
110 + });
111 +
112 /**
113 * Zod schema for validating the string/scalar fields of createCustomTool() options.
99 - * Used internally for validation — inputParams and execute are checked manually.
114 + * Slug is validated separately as the first argument.
115 + * Used internally for validation — inputParams, outputParams, and execute are checked manually.
116 */
117 export const CreateCustomToolBaseSchema = z.object({
102 - slug: z
103 - .string()
104 - .min(1, 'createCustomTool: slug is required')
105 - .refine(s => !s.toUpperCase().startsWith('LOCAL_'), {
106 - message:
107 - 'createCustomTool: slug must not start with "LOCAL_" — this prefix is reserved for internal routing.',
108 - }),
118 name: z.string().min(1, 'createCustomTool: name is required'),
119 description: z.string().min(1, 'createCustomTool: description is required'),
120 /**
112 - * Composio toolkit slug that this tool requires an active connection for.
121 + * Composio toolkit slug that this tool extends (requires an active connection for).
122 * Set this to the toolkit whose auth your tool needs (e.g. `'meta_ads'`, `'gmail'`).
123 * Leave empty for tools that don't need any Composio-managed authentication.
124 */
116 - toolkit: z.string().optional(),
125 + extendsToolkit: z.string().optional(),
126 });
127
128 /** Options for creating a custom tool via `createCustomTool()`. */
@@ -122,25 +131,28 @@ export type CreateCustomToolParams<T extends z.ZodType> = z.infer<
131 > & {
132 /** Zod schema for input parameters */
133 inputParams: T;
134 + /** Optional Zod schema for output parameters (sent to backend for documentation) */
135 + outputParams?: z.ZodType;
136 /** The function that executes the tool */
137 execute: CustomToolExecuteFn<T>;
138 };
139
140 /**
141 * Custom tool definition returned from `createCustomTool()`.
131 - * Pass to `composio.create(userId, { customTools: [...] })` to bind to a session.
142 + * Pass to `composio.create(userId, { experimental: { customTools: [...] } })` to bind to a session.
143 */
144 export interface CustomTool {
145 readonly slug: string;
146 readonly name: string;
147 readonly description: string;
148 /**
138 - * Composio toolkit slug that this tool requires an active connection for.
139 - * Set this to the toolkit whose auth your tool needs (e.g. `'meta_ads'`, `'gmail'`).
149 + * Composio toolkit slug that this tool extends (requires an active connection for).
150 * Undefined means the tool doesn't need any Composio-managed authentication.
151 */
142 - readonly toolkit?: string;
152 + readonly extendsToolkit?: string;
153 readonly inputSchema: Record<string, unknown>;
154 + /** JSON Schema representation of the output (for backend documentation) */
155 + readonly outputSchema?: Record<string, unknown>;
156 /** @internal Original Zod schema — used for runtime input validation (defaults, coercions, transforms) */
157 readonly inputParams: z.ZodType;
158 /** Direct reference to the execute function — useful for testing */
@@ -153,9 +165,54 @@ export interface CustomToolDefinition {
165 name: string;
166 description: string;
167 input_schema: Record<string, unknown>;
156 - toolkit?: string;
168 + output_schema?: Record<string, unknown>;
169 + /** Mapped from `extendsToolkit`. Omitted for standalone tools. */
170 + extends_toolkit?: string;
171 +}
172 +
173 +// ────────────────────────────────────────────────────────────────
174 +// Custom toolkit types
175 +// ────────────────────────────────────────────────────────────────
176 +
177 +/**
178 + * Zod schema for validating the string/scalar fields of createCustomToolkit() options.
179 + * Slug is validated separately as the first argument.
180 + */
181 +export const CreateCustomToolkitBaseSchema = z.object({
182 + name: z.string().min(1, 'createCustomToolkit: name is required'),
183 + description: z.string().min(1, 'createCustomToolkit: description is required'),
184 +});
185 +
186 +/** Options for creating a custom toolkit via `createCustomToolkit()`. */
187 +export type CreateCustomToolkitParams = z.infer<typeof CreateCustomToolkitBaseSchema> & {
188 + /** Tools to include in this toolkit. Must not have `extendsToolkit` set. */
189 + tools: CustomTool[];
190 +};
191 +
192 +/**
193 + * Custom toolkit definition returned from `createCustomToolkit()`.
194 + * Pass to `composio.create(userId, { experimental: { customToolkits: [...] } })`.
195 + */
196 +export interface CustomToolkit {
197 + readonly slug: string;
198 + readonly name: string;
199 + readonly description: string;
200 + readonly tools: readonly CustomTool[];
201 }
202
203 +/** Serialized toolkit definition sent to backend. */
204 +export interface CustomToolkitDefinition {
205 + slug: string;
206 + name: string;
207 + description: string;
208 + /** Nested tools — no extends_toolkit, they inherit the toolkit identity from the parent. */
209 + tools: Omit<CustomToolDefinition, 'extends_toolkit'>[];
210 +}
211 +
212 +// ────────────────────────────────────────────────────────────────
213 +// Internal routing types
214 +// ────────────────────────────────────────────────────────────────
215 +
216 /** @internal Entry in the per-session custom tools routing map. */
217 export type CustomToolsMapEntry = {
218 handle: CustomTool;
ts/packages/core/src/types/toolRouter.types.ts
+41 -9
@@ -3,7 +3,7 @@ import type { BaseComposioProvider } from '../provider/BaseProvider';
3 import { SessionMetaToolOptions } from './modifiers.types';
4 import { ConnectionRequest } from './connectionRequest.types';
5 import type { ToolRouterSessionFilesMount } from '../models/ToolRouterSessionFileMount';
6 -import type { CustomTool } from './customTool.types';
6 +import type { CustomTool, CustomToolkit } from './customTool.types';
7
8 export const MCPServerTypeSchema = z.enum(['http', 'sse']);
9 export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;
@@ -213,15 +213,21 @@ export const ToolRouterCreateSessionConfigSchema = z
213 })
214 .optional()
215 .describe('Configuration for assistive prompt generation'),
216 + customTools: z
217 + .array(z.custom<CustomTool>())
218 + .optional()
219 + .describe(
220 + 'Custom tools to include in this session. Created via createCustomTool() from @composio/core/experimental.'
221 + ),
222 + customToolkits: z
223 + .array(z.custom<CustomToolkit>())
224 + .optional()
225 + .describe(
226 + 'Custom toolkits to include in this session. Created via createCustomToolkit() from @composio/core/experimental.'
227 + ),
228 })
229 .optional()
230 .describe('Experimental features configuration - not stable, may be modified or removed'),
219 - customTools: z
220 - .array(z.custom<CustomTool>())
221 - .optional()
222 - .describe(
223 - 'Custom tools to include in this session. Created via createCustomTool() from @composio/core/experimental.'
224 - ),
231 })
232 .partial()
233 .describe('The config for the tool router session');
@@ -425,6 +431,32 @@ export type ToolRouterSessionExecuteFn = (
431 arguments_?: Record<string, unknown>
432 ) => Promise<ToolRouterSessionExecuteResponse>;
433
434 +export const SessionProxyExecuteParamsSchema = z.object({
435 + /** The toolkit whose connected account to use for auth (e.g. 'gmail', 'github') */
436 + toolkit: z.string(),
437 + /** The API endpoint URL to call */
438 + endpoint: z.string(),
439 + /** HTTP method */
440 + method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']),
441 + /** Request body (for POST/PUT/PATCH) */
442 + body: z.unknown().optional(),
443 + /** Query params or headers to include */
444 + parameters: z
445 + .array(
446 + z.object({
447 + in: z.enum(['query', 'header']),
448 + name: z.string(),
449 + value: z.union([z.string(), z.number()]),
450 + })
451 + )
452 + .optional(),
453 +});
454 +export type SessionProxyExecuteParams = z.infer<typeof SessionProxyExecuteParamsSchema>;
455 +
456 +export type ToolRouterSessionProxyExecuteFn = (
457 + params: SessionProxyExecuteParams
458 +) => Promise<ToolRouterSessionExecuteResponse>;
459 +
460 /** Session type returned by ToolRouter.create() and ToolRouter.use() */
461 export interface Session<
462 TToolCollection,
@@ -440,8 +472,8 @@ export interface Session<
472 search: ToolRouterSessionSearchFn;
473 /** Execute a tool within the session */
474 execute: ToolRouterSessionExecuteFn;
443 - /** Get provider-wrapped custom tools for MCP flows */
444 - localTools: () => Promise<ReturnType<TProvider['wrapTools']>>;
475 + /** Proxy an API call through Composio's auth layer using the session's connected account */
476 + proxyExecute: ToolRouterSessionProxyExecuteFn;
477 /** Experimental features (files, assistive prompt, etc.) */
478 experimental: SessionExperimental;
479 }
ts/packages/core/test/models/customTool.test.ts
+343 -55
@@ -1,8 +1,15 @@
1 import { describe, it, expect, vi, beforeEach } from 'vitest';
2 import { z } from 'zod/v3';
3 -import { createCustomTool, buildCustomToolsMap, serializeCustomTools, LOCAL_TOOL_PREFIX } from '../../src/models/CustomTool';
3 +import {
4 + createCustomTool,
5 + createCustomToolkit,
6 + buildCustomToolsMap,
7 + serializeCustomTools,
8 + serializeCustomToolkits,
9 + LOCAL_TOOL_PREFIX,
10 +} from '../../src/models/CustomTool';
11 import { SessionContextImpl } from '../../src/models/SessionContext';
5 -import type { CustomTool, SessionContext } from '../../src/types/customTool.types';
12 +import type { CustomTool, CustomToolkit, SessionContext } from '../../src/types/customTool.types';
13
14 // ────────────────────────────────────────────────────────────────
15 // createCustomTool() factory
@@ -10,7 +17,6 @@ import type { CustomTool, SessionContext } from '../../src/types/customTool.type
17
18 describe('createCustomTool', () => {
19 const baseOptions = {
13 - slug: 'GET_USER_CONTEXT',
20 name: 'Get user context',
21 description: 'Retrieve what we know about a user',
22 inputParams: z.object({
@@ -20,12 +26,12 @@ describe('createCustomTool', () => {
26 };
27
28 it('should return a valid tool with correct fields', () => {
23 - const tool = createCustomTool(baseOptions);
29 + const tool = createCustomTool('GET_USER_CONTEXT', baseOptions);
30
31 expect(tool.slug).toBe('GET_USER_CONTEXT');
32 expect(tool.name).toBe('Get user context');
33 expect(tool.description).toBe('Retrieve what we know about a user');
28 - expect(tool.toolkit).toBeUndefined();
34 + expect(tool.extendsToolkit).toBeUndefined();
35 expect(tool.execute).toBe(baseOptions.execute);
36 expect(tool.inputSchema).toMatchObject({
37 type: 'object',
@@ -37,13 +43,37 @@ describe('createCustomTool', () => {
43 expect(tool.inputParams).toBe(baseOptions.inputParams);
44 });
45
40 - it('should include toolkit when provided', () => {
41 - const tool = createCustomTool({ ...baseOptions, toolkit: 'meta_ads' });
42 - expect(tool.toolkit).toBe('meta_ads');
46 + it('should include extendsToolkit when provided', () => {
47 + const tool = createCustomTool('GET_AD_ACCOUNTS', { ...baseOptions, extendsToolkit: 'meta_ads' });
48 + expect(tool.extendsToolkit).toBe('meta_ads');
49 + });
50 +
51 + it('should convert outputParams to JSON Schema when provided', () => {
52 + const tool = createCustomTool('WITH_OUTPUT', {
53 + ...baseOptions,
54 + outputParams: z.object({
55 + result: z.string(),
56 + count: z.number(),
57 + }),
58 + });
59 +
60 + expect(tool.outputSchema).toMatchObject({
61 + type: 'object',
62 + properties: {
63 + result: { type: 'string' },
64 + count: { type: 'number' },
65 + },
66 + required: ['result', 'count'],
67 + });
68 + });
69 +
70 + it('should not have outputSchema when outputParams is not provided', () => {
71 + const tool = createCustomTool('NO_OUTPUT', baseOptions);
72 + expect(tool.outputSchema).toBeUndefined();
73 });
74
75 it('should convert Zod schema with optional fields correctly', () => {
46 - const tool = createCustomTool({
76 + const tool = createCustomTool('OPT_FIELDS', {
77 ...baseOptions,
78 inputParams: z.object({
79 required_field: z.string(),
@@ -62,7 +92,7 @@ describe('createCustomTool', () => {
92 });
93
94 it('should convert Zod schema with defaults correctly', () => {
65 - const tool = createCustomTool({
95 + const tool = createCustomTool('DEFAULTS', {
96 ...baseOptions,
97 inputParams: z.object({
98 category: z.string().default('all'),
@@ -77,41 +107,53 @@ describe('createCustomTool', () => {
107 });
108 });
109
80 - describe('validation', () => {
81 - it('should throw if slug is missing', () => {
82 - expect(() => createCustomTool({ ...baseOptions, slug: '' })).toThrow('slug is required');
110 + describe('slug validation', () => {
111 + it('should throw if slug is empty', () => {
112 + expect(() => createCustomTool('', baseOptions)).toThrow('slug is required');
113 });
114
115 it('should throw if slug starts with LOCAL_ prefix', () => {
86 - expect(() => createCustomTool({ ...baseOptions, slug: 'LOCAL_MY_TOOL' })).toThrow(
87 - /LOCAL_/
88 - );
116 + expect(() => createCustomTool('LOCAL_MY_TOOL', baseOptions)).toThrow(/LOCAL_/);
117 });
118
119 it('should throw if slug starts with local_ prefix (case-insensitive)', () => {
92 - expect(() => createCustomTool({ ...baseOptions, slug: 'local_something' })).toThrow(
93 - /LOCAL_/
94 - );
120 + expect(() => createCustomTool('local_something', baseOptions)).toThrow(/LOCAL_/);
121 });
122
123 + it('should throw if slug contains invalid characters', () => {
124 + expect(() => createCustomTool('MY TOOL', baseOptions)).toThrow(/alphanumeric/);
125 + expect(() => createCustomTool('MY.TOOL', baseOptions)).toThrow(/alphanumeric/);
126 + expect(() => createCustomTool('MY@TOOL', baseOptions)).toThrow(/alphanumeric/);
127 + });
128 +
129 + it('should allow underscores and hyphens in slug', () => {
130 + const tool1 = createCustomTool('MY_TOOL', baseOptions);
131 + expect(tool1.slug).toBe('MY_TOOL');
132 +
133 + const tool2 = createCustomTool('my-tool', baseOptions);
134 + expect(tool2.slug).toBe('my-tool');
135 + });
136 + });
137 +
138 + describe('other validation', () => {
139 it('should throw if name is missing', () => {
98 - expect(() => createCustomTool({ ...baseOptions, name: '' })).toThrow('name is required');
140 + expect(() => createCustomTool('SLUG', { ...baseOptions, name: '' })).toThrow('name is required');
141 });
142
143 it('should throw if description is missing', () => {
102 - expect(() => createCustomTool({ ...baseOptions, description: '' })).toThrow(
144 + expect(() => createCustomTool('SLUG', { ...baseOptions, description: '' })).toThrow(
145 'description is required'
146 );
147 });
148
149 it('should throw if inputParams is missing', () => {
108 - expect(() => createCustomTool({ ...baseOptions, inputParams: null as any })).toThrow(
150 + expect(() => createCustomTool('SLUG', { ...baseOptions, inputParams: null as any })).toThrow(
151 'inputParams is required'
152 );
153 });
154
155 it('should throw if execute is not a function', () => {
114 - expect(() => createCustomTool({ ...baseOptions, execute: 'not-fn' as any })).toThrow(
156 + expect(() => createCustomTool('SLUG', { ...baseOptions, execute: 'not-fn' as any })).toThrow(
157 'execute must be a function'
158 );
159 });
@@ -121,12 +163,11 @@ describe('createCustomTool', () => {
163 it('should allow no-session execute (input only)', async () => {
164 const noSessionExecute = vi.fn().mockResolvedValue({ result: 42 });
165
124 - const tool = createCustomTool({
166 + const tool = createCustomTool('NO_SESSION', {
167 ...baseOptions,
168 execute: noSessionExecute,
169 });
170
129 - // Call without session — JS ignores extra params
171 const result = await tool.execute({ category: 'test' } as any);
172 expect(result.result).toBe(42);
173 expect(noSessionExecute).toHaveBeenCalledWith({ category: 'test' });
@@ -135,7 +176,7 @@ describe('createCustomTool', () => {
176 it('should allow session-based execute (input + session)', async () => {
177 const sessionExecute = vi.fn().mockResolvedValue({ userId: 'u1' });
178
138 - const tool = createCustomTool({
179 + const tool = createCustomTool('WITH_SESSION', {
180 ...baseOptions,
181 execute: sessionExecute,
182 });
@@ -153,49 +194,204 @@ describe('createCustomTool', () => {
194 });
195 });
196
197 +// ────────────────────────────────────────────────────────────────
198 +// createCustomToolkit() factory
199 +// ────────────────────────────────────────────────────────────────
200 +
201 +describe('createCustomToolkit', () => {
202 + const baseTool = createCustomTool('GREP', {
203 + name: 'Grep',
204 + description: 'Search files',
205 + inputParams: z.object({ pattern: z.string() }),
206 + execute: vi.fn().mockResolvedValue({}),
207 + });
208 +
209 + it('should return a valid toolkit with correct fields', () => {
210 + const tk = createCustomToolkit('DEV_TOOLS', {
211 + name: 'Dev Tools',
212 + description: 'Local dev utilities',
213 + tools: [baseTool],
214 + });
215 +
216 + expect(tk.slug).toBe('DEV_TOOLS');
217 + expect(tk.name).toBe('Dev Tools');
218 + expect(tk.description).toBe('Local dev utilities');
219 + expect(tk.tools).toHaveLength(1);
220 + expect(tk.tools[0].slug).toBe('GREP');
221 + });
222 +
223 + it('should throw if slug is empty', () => {
224 + expect(() =>
225 + createCustomToolkit('', { name: 'X', description: 'X', tools: [baseTool] })
226 + ).toThrow('slug is required');
227 + });
228 +
229 + it('should throw if slug starts with LOCAL_', () => {
230 + expect(() =>
231 + createCustomToolkit('LOCAL_TK', { name: 'X', description: 'X', tools: [baseTool] })
232 + ).toThrow(/LOCAL_/);
233 + });
234 +
235 + it('should throw if slug contains invalid characters', () => {
236 + expect(() =>
237 + createCustomToolkit('MY TOOLKIT', { name: 'X', description: 'X', tools: [baseTool] })
238 + ).toThrow(/alphanumeric/);
239 + });
240 +
241 + it('should throw if name is missing', () => {
242 + expect(() =>
243 + createCustomToolkit('TK', { name: '', description: 'X', tools: [baseTool] })
244 + ).toThrow('name is required');
245 + });
246 +
247 + it('should throw if description is missing', () => {
248 + expect(() =>
249 + createCustomToolkit('TK', { name: 'X', description: '', tools: [baseTool] })
250 + ).toThrow('description is required');
251 + });
252 +
253 + it('should throw if tools array is empty', () => {
254 + expect(() =>
255 + createCustomToolkit('TK', { name: 'X', description: 'X', tools: [] })
256 + ).toThrow('at least one tool is required');
257 + });
258 +
259 + it('should reject tools with extendsToolkit set', () => {
260 + const extendsTool = createCustomTool('EXTENDS_TOOL', {
261 + name: 'Extends',
262 + description: 'Has extendsToolkit',
263 + extendsToolkit: 'gmail',
264 + inputParams: z.object({}),
265 + execute: vi.fn().mockResolvedValue({}),
266 + });
267 +
268 + expect(() =>
269 + createCustomToolkit('TK', { name: 'X', description: 'X', tools: [extendsTool] })
270 + ).toThrow('extendsToolkit');
271 + });
272 +});
273 +
274 // ────────────────────────────────────────────────────────────────
275 // buildCustomToolsMap()
276 // ────────────────────────────────────────────────────────────────
277
278 describe('buildCustomToolsMap', () => {
161 - const makeTool = (slug: string): CustomTool => ({
279 + const makeTool = (slug: string, extendsToolkit?: string): CustomTool => ({
280 slug,
281 name: `Tool ${slug}`,
282 description: `Description for ${slug}`,
283 + extendsToolkit,
284 inputSchema: { type: 'object', properties: {} },
285 inputParams: z.object({}),
286 execute: vi.fn(),
287 });
288
170 - it('should create maps with both prefixed and original slug keys', () => {
171 - const tools = [makeTool('MY_TOOL'), makeTool('OTHER_TOOL')];
172 - const map = buildCustomToolsMap(tools);
289 + describe('standalone tools (no extendsToolkit)', () => {
290 + it('should prefix as LOCAL_<SLUG>', () => {
291 + const map = buildCustomToolsMap([makeTool('MY_TOOL')]);
292 +
293 + expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
294 + expect(map.byOriginal.has('MY_TOOL')).toBe(true);
295 + });
296 +
297 + it('should handle case-insensitive slugs (uppercased internally)', () => {
298 + const map = buildCustomToolsMap([makeTool('my_tool')]);
299 +
300 + expect(map.byOriginal.has('MY_TOOL')).toBe(true);
301 + expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
302 + });
303 + });
304 +
305 + describe('tools with extendsToolkit', () => {
306 + it('should prefix as LOCAL_<EXTENDS_TOOLKIT>_<SLUG>', () => {
307 + const map = buildCustomToolsMap([makeTool('GET_EMAILS', 'gmail')]);
308 +
309 + expect(map.byPrefixed.has('LOCAL_GMAIL_GET_EMAILS')).toBe(true);
310 + expect(map.byOriginal.has('GET_EMAILS')).toBe(true);
311 + });
312 + });
313
174 - expect(map.byPrefixed.size).toBe(2);
175 - expect(map.byOriginal.size).toBe(2);
314 + describe('toolkit tools', () => {
315 + it('should prefix as LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>', () => {
316 + const sed = makeTool('SED');
317 + const tk: CustomToolkit = {
318 + slug: 'DEV_TOOLS',
319 + name: 'Dev Tools',
320 + description: 'Utilities',
321 + tools: [sed],
322 + };
323
177 - // Prefixed lookup
178 - expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
179 - expect(map.byPrefixed.has('LOCAL_OTHER_TOOL')).toBe(true);
324 + const map = buildCustomToolsMap([], [tk]);
325
181 - // Original lookup
182 - expect(map.byOriginal.has('MY_TOOL')).toBe(true);
183 - expect(map.byOriginal.has('OTHER_TOOL')).toBe(true);
326 + expect(map.byPrefixed.has('LOCAL_DEV_TOOLS_SED')).toBe(true);
327 + expect(map.byOriginal.has('SED')).toBe(true);
328 + });
329 });
330
186 - it('should handle case-insensitive slugs (uppercased internally)', () => {
187 - const tool = makeTool('my_tool');
188 - const map = buildCustomToolsMap([tool]);
331 + describe('mixed tools and toolkits', () => {
332 + it('should handle standalone + toolkit tools together', () => {
333 + const grep = makeTool('GREP');
334 + const sed = makeTool('SED');
335 + const tk: CustomToolkit = {
336 + slug: 'DEV_TOOLS',
337 + name: 'Dev Tools',
338 + description: 'Utilities',
339 + tools: [sed],
340 + };
341 +
342 + const map = buildCustomToolsMap([grep], [tk]);
343
190 - expect(map.byOriginal.has('MY_TOOL')).toBe(true);
191 - expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
344 + expect(map.byPrefixed.size).toBe(2);
345 + expect(map.byPrefixed.has('LOCAL_GREP')).toBe(true);
346 + expect(map.byPrefixed.has('LOCAL_DEV_TOOLS_SED')).toBe(true);
347 + });
348 });
349
194 - it('should throw on duplicate slugs', () => {
195 - const tools = [makeTool('DUPE'), makeTool('DUPE')];
196 - expect(() => buildCustomToolsMap(tools)).toThrow('duplicate slug "DUPE"');
350 + describe('collision detection', () => {
351 + it('should throw on duplicate standalone slugs', () => {
352 + expect(() => buildCustomToolsMap([makeTool('DUPE'), makeTool('DUPE')])).toThrow(
353 + 'collision'
354 + );
355 + });
356 +
357 + it('should throw on cross-group collision (standalone vs toolkit same original slug)', () => {
358 + const standalone = makeTool('SED');
359 + const tkTool = makeTool('SED');
360 + const tk: CustomToolkit = {
361 + slug: 'DEV_TOOLS',
362 + name: 'Dev Tools',
363 + description: 'Utilities',
364 + tools: [tkTool],
365 + };
366 +
367 + expect(() => buildCustomToolsMap([standalone], [tk])).toThrow('collision');
368 + });
369 });
370
371 + describe('length validation', () => {
372 + it('should throw when prefixed slug exceeds 60 characters with contextual error', () => {
373 + const longSlug = 'A'.repeat(56); // LOCAL_ + 56 = 62 > 60
374 + expect(() => buildCustomToolsMap([makeTool(longSlug)])).toThrow('too long');
375 + });
376 +
377 + it('should show available length in error for toolkit tools', () => {
378 + const longSlug = 'A'.repeat(50); // LOCAL_DEV_TOOLS_ + 50 = 66 > 60
379 + const tk: CustomToolkit = {
380 + slug: 'DEV_TOOLS',
381 + name: 'Dev Tools',
382 + description: 'Utilities',
383 + tools: [makeTool(longSlug)],
384 + };
385 +
386 + expect(() => buildCustomToolsMap([], [tk])).toThrow(/Shorten the slug to at most/);
387 + });
388 +
389 + it('should accept slugs that fit within 60 chars', () => {
390 + const slug = 'A'.repeat(54); // LOCAL_ + 54 = 60 exactly
391 + const map = buildCustomToolsMap([makeTool(slug)]);
392 + expect(map.byPrefixed.size).toBe(1);
393 + });
394 + });
395 });
396
397 // ────────────────────────────────────────────────────────────────
@@ -203,12 +399,12 @@ describe('buildCustomToolsMap', () => {
399 // ────────────────────────────────────────────────────────────────
400
401 describe('serializeCustomTools', () => {
206 - it('should serialize tools into backend format', () => {
402 + it('should serialize tools with extendsToolkit as extends_toolkit', () => {
403 const tool: CustomTool = {
404 slug: 'GET_DATA',
405 name: 'Get Data',
406 description: 'Gets some data',
211 - toolkit: 'my_toolkit',
407 + extendsToolkit: 'my_toolkit',
408 inputSchema: { type: 'object', properties: { id: { type: 'string' } } },
409 inputParams: z.object({ id: z.string() }),
410 execute: vi.fn(),
@@ -221,13 +417,13 @@ describe('serializeCustomTools', () => {
417 slug: 'GET_DATA',
418 name: 'Get Data',
419 description: 'Gets some data',
224 - toolkit: 'my_toolkit',
420 + extends_toolkit: 'my_toolkit',
421 input_schema: { type: 'object', properties: { id: { type: 'string' } } },
422 },
423 ]);
424 });
425
230 - it('should omit toolkit when not provided', () => {
426 + it('should omit extends_toolkit when extendsToolkit is not provided', () => {
427 const tool: CustomTool = {
428 slug: 'NO_TOOLKIT',
429 name: 'No Toolkit',
@@ -238,7 +434,66 @@ describe('serializeCustomTools', () => {
434 };
435
436 const result = serializeCustomTools([tool]);
241 - expect(result[0]).not.toHaveProperty('toolkit');
437 + expect(result[0]).not.toHaveProperty('extends_toolkit');
438 + });
439 +
440 + it('should include output_schema when outputSchema is present', () => {
441 + const tool: CustomTool = {
442 + slug: 'WITH_OUTPUT',
443 + name: 'With Output',
444 + description: 'Has output schema',
445 + inputSchema: { type: 'object', properties: {} },
446 + outputSchema: { type: 'object', properties: { result: { type: 'string' } } },
447 + inputParams: z.object({}),
448 + execute: vi.fn(),
449 + };
450 +
451 + const result = serializeCustomTools([tool]);
452 + expect(result[0].output_schema).toEqual({
453 + type: 'object',
454 + properties: { result: { type: 'string' } },
455 + });
456 + });
457 +});
458 +
459 +// ────────────────────────────────────────────────────────────────
460 +// serializeCustomToolkits()
461 +// ────────────────────────────────────────────────────────────────
462 +
463 +describe('serializeCustomToolkits', () => {
464 + it('should serialize toolkits with their tools', () => {
465 + const tool: CustomTool = {
466 + slug: 'SED',
467 + name: 'Sed Replace',
468 + description: 'Find and replace',
469 + inputSchema: { type: 'object', properties: { pattern: { type: 'string' } } },
470 + inputParams: z.object({ pattern: z.string() }),
471 + execute: vi.fn(),
472 + };
473 + const tk: CustomToolkit = {
474 + slug: 'DEV_TOOLS',
475 + name: 'Dev Tools',
476 + description: 'Dev utilities',
477 + tools: [tool],
478 + };
479 +
480 + const result = serializeCustomToolkits([tk]);
481 +
482 + expect(result).toEqual([
483 + {
484 + slug: 'DEV_TOOLS',
485 + name: 'Dev Tools',
486 + description: 'Dev utilities',
487 + tools: [
488 + {
489 + slug: 'SED',
490 + name: 'Sed Replace',
491 + description: 'Find and replace',
492 + input_schema: { type: 'object', properties: { pattern: { type: 'string' } } },
493 + },
494 + ],
495 + },
496 + ]);
497 });
498 });
499
@@ -299,11 +554,45 @@ describe('SessionContextImpl', () => {
554 expect(result.error).toBe('something went wrong');
555 });
556
302 - it('should throw on proxyExecute() (not yet implemented)', async () => {
557 + it('should call session proxy_execute endpoint via proxyExecute()', async () => {
558 + const mockPost = vi.fn().mockResolvedValue({
559 + data: { proxy_result: true },
560 + error: null,
561 + log_id: 'log_proxy',
562 + });
563 + const clientWithPost = { ...mockClient, post: mockPost };
564 + const ctx = new SessionContextImpl(clientWithPost as any, 'user_1', 'sess_1');
565 +
566 + const result = await ctx.proxyExecute({
567 + toolkit: 'github',
568 + endpoint: 'https://api.github.com/user',
569 + method: 'GET',
570 + parameters: [{ in: 'header' as const, name: 'X-Custom', value: 'val' }],
571 + });
572 +
573 + expect(mockPost).toHaveBeenCalledWith(
574 + '/api/v3/tool_router/session/sess_1/proxy_execute',
575 + {
576 + body: {
577 + toolkit_slug: 'github',
578 + endpoint: 'https://api.github.com/user',
579 + method: 'GET',
580 + parameters: [{ name: 'X-Custom', type: 'header', value: 'val' }],
581 + },
582 + }
583 + );
584 + expect(result).toEqual({
585 + data: { proxy_result: true },
586 + error: null,
587 + successful: true,
588 + });
589 + });
590 +
591 + it('should throw on proxyExecute() with invalid params', async () => {
592 const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
593 await expect(
305 - ctx.proxyExecute({ endpoint: '/test', method: 'GET' })
306 - ).rejects.toThrow('proxyExecute is not yet implemented');
594 + ctx.proxyExecute({ toolkit: 'github', endpoint: '/test', method: 'INVALID' as any })
595 + ).rejects.toThrow('Invalid proxy execute parameters');
596 });
597
598 describe('sibling local tool routing', () => {
@@ -317,7 +606,6 @@ describe('SessionContextImpl', () => {
606
607 expect(tryLocalExecute).toHaveBeenCalledWith('SIBLING_TOOL', { key: 'val' });
608 expect(result).toEqual({ data: { local: true }, error: null, successful: true });
320 - // Should NOT call remote
609 expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
610 });
611
ts/packages/core/test/models/customToolRouting.test.ts
+48 -189
@@ -65,8 +65,7 @@ const createMockClient = () => ({
65 // Execute returns data directly (simplified API)
66 const localExecute = vi.fn().mockResolvedValue({ local_result: true });
67
68 -const customToolHandle = createCustomTool({
69 - slug: 'GET_USER_CONTEXT',
68 +const customToolHandle = createCustomTool('GET_USER_CONTEXT', {
69 name: 'Get user context',
70 description: 'Retrieve user preferences',
71 inputParams: z.object({ category: z.string() }),
@@ -77,11 +76,10 @@ const sessionExecute = vi.fn().mockImplementation(async (input: any, session: an
76 userId: session.userId,
77 }));
78
80 -const sessionToolHandle = createCustomTool({
81 - slug: 'GET_AD_ACCOUNTS',
79 +const sessionToolHandle = createCustomTool('GET_AD_ACCOUNTS', {
80 name: 'Get ad accounts',
81 description: 'Get ad account IDs',
84 - toolkit: 'meta_ads',
82 + extendsToolkit: 'meta_ads',
83 inputParams: z.object({ fields: z.string() }),
84 execute: sessionExecute,
85 });
@@ -113,7 +111,7 @@ const captureExecuteFn = (provider: MockProvider) => {
111 };
112
113 // ────────────────────────────────────────────────────────────────
116 -// ToolRouter.create() with customTools
114 +// ToolRouter.create() with customTools under experimental
115 // ────────────────────────────────────────────────────────────────
116
117 describe('ToolRouter.create() with customTools', () => {
@@ -129,14 +127,16 @@ describe('ToolRouter.create() with customTools', () => {
127 });
128 });
129
132 - it('should send custom_tools in the create payload', async () => {
130 + it('should send custom_tools under experimental in the create payload', async () => {
131 await router.create('user_1', {
132 toolkits: ['gmail'],
135 - customTools: [customToolHandle],
133 + experimental: {
134 + customTools: [customToolHandle],
135 + },
136 });
137
138 const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
139 - expect(payload.custom_tools).toEqual([
139 + expect(payload.experimental.custom_tools).toEqual([
140 {
141 slug: 'GET_USER_CONTEXT',
142 name: 'Get user context',
@@ -146,27 +146,33 @@ describe('ToolRouter.create() with customTools', () => {
146 ]);
147 });
148
149 - it('should include toolkit in custom_tools when toolkit is present', async () => {
149 + it('should include extendsToolkit as extends_toolkit in serialized custom_tools', async () => {
150 await router.create('user_1', {
151 - customTools: [sessionToolHandle],
151 + experimental: {
152 + customTools: [sessionToolHandle],
153 + },
154 });
155
156 const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
155 - expect(payload.custom_tools[0].toolkit).toBe('meta_ads');
157 + expect(payload.experimental.custom_tools[0].extends_toolkit).toBe('meta_ads');
158 });
159
158 - it('should not send custom_tools when customTools is omitted or empty', async () => {
160 + it('should not send experimental.custom_tools when customTools is omitted or empty', async () => {
161 await router.create('user_1', { toolkits: ['gmail'] });
160 - expect(mockClient.toolRouter.session.create.mock.calls[0][0].custom_tools).toBeUndefined();
162 + const payload1 = mockClient.toolRouter.session.create.mock.calls[0][0];
163 + expect(payload1.experimental).toBeUndefined();
164
165 vi.clearAllMocks();
163 - await router.create('user_1', { customTools: [] });
164 - expect(mockClient.toolRouter.session.create.mock.calls[0][0].custom_tools).toBeUndefined();
166 + await router.create('user_1', { experimental: { customTools: [] } });
167 + const payload2 = mockClient.toolRouter.session.create.mock.calls[0][0];
168 + expect(payload2.experimental).toBeUndefined();
169 });
170
171 it('should return a session with the correct sessionId', async () => {
172 const session = await router.create('user_1', {
169 - customTools: [customToolHandle],
173 + experimental: {
174 + customTools: [customToolHandle],
175 + },
176 });
177
178 expect(session.sessionId).toBe('sess_123');
@@ -210,14 +216,12 @@ describe('ToolRouterSession execution routing', () => {
216
217 const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
218
213 - // User returns data directly, SDK wraps it
219 expect(result.data).toEqual({ local_result: true });
220 expect(result.logId).toBe('local');
221 expect(localExecute).toHaveBeenCalledWith(
222 { category: 'prefs' },
223 expect.objectContaining({ userId: 'user_1' })
224 );
220 - // Should NOT call remote
225 expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
226 });
227
@@ -231,6 +235,17 @@ describe('ToolRouterSession execution routing', () => {
235 expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
236 });
237
238 + it('should route extendsToolkit tool by prefixed slug', async () => {
239 + const session = createSession(mockClient, [sessionToolHandle]);
240 +
241 + // sessionToolHandle has extendsToolkit: 'meta_ads' → LOCAL_META_ADS_GET_AD_ACCOUNTS
242 + const result = await session.execute('LOCAL_META_ADS_GET_AD_ACCOUNTS', { fields: 'id' });
243 +
244 + expect(result.data).toEqual({ userId: 'user_1' });
245 + expect(sessionExecute).toHaveBeenCalled();
246 + expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
247 + });
248 +
249 it('should be case-insensitive for local tool lookup', async () => {
250 const session = createSession(mockClient, [customToolHandle]);
251
@@ -276,14 +291,12 @@ describe('ToolRouterSession execution routing', () => {
291 });
292
293 it('should provide a working execute() on SessionContext for remote tools', async () => {
279 - // Tool that calls a remote tool via session.execute()
294 const chainedExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
295 const inner = await session.execute('GMAIL_SEND_EMAIL', { to: input.to });
296 return { inner_result: inner.data };
297 });
298
285 - const chainedTool = createCustomTool({
286 - slug: 'CHAINED_TOOL',
299 + const chainedTool = createCustomTool('CHAINED_TOOL', {
300 name: 'Chained',
301 description: 'Calls another tool',
302 inputParams: z.object({ to: z.string() }),
@@ -293,7 +306,6 @@ describe('ToolRouterSession execution routing', () => {
306 const session = createSession(mockClient, [chainedTool]);
307 await session.execute('CHAINED_TOOL', { to: 'test@test.com' });
308
296 - // The chained tool should have called session.execute, which calls the API
309 expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_123', {
310 tool_slug: 'GMAIL_SEND_EMAIL',
311 arguments: { to: 'test@test.com' },
@@ -301,23 +313,19 @@ describe('ToolRouterSession execution routing', () => {
313 });
314
315 it('should route sibling local tools in-process without hitting the API', async () => {
304 - // Tool B — a sibling local tool
316 const siblingExecute = vi.fn().mockResolvedValue({ siblingData: 'from-B' });
306 - const toolB = createCustomTool({
307 - slug: 'TOOL_B',
317 + const toolB = createCustomTool('TOOL_B', {
318 name: 'Tool B',
319 description: 'Sibling tool',
320 inputParams: z.object({ key: z.string() }),
321 execute: siblingExecute,
322 });
323
314 - // Tool A — calls Tool B via session.execute()
324 const toolAExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
325 const inner = await session.execute('TOOL_B', { key: input.value });
326 return { fromA: true, fromB: inner.data };
327 });
319 - const toolA = createCustomTool({
320 - slug: 'TOOL_A',
328 + const toolA = createCustomTool('TOOL_A', {
329 name: 'Tool A',
330 description: 'Calls sibling tool B',
331 inputParams: z.object({ value: z.string() }),
@@ -327,25 +335,21 @@ describe('ToolRouterSession execution routing', () => {
335 const session = createSession(mockClient, [toolA, toolB]);
336 const result = await session.execute('TOOL_A', { value: 'hello' });
337
330 - // Tool B should have been called in-process
338 expect(siblingExecute).toHaveBeenCalledWith(
339 { key: 'hello' },
340 expect.objectContaining({ userId: 'user_1' })
341 );
335 - // Result should contain data from both tools
342 expect(result.data).toEqual({
343 fromA: true,
344 fromB: { siblingData: 'from-B' },
345 });
340 - // Should NOT have called the remote API for Tool B
346 expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
347 });
348 });
349
350 describe('session.execute() — error handling', () => {
351 it('should catch errors thrown by execute function and return error response', async () => {
347 - const throwingTool = createCustomTool({
348 - slug: 'THROWING_TOOL',
352 + const throwingTool = createCustomTool('THROWING_TOOL', {
353 name: 'Throwing',
354 description: 'Throws an error',
355 inputParams: z.object({}),
@@ -366,8 +370,7 @@ describe('ToolRouterSession execution routing', () => {
370 category: input.category,
371 }));
372
369 - const toolWithDefaults = createCustomTool({
370 - slug: 'DEFAULTS_TOOL',
373 + const toolWithDefaults = createCustomTool('DEFAULTS_TOOL', {
374 name: 'Defaults',
375 description: 'Tool with default values',
376 inputParams: z.object({ category: z.string().default('all') }),
@@ -377,7 +380,6 @@ describe('ToolRouterSession execution routing', () => {
380 const session = createSession(mockClient, [toolWithDefaults]);
381 const result = await session.execute('DEFAULTS_TOOL', {});
382
380 - // Zod default should be applied
383 expect(defaultExecute).toHaveBeenCalledWith(
384 { category: 'all' },
385 expect.anything()
@@ -386,8 +388,7 @@ describe('ToolRouterSession execution routing', () => {
388 });
389
390 it('should return validation error for invalid input', async () => {
389 - const strictTool = createCustomTool({
390 - slug: 'STRICT_TOOL',
391 + const strictTool = createCustomTool('STRICT_TOOL', {
392 name: 'Strict',
393 description: 'Tool with strict input',
394 inputParams: z.object({ count: z.number() }),
@@ -402,8 +403,7 @@ describe('ToolRouterSession execution routing', () => {
403 });
404
405 it('should handle non-Error throws gracefully', async () => {
405 - const throwingTool = createCustomTool({
406 - slug: 'STRING_THROW',
406 + const throwingTool = createCustomTool('STRING_THROW', {
407 name: 'String throw',
408 description: 'Throws a string',
409 inputParams: z.object({}),
@@ -479,7 +479,6 @@ describe('ToolRouterSession execution routing', () => {
479 sync_response_to_workbench: false,
480 });
481
482 - // All remote — goes to executeMetaTool
482 expect(result.data).toEqual({ remote: true });
483 expect(localExecute).not.toHaveBeenCalled();
484 });
@@ -496,7 +495,6 @@ describe('ToolRouterSession execution routing', () => {
495 queries: [{ use_case: 'send email' }],
496 });
497
499 - // COMPOSIO_SEARCH_TOOLS always goes remote
498 expect(result.data).toEqual({ remote: true });
499 });
500
@@ -506,18 +504,15 @@ describe('ToolRouterSession execution routing', () => {
504 { apiKey: 'key', provider: new MockProvider() },
505 'sess_123',
506 { type: 'http' as const, url: 'https://mcp.example.com/sess_123' }
509 - // No customToolsMap, no userId
507 );
508
509 const result = await session.tools();
510
514 - // Should use the standard path
511 expect(result).toBe('wrapped-tools');
512 });
513 });
514
515 describe('COMPOSIO_MULTI_EXECUTE_TOOL — detailed split/merge behavior', () => {
520 - /** Helper: set up provider + session + capture executeFn + get latest Tools mock */
516 const setupMultiExecute = async (
517 client: ReturnType<typeof createMockClient>,
518 customTools: CustomTool[]
@@ -533,7 +528,6 @@ describe('ToolRouterSession execution routing', () => {
528 return { executeFn, toolsInstance, provider, session };
529 };
530
536 - /** Build a backend-shaped results[] response */
531 const backendResponse = (
532 results: Array<{ tool_slug: string; data: any; error?: string }>,
533 ) => {
@@ -560,7 +554,6 @@ describe('ToolRouterSession execution routing', () => {
554 };
555 };
556
563 - /** Find a local tool result in the results[] array by slug */
557 const findResult = (results: any[], slug: string) =>
558 results.find((r: any) => r.tool_slug === slug);
559
@@ -579,11 +572,9 @@ describe('ToolRouterSession execution routing', () => {
572 sync_response_to_workbench: false,
573 });
574
582 - // Results is an array with both remote and local entries
575 const { results } = result.data;
576 expect(results).toHaveLength(2);
577
586 - // Remote result comes first (from backend), local appended after
578 const remote = findResult(results, 'GMAIL_SEND_EMAIL');
579 const local = findResult(results, 'LOCAL_GET_USER_CONTEXT');
580 expect(remote.response.data).toEqual({ sent: true });
@@ -597,7 +588,7 @@ describe('ToolRouterSession execution routing', () => {
588 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
589 tools: [
590 { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'batch' } },
600 - { tool_slug: 'LOCAL_GET_AD_ACCOUNTS', arguments: { fields: 'id,name' } },
591 + { tool_slug: 'LOCAL_META_ADS_GET_AD_ACCOUNTS', arguments: { fields: 'id,name' } },
592 ],
593 sync_response_to_workbench: false,
594 });
@@ -614,7 +605,7 @@ describe('ToolRouterSession execution routing', () => {
605 const { results } = result.data;
606 expect(results).toHaveLength(2);
607 expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();
617 - expect(findResult(results, 'LOCAL_GET_AD_ACCOUNTS')).toBeDefined();
608 + expect(findResult(results, 'LOCAL_META_ADS_GET_AD_ACCOUNTS')).toBeDefined();
609 });
610
611 it('should handle mixed batch with multiple locals + multiple remotes', async () => {
@@ -634,21 +625,19 @@ describe('ToolRouterSession execution routing', () => {
625 tools: [
626 { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'x' } },
627 { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } },
637 - { tool_slug: 'LOCAL_GET_AD_ACCOUNTS', arguments: { fields: 'id' } },
628 + { tool_slug: 'LOCAL_META_ADS_GET_AD_ACCOUNTS', arguments: { fields: 'id' } },
629 { tool_slug: 'SLACK_POST_MESSAGE', arguments: { channel: '#dev' } },
630 ],
631 sync_response_to_workbench: false,
632 });
633
643 - // All 4 tools should appear in results array
634 const { results } = result.data;
635 expect(results).toHaveLength(4);
636 expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();
647 - expect(findResult(results, 'LOCAL_GET_AD_ACCOUNTS')).toBeDefined();
637 + expect(findResult(results, 'LOCAL_META_ADS_GET_AD_ACCOUNTS')).toBeDefined();
638 expect(findResult(results, 'GMAIL_SEND_EMAIL')).toBeDefined();
639 expect(findResult(results, 'SLACK_POST_MESSAGE')).toBeDefined();
640
651 - // Backend only got the 2 remote tools
641 const backendTools = toolsInstance.executeMetaTool.mock.calls[0][1].arguments.tools;
642 expect(backendTools).toHaveLength(2);
643 expect(backendTools.map((t: any) => t.tool_slug)).toEqual([
@@ -656,15 +645,13 @@ describe('ToolRouterSession execution routing', () => {
645 'SLACK_POST_MESSAGE',
646 ]);
647
659 - // Both local execute fns were called
648 expect(localExecute).toHaveBeenCalled();
649 expect(sessionExecute).toHaveBeenCalled();
650 expect(result.successful).toBe(true);
651 });
652
653 it('should surface errors from both local and remote tools', async () => {
666 - const throwingHandle = createCustomTool({
667 - slug: 'MIXED_THROWER',
654 + const throwingHandle = createCustomTool('MIXED_THROWER', {
655 name: 'Throws in batch',
656 description: 'Throws',
657 inputParams: z.object({}),
@@ -676,7 +663,6 @@ describe('ToolRouterSession execution routing', () => {
663 [customToolHandle, throwingHandle]
664 );
665
679 - // Remote also returns an error for one tool
666 toolsInstance.executeMetaTool.mockResolvedValueOnce(
667 backendResponse([
668 { tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } },
@@ -697,21 +683,17 @@ describe('ToolRouterSession execution routing', () => {
683 const { results } = result.data;
684 expect(results).toHaveLength(4);
685
700 - // Local success
686 const localOk = findResult(results, 'LOCAL_GET_USER_CONTEXT');
687 expect(localOk.response.successful).toBe(true);
688
704 - // Local error — data is empty, error is surfaced
689 const localErr = findResult(results, 'LOCAL_MIXED_THROWER');
690 expect(localErr.response.successful).toBe(false);
691 expect(localErr.response.error).toBe('batch-boom');
692 expect(localErr.error).toBe('batch-boom');
693
710 - // Remote error is also preserved (not dropped!)
694 const remoteErr = findResult(results, 'SLACK_POST_MESSAGE');
695 expect(remoteErr.response.error).toBe('auth failed');
696
714 - // Top-level error reflects total failure count
697 expect(result.successful).toBe(false);
698 expect(result.error).toContain('2 out of 4');
699 });
@@ -724,7 +706,6 @@ describe('ToolRouterSession execution routing', () => {
706 sync_response_to_workbench: false,
707 });
708
727 - // Empty array → fallback to backend with full original input
709 expect(toolsInstance.executeMetaTool).toHaveBeenCalledWith(
710 'COMPOSIO_MULTI_EXECUTE_TOOL',
711 expect.objectContaining({
@@ -742,13 +723,11 @@ describe('ToolRouterSession execution routing', () => {
723 backendResponse([])
724 );
725
745 - // Malformed: string instead of object — should not crash
726 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
727 tools: ['not-an-object', null, { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'ok' } }],
728 sync_response_to_workbench: false,
729 });
730
751 - // The valid local tool should still execute
731 expect(localExecute).toHaveBeenCalledWith(
732 { category: 'ok' },
733 expect.objectContaining({ userId: 'user_1' })
@@ -758,11 +737,9 @@ describe('ToolRouterSession execution routing', () => {
737 });
738
739 it('should execute local and remote in parallel (not sequentially)', async () => {
761 - // Track call timing to verify parallelism
740 const callOrder: string[] = [];
741
764 - const slowLocalHandle = createCustomTool({
765 - slug: 'SLOW_LOCAL',
742 + const slowLocalHandle = createCustomTool('SLOW_LOCAL', {
743 name: 'Slow local',
744 description: 'Slow',
745 inputParams: z.object({}),
@@ -798,16 +775,13 @@ describe('ToolRouterSession execution routing', () => {
775 sync_response_to_workbench: false,
776 });
777
801 - // Both should start before either ends (parallel execution)
778 const localStartIdx = callOrder.indexOf('local-start');
779 const remoteStartIdx = callOrder.indexOf('remote-start');
780 const localEndIdx = callOrder.indexOf('local-end');
781 const remoteEndIdx = callOrder.indexOf('remote-end');
782
807 - // Both started
783 expect(localStartIdx).toBeGreaterThanOrEqual(0);
784 expect(remoteStartIdx).toBeGreaterThanOrEqual(0);
810 - // Both started before either finished
785 expect(Math.max(localStartIdx, remoteStartIdx)).toBeLessThan(
786 Math.min(localEndIdx, remoteEndIdx)
787 );
@@ -818,14 +792,12 @@ describe('ToolRouterSession execution routing', () => {
792 it('should route each tool to its correct execute function', async () => {
793 const session = createSession(mockClient, [customToolHandle, sessionToolHandle]);
794
821 - // First tool
795 await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
796 expect(localExecute).toHaveBeenCalled();
797 expect(sessionExecute).not.toHaveBeenCalled();
798
799 localExecute.mockClear();
800
828 - // Second tool
801 await session.execute('GET_AD_ACCOUNTS', { fields: 'id' });
802 expect(sessionExecute).toHaveBeenCalled();
803 expect(localExecute).not.toHaveBeenCalled();
@@ -871,7 +843,6 @@ describe('ToolRouterSession execution routing', () => {
843 const { results } = result.data;
844 expect(results).toHaveLength(3);
845
874 - // Each tool has its own entry
846 const local = results.find((r: any) => r.tool_slug === 'LOCAL_GET_USER_CONTEXT');
847 const gmail = results.find((r: any) => r.tool_slug === 'GMAIL_SEND_EMAIL');
848 const slack = results.find((r: any) => r.tool_slug === 'SLACK_POST_MESSAGE');
@@ -888,7 +859,7 @@ describe('ToolRouterSession execution routing', () => {
859
860 const session = new ToolRouterSession(
861 mockClient as unknown as ComposioClient,
891 - { apiKey: 'key' } as any, // no provider
862 + { apiKey: 'key' } as any,
863 'sess_123',
864 { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
865 undefined,
@@ -902,116 +873,4 @@ describe('ToolRouterSession execution routing', () => {
873 });
874 });
875
905 - describe('localTools() method', () => {
906 - it('should return wrapped tools with COMPOSIO_EXECUTE_LOCAL_TOOL slug', async () => {
907 - const provider = new MockProvider();
908 - captureExecuteFn(provider);
909 - const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
910 -
911 - const result = await session.localTools();
912 -
913 - expect(result).toBe('wrapped-tools-with-routing');
914 - expect(provider.wrapTools).toHaveBeenCalled();
915 -
916 - const tools = (provider as any)._capturedTools;
917 - expect(tools).toHaveLength(1);
918 - expect(tools[0].slug).toBe('COMPOSIO_EXECUTE_LOCAL_TOOL');
919 - });
920 -
921 - it('should route to local tool correctly when executing via localTools()', async () => {
922 - const provider = new MockProvider();
923 - captureExecuteFn(provider);
924 - const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
925 -
926 - await session.localTools();
927 - const executeFn = (provider as any)._capturedExecuteFn;
928 -
929 - const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {
930 - tool_slug: 'LOCAL_GET_USER_CONTEXT',
931 - arguments: { category: 'test' },
932 - });
933 -
934 - expect(result.data).toEqual({ local_result: true });
935 - expect(result.successful).toBe(true);
936 - expect(localExecute).toHaveBeenCalledWith(
937 - { category: 'test' },
938 - expect.objectContaining({ userId: 'user_1' })
939 - );
940 - });
941 -
942 - it('should return error when executing with invalid slug via localTools()', async () => {
943 - const provider = new MockProvider();
944 - captureExecuteFn(provider);
945 - const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
946 -
947 - await session.localTools();
948 - const executeFn = (provider as any)._capturedExecuteFn;
949 -
950 - const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {
951 - tool_slug: 'NON_EXISTENT_TOOL',
952 - arguments: {},
953 - });
954 -
955 - expect(result.successful).toBe(false);
956 - expect(result.error).toContain('Custom tool "NON_EXISTENT_TOOL" not found');
957 - expect(result.data).toEqual({});
958 - });
959 -
960 - it('should throw when calling localTools() without custom tools', async () => {
961 - const session = new ToolRouterSession(
962 - mockClient as unknown as ComposioClient,
963 - { apiKey: 'key', provider: new MockProvider() },
964 - 'sess_123',
965 - { type: 'http' as const, url: 'https://mcp.example.com/sess_123' }
966 - // No customToolsMap, no userId
967 - );
968 -
969 - await expect(session.localTools()).rejects.toThrow(
970 - 'No custom tools are bound to this session.'
971 - );
972 - });
973 - });
974 -
975 - describe('COMPOSIO_EXECUTE_LOCAL_TOOL interception in routing', () => {
976 - it('should route COMPOSIO_EXECUTE_LOCAL_TOOL to the correct local tool via session.tools() routing', async () => {
977 - const provider = new MockProvider();
978 - captureExecuteFn(provider);
979 - const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
980 -
981 - await session.tools();
982 - const executeFn = (provider as any)._capturedExecuteFn;
983 -
984 - const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {
985 - tool_slug: 'LOCAL_GET_USER_CONTEXT',
986 - arguments: { category: 'routing-test' },
987 - });
988 -
989 - expect(result.data).toEqual({ local_result: true });
990 - expect(result.successful).toBe(true);
991 - expect(localExecute).toHaveBeenCalledWith(
992 - { category: 'routing-test' },
993 - expect.objectContaining({ userId: 'user_1' })
994 - );
995 - // Should NOT call remote
996 - expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
997 - });
998 -
999 - it('should return error for COMPOSIO_EXECUTE_LOCAL_TOOL with unknown slug', async () => {
1000 - const provider = new MockProvider();
1001 - captureExecuteFn(provider);
1002 - const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
1003 -
1004 - await session.tools();
1005 - const executeFn = (provider as any)._capturedExecuteFn;
1006 -
1007 - const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {
1008 - tool_slug: 'DOES_NOT_EXIST',
1009 - arguments: {},
1010 - });
1011 -
1012 - expect(result.successful).toBe(false);
1013 - expect(result.error).toContain('Custom tool "DOES_NOT_EXIST" not found');
1014 - expect(result.data).toEqual({});
1015 - });
1016 - });
876 });