Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat: align custom tools API with backend refactor, add toolkits and extension tools
Dhawal Upadhyay0270042316b3
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 356adbb10..8794e0829 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -703,16 +703,16 @@ importers:version: link:../../packages/providers/llamaindex'@llamaindex/openai':specifier: ^0.4.20- version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])+ version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])'@llamaindex/workflow':specifier: ^1.1.24- version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])dotenv:specifier: ^16.4.1version: 16.6.1llamaindex:specifier: ^0.12.0- version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])+ version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])devDependencies:'@types/bun':specifier: ^1.2.9@@ -882,8 +882,8 @@ importers:specifier: ^1.1.3version: 1.2.8(@langchain/[email protected](@opentelemetry/[email protected])([email protected]([email protected])([email protected])))([email protected])'@openai/agents':- specifier: ^0.3.3+ specifier: ^0.1.3ai:specifier: 'catalog:'version: 6.0.90([email protected])@@ -893,12 +893,18 @@ importers:langchain:specifier: ^1.1.1version: 1.2.24(@langchain/[email protected](@opentelemetry/[email protected])([email protected]([email protected])([email protected])))(@opentelemetry/[email protected])([email protected]([email protected])([email protected]))([email protected]([email protected]))+ openai:+ specifier: ^6.22.0+ version: 6.22.0([email protected])([email protected])ora:specifier: ^9.0.0version: 9.3.0pnpm:specifier: 'catalog:'version: 10.30.0+ zod:+ specifier: 'catalog:'+ version: 4.3.6devDependencies:'@types/bun':specifier: ^1.2.9@@ -1312,7 +1318,7 @@ importers:dependencies:llamaindex:specifier: ^0.12.0- version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])devDependencies:'@composio/core':specifier: workspace:*@@ -2825,44 +2831,21 @@ packages:zod:optional: true- '@openai/[email protected]':- resolution: {integrity: sha512-6Fr/VkA3lMaTT9EV2+OsmkMX9Yx+/PeWtlmaWNKDRG8D15IWuK13NOC9eFklTsa7otbuwbw/Xmjes+h4Z+CwSQ==}- peerDependencies:- zod: ^3.25.40 || ^4.0- peerDependenciesMeta:- zod:- optional: true-'@openai/[email protected]':resolution: {integrity: sha512-TYYbY7o1cNxtOIO4F1a20qkqDT1Iwr9ZEi0MO2sEaeioK8rGB/Ux54iFvsA3IblUYyK+5fD25vr4vXFasvg2Kg==}peerDependencies:zod: ^3.25.40- '@openai/[email protected]':- resolution: {integrity: sha512-duXUt0xU6K/+c7ae4m8BrJIUzZal6Pzln8V0frnJfNyfYO4SvHMV4qwPRzVDvv/ANj4DQXWI2L1JdPxKJeSHkw==}- peerDependencies:- zod: ^3.25.40 || ^4.0-'@openai/[email protected]':resolution: {integrity: sha512-8jaNuYU1acra28i7bYrZIPubI6s2ziY2ZudqAVK2ad+giopXcrNSiJTuZ2S3z+ESnIejwMiYLfnY2Le8W0SJ7A==}peerDependencies:zod: ^3.25.40- '@openai/[email protected]':- resolution: {integrity: sha512-51zHO/zao/LHv70gseU1otTvXyS81tuVaewHlUBiNMXvqSZNkYViiO69hpXMoTYn5c3gCjUrXPxxI+NlHUtaHg==}- peerDependencies:- zod: ^3.25.40 || ^4.0-'@openai/[email protected]':resolution: {integrity: sha512-jnaFt54iP71vYDXvpG3EGX2kVRYIU2xBdCT3uFqdXm4KqFAP9JQFNGiKKBEeE5rbXARpqAQpKH+5HfoANndpcQ==}peerDependencies:zod: ^3.25.40- '@openai/[email protected]':- resolution: {integrity: sha512-YaKnqv0M6bCVvn47pThkFfyHz8xWJ+0Ll9ZnhvwJZ5gyPX0UxHIUeUs9SMG9BSvNuJNJHlc5uvfUDGYAmKJClw==}- peerDependencies:- zod: ^3.25.40 || ^4.0-'@opentelemetry/[email protected]':resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==}engines: {node: '>=8.0.0'}@@ -7478,7 +7461,7 @@ snapshots:mustache: 4.2.0p-queue: 6.6.2uuid: 10.0.0- zod: 4.3.6+ zod: 3.25.76transitivePeerDependencies:- '@opentelemetry/api'- '@opentelemetry/exporter-trace-otlp-proto'@@ -7574,26 +7557,43 @@ snapshots:tree-sitter: 0.22.4web-tree-sitter: 0.24.7- '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])':+ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])':dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30- openai: 5.23.2([email protected])([email protected])+ openai: 5.23.2([email protected])([email protected])transitivePeerDependencies:- ws- zod- '@llamaindex/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':+ '@llamaindex/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':optionalDependencies:- '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])+ '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])hono: 4.11.9+ zod: 3.25.76++ '@llamaindex/[email protected]([email protected])':+ optionalDependencies:zod: 4.3.6- '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':+ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30- '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ transitivePeerDependencies:+ - '@modelcontextprotocol/sdk'+ - hono+ - next+ - p-retry+ - rxjs+ - zod++ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])':+ dependencies:+ '@llamaindex/core': 0.6.22+ '@llamaindex/env': 0.1.30+ '@llamaindex/workflow-core': 1.3.3([email protected])transitivePeerDependencies:- '@modelcontextprotocol/sdk'- hono@@ -7875,18 +7875,6 @@ snapshots:- supports-color- ws- dependencies:- debug: 4.4.3([email protected])- openai: 6.22.0([email protected])([email protected])- optionalDependencies:- '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])- zod: 4.3.6- transitivePeerDependencies:- - '@cfworker/json-schema'- - supports-color- - ws-dependencies:@@ -7898,17 +7886,6 @@ snapshots:- supports-color- ws- dependencies:- debug: 4.4.3([email protected])- openai: 6.22.0([email protected])([email protected])- zod: 4.3.6- transitivePeerDependencies:- - '@cfworker/json-schema'- - supports-color- - ws-dependencies:@@ -7922,19 +7899,6 @@ snapshots:- supports-color- utf-8-validate- dependencies:- '@types/ws': 8.18.1- debug: 4.4.3([email protected])- ws: 8.19.0- zod: 4.3.6- transitivePeerDependencies:- - '@cfworker/json-schema'- - bufferutil- - supports-color- - utf-8-validate-dependencies:@@ -7950,21 +7914,6 @@ snapshots:- utf-8-validate- ws- dependencies:- '@openai/agents-realtime': 0.3.9(@cfworker/[email protected])([email protected])- debug: 4.4.3([email protected])- openai: 6.22.0([email protected])([email protected])- zod: 4.3.6- transitivePeerDependencies:- - '@cfworker/json-schema'- - bufferutil- - supports-color- - utf-8-validate- - ws-'@opentelemetry/[email protected]': {}'@oxc-project/[email protected]': {}@@ -9974,12 +9923,34 @@ snapshots:rfdc: 1.4.1wrap-ansi: 9.0.2- [email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected]):+ [email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected]):dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30'@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])- '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ '@types/lodash': 4.17.23+ '@types/node': 24.10.13+ lodash: 4.17.23+ magic-bytes.js: 1.13.0+ transitivePeerDependencies:+ - '@huggingface/transformers'+ - '@modelcontextprotocol/sdk'+ - gpt-tokenizer+ - hono+ - next+ - p-retry+ - rxjs+ - tree-sitter+ - web-tree-sitter+ - zod++ dependencies:+ '@llamaindex/core': 0.6.22+ '@llamaindex/env': 0.1.30+ '@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])+ '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])'@types/lodash': 4.17.23'@types/node': 24.10.13lodash: 4.17.23@@ -10259,6 +10230,11 @@ snapshots:is-inside-container: 1.0.0wsl-utils: 0.1.0+ optionalDependencies:+ ws: 8.19.0+ zod: 3.25.76+optionalDependencies:ws: 8.19.0diff --git a/ts/docs/api/tool-router.md b/ts/docs/api/tool-router.mdindex 6c4055cb4..0885a8350 100644--- a/ts/docs/api/tool-router.md+++ b/ts/docs/api/tool-router.md@@ -245,6 +245,8 @@ const session = await composio.create('user_123', {Configure experimental features for the session. These features are not stable and may be modified or removed in future versions.+#### Assistive Prompt+```typescriptconst session = await composio.create('user_123', {toolkits: ['gmail'],@@ -263,6 +265,86 @@ if (session.experimental?.assistivePrompt) {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.+#### Custom Tools & Custom Toolkits++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.++There are three ways to define custom tools:++**1. Standalone tool** — no auth, passed in `customTools`:++```typescript+import { experimental_createTool } from '@composio/core';+import { z } from 'zod/v3';++const grep = experimental_createTool('GREP', {+ name: 'Grep Search',+ description: 'Search for patterns in files',+ inputParams: z.object({ pattern: z.string(), path: z.string() }),+ execute: async (input) => ({ matches: [] }),+});+```++Slug format: `LOCAL_GREP`++**2. Extension tool** — extends a Composio toolkit (inherits auth), passed in `customTools`:++```typescript+const getImportant = experimental_createTool('GET_IMPORTANT_EMAILS', {+ name: 'Get Important Emails',+ description: 'Fetch high-priority emails',+ extendsToolkit: 'gmail',+ inputParams: z.object({ limit: z.number().default(10) }),+ execute: async (input, session) => {+ const result = await session.execute('GMAIL_SEARCH', { query: 'is:important' });+ return { emails: result.data };+ },+});+```++Slug format: `LOCAL_GMAIL_GET_IMPORTANT_EMAILS`++**3. Custom toolkit** — groups no-auth tools, passed in `customToolkits`:++```typescript+import { experimental_createToolkit } from '@composio/core';++const sed = experimental_createTool('SED', {+ name: 'Sed Replace',+ description: 'Find and replace in files',+ inputParams: z.object({ pattern: z.string(), replacement: z.string() }),+ execute: async (input) => ({ replaced: 0 }),+});++const devTools = experimental_createToolkit('DEV_TOOLS', {+ name: 'Dev Tools',+ description: 'Local dev utilities',+ tools: [sed],+});+```++Slug format: `LOCAL_DEV_TOOLS_SED`++**Using in a session:**++```typescript+const session = await composio.create('user_123', {+ toolkits: ['gmail'],+ experimental: {+ customTools: [grep, getImportant],+ customToolkits: [devTools],+ },+});++// Execute locally via session.execute()+const result = await session.execute('GREP', { pattern: 'TODO', path: '/src' });++// Also works with prefixed slug+const result2 = await session.execute('LOCAL_DEV_TOOLS_SED', { pattern: 'foo', replacement: 'bar' });+```++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.+## Session PropertiesA Tool Router session provides the following properties and methods:@@ -347,6 +429,49 @@ Meta tools allow you to:This method is useful when you need direct access to the underlying meta tools without creating a full session object.+### `execute()`++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.++```typescript+// Execute a custom tool+const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });+console.log(result.data); // { preferences: { ... } }+console.log(result.error); // null on success+console.log(result.logId); // 'local' for custom tools, backend log ID for remote tools++// Execute a remote Composio tool+const weather = await session.execute('WEATHERMAP_WEATHER', { location: 'Tokyo' });+```++### `search()`++Search for tools by semantic use case. Returns relevant tools with schemas and guidance.++```typescript+const results = await session.search({ query: 'send an email via gmail' });++for (const result of results.results) {+ console.log(result.useCase);+ console.log(result.primaryToolSlugs); // e.g. ['GMAIL_SEND_EMAIL']+}+```++### `proxyExecute()`++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.++```typescript+const result = await session.proxyExecute({+ toolkit: 'github',+ endpoint: 'https://api.github.com/user',+ method: 'GET',+ parameters: [+ { in: 'header', name: 'X-Custom', value: 'value' },+ ],+});+```+### `authorize()`Initiate an authorization flow for a toolkit.@@ -802,6 +927,8 @@ interface ToolRouterCreateSessionConfig {assistivePrompt?: {userTimezone?: string; // IANA timezone identifier for timezone-aware assistive prompts};+ customTools?: CustomTool[]; // Standalone or extension tools (from experimental_createTool)+ customToolkits?: CustomToolkit[]; // Grouped no-auth tools (from experimental_createToolkit)};}```@@ -817,8 +944,11 @@ interface ToolRouterSession {headers?: Record<string, string>; // Authentication headers (includes x-api-key if configured)};tools: (modifiers?: ProviderOptions) => Promise<Tools>;+ execute: (toolSlug: string, arguments?: Record<string, unknown>) => Promise<ToolRouterSessionExecuteResponse>;+ search: (params: { query: string; toolkits?: string[] }) => Promise<ToolRouterSessionSearchResponse>;+ proxyExecute: (params: SessionProxyExecuteParams) => Promise<ToolRouterSessionExecuteResponse>;authorize: (toolkit: string, options?: { callbackUrl?: string }) => Promise<ConnectionRequest>;- toolkits: (options?: {+ toolkits: (options?: {toolkits?: string[]; // Filter by specific toolkit slugsnextCursor?: string; // Pagination cursorlimit?: number; // Number of items per pagediff --git a/ts/e2e-tests/README.md b/ts/e2e-tests/README.mdindex a0f397073..f6ccd58f3 100644--- a/ts/e2e-tests/README.md+++ b/ts/e2e-tests/README.md@@ -27,7 +27,7 @@ ts/e2e-tests/├── runtimes/├── node/ # Node.js runtime tests│ ├── cjs-basic/ # CommonJS compatibility tests- │ ├── custom-tools/ # Custom local tools execution (session.execute, localTools, Zod validation)+ │ ├── custom-tools/ # Custom local tools execution (session.execute, proxyExecute, Zod validation)│ ├── esm-basic/ # ESM compatibility tests│ ├── json-schema-to-zod-v3/ # @composio/json-schema-to-zod + Zod v3 tests│ ├── json-schema-to-zod-v4/ # @composio/json-schema-to-zod + Zod v4 testsdiff --git a/ts/e2e-tests/runtimes/node/custom-tools/e2e.test.ts b/ts/e2e-tests/runtimes/node/custom-tools/e2e.test.tsindex ce977e990..a58493634 100644--- a/ts/e2e-tests/runtimes/node/custom-tools/e2e.test.ts+++ b/ts/e2e-tests/runtimes/node/custom-tools/e2e.test.ts@@ -74,10 +74,6 @@ e2e(import.meta.url, {expect(result.stdout).toContain('NONEXISTENT_TOOL_OK');});- it('localTools() method works', () => {- expect(result.stdout).toContain('LOCAL_TOOLS_METHOD_OK');- });-it('session.tools() wrapping works', () => {expect(result.stdout).toContain('TOOLS_WRAPPING_OK');});diff --git a/ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs b/ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjsindex 647561fa4..ab99073b2 100644--- a/ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs+++ b/ts/e2e-tests/runtimes/node/custom-tools/fixtures/index.mjs@@ -18,8 +18,7 @@ if (!apiKey) {// ── Define custom tools ──────────────────────────────────────-const getUserContext = createCustomTool({- slug: 'GET_USER_CONTEXT',+const getUserContext = createCustomTool('GET_USER_CONTEXT', {name: 'Get user context',description: 'Retrieve user preferences and history',inputParams: z.object({@@ -30,8 +29,7 @@ const getUserContext = createCustomTool({},});-const enrichedSearch = createCustomTool({- slug: 'ENRICHED_SEARCH',+const enrichedSearch = createCustomTool('ENRICHED_SEARCH', {name: 'Enriched search',description: 'Search and enrich results with user context',inputParams: z.object({@@ -45,8 +43,7 @@ const enrichedSearch = createCustomTool({},});-const throwingTool = createCustomTool({- slug: 'THROWING_TOOL',+const throwingTool = createCustomTool('THROWING_TOOL', {name: 'Throwing tool',description: 'A tool that always throws an error',inputParams: z.object({}),@@ -56,8 +53,7 @@ const throwingTool = createCustomTool({});// Tool with strict numeric schema — for Zod validation failure test-const strictTool = createCustomTool({- slug: 'STRICT_TOOL',+const strictTool = createCustomTool('STRICT_TOOL', {name: 'Strict tool',description: 'Tool with strict numeric input',inputParams: z.object({@@ -69,8 +65,7 @@ const strictTool = createCustomTool({});// Tool that chains into a remote tool via SessionContext.execute()-const weatherChain = createCustomTool({- slug: 'WEATHER_CHAIN',+const weatherChain = createCustomTool('WEATHER_CHAIN', {name: 'Weather chain',description: 'Fetches weather via remote tool and enriches with local context',inputParams: z.object({@@ -100,7 +95,9 @@ async function main() {const session = await composio.create(userId, {toolkits: ['weathermap'],manageConnections: false,- customTools: [getUserContext, enrichedSearch, throwingTool, strictTool, weatherChain],+ experimental: {+ customTools: [getUserContext, enrichedSearch, throwingTool, strictTool, weatherChain],+ },});// ── Test 1: Single local tool execution ──@@ -232,24 +229,6 @@ async function main() {console.log('NONEXISTENT_TOOL_OK');}- // ── Test 11: localTools() method ──- {- try {- const localTool = await session.localTools();- if (!localTool) {- throw new Error('localTools() returned falsy value');- }- console.log('LOCAL_TOOLS_METHOD_OK');- } catch (err) {- // Expected — no provider configured in this fixture- if (err.message?.includes('provider')) {- console.log('LOCAL_TOOLS_METHOD_OK');- } else {- throw err;- }- }- }-// ── Test 12: session.tools() wrapping ──{try {diff --git a/ts/examples/tool-router/package.json b/ts/examples/tool-router/package.jsonindex 44e248797..82109e5af 100644--- a/ts/examples/tool-router/package.json+++ b/ts/examples/tool-router/package.json@@ -27,7 +27,9 @@"@langchain/anthropic": "^1.1.3","@langchain/mcp-adapters": "^1.0.1","@langchain/openai": "^1.1.3",- "@openai/agents": "^0.3.3",+ "@openai/agents": "^0.1.3",+ "openai": "^6.22.0",+ "zod": "catalog:","ai": "catalog:","dotenv": "^16.4.1","langchain": "^1.1.1",diff --git a/ts/examples/tool-router/src/custom-tools-agent.ts b/ts/examples/tool-router/src/custom-tools-agent.tsnew file mode 100644index 000000000..0b85ab8d2--- /dev/null+++ b/ts/examples/tool-router/src/custom-tools-agent.ts@@ -0,0 +1,216 @@+/**+ * Custom Tools + Tool Router Agent+ *+ * Uses @composio/openai-agents provider with session.tools() for a proper+ * multi-turn agent that has both remote Composio tools (via tool router) and+ * custom local tools executing in-process.+ *+ * Demonstrates all three custom tool types:+ * 1. Standalone tools (no auth) — GET_USER_DETAILS, LIST_USER_KEYS+ * 2. Extension tool (inherits gmail auth) — FORMAT_GMAIL_EMAIL+ * 3. Custom toolkit (USER_MANAGEMENT) — SET_USER_ROLE, UPDATE_USER_STATUS+ *+ * Usage:+ * COMPOSIO_API_KEY=... OPENAI_API_KEY=... bun src/custom-tools-agent.ts+ */+import "dotenv/config";+import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";+import { OpenAIAgentsProvider } from "@composio/openai-agents";+import { Agent, run } from "@openai/agents";+import { z } from "zod/v3";++// ── In-memory user store (shared across tools) ───────────────────++const userStore: Record<string, Record<string, unknown>> = {+ "user-1": {+ id: "user-1",+ name: "Alice Johnson",+ email: "[email protected]",+ role: "admin",+ status: "active",+ created_at: "2024-01-15",+ },+ "user-2": {+ id: "user-2",+ name: "Bob Smith",+ email: "[email protected]",+ role: "developer",+ status: "active",+ created_at: "2024-03-22",+ },+ "user-3": {+ id: "user-3",+ name: "Carol Williams",+ email: "[email protected]",+ role: "viewer",+ status: "suspended",+ created_at: "2025-06-10",+ },+};++// ── 1. Standalone tools (no auth) → LOCAL_<SLUG> ─────────────────++const getUserDetails = experimental_createTool("GET_USER_DETAILS", {+ name: "Get user details",+ description:+ "Retrieve user profile information including name, email, role, and account status by user ID",+ inputParams: z.object({+ user_id: z.string().describe("The unique user identifier"),+ }),+ execute: async (input) => {+ const user = userStore[input.user_id];+ if (!user) throw new Error(`User "${input.user_id}" not found`);+ return user;+ },+});++const listUserKeys = experimental_createTool("LIST_USER_KEYS", {+ name: "List user API keys",+ description:+ "List all active API keys for a given user, including creation date and last used timestamp",+ inputParams: z.object({+ user_id: z.string().describe("The user whose keys to list"),+ include_expired: z.boolean().default(false).describe("Whether to include expired keys"),+ }),+ execute: async (input) => {+ const allKeys: Record<string, Array<Record<string, unknown>>> = {+ "user-1": [+ { key_id: "key_abc", prefix: "sk-***abc", created_at: "2025-01-01", last_used: "2026-03-15", expired: false },+ { key_id: "key_old", prefix: "sk-***old", created_at: "2024-01-01", last_used: "2024-06-01", expired: true },+ ],+ "user-2": [+ { key_id: "key_xyz", prefix: "sk-***xyz", created_at: "2025-06-01", last_used: "2026-03-14", expired: false },+ ],+ };+ const keys = allKeys[input.user_id] ?? [];+ const filtered = input.include_expired ? keys : keys.filter((k) => !k.expired);+ return { user_id: input.user_id, api_keys: filtered, total: filtered.length };+ },+});++// ── 2. Extension tool (inherits gmail auth) → LOCAL_GMAIL_<SLUG> ──++const formatGmailEmail = experimental_createTool("FORMAT_GMAIL_EMAIL", {+ name: "Format Gmail email",+ description: "Format and prepare an email draft with proper HTML formatting for sending via Gmail",+ extendsToolkit: "gmail",+ inputParams: z.object({+ to: z.string().describe("Recipient email address"),+ subject: z.string().describe("Email subject line"),+ body: z.string().describe("Email body content in markdown"),+ }),+ execute: async (input, session) => {+ const htmlBody = input.body+ .replace(/\*\*(.*?)\*\*/g, "<b>$1</b>")+ .replace(/\*(.*?)\*/g, "<i>$1</i>")+ .replace(/\n/g, "<br>");+ return {+ formatted: true,+ to: input.to,+ subject: input.subject,+ html_body: htmlBody,+ plain_body: input.body,+ user_id: session.userId,+ };+ },+});++// ── 3. Custom toolkit (USER_MANAGEMENT) → LOCAL_USER_MANAGEMENT_<SLUG> ──++const setUserRole = experimental_createTool("SET_USER_ROLE", {+ name: "Set user role",+ description: "Change the role of an existing user (admin, developer, viewer)",+ inputParams: z.object({+ user_id: z.string().describe("The user to update"),+ role: z.enum(["admin", "developer", "viewer"]).describe("The new role to assign"),+ }),+ execute: async (input) => {+ const user = userStore[input.user_id];+ if (!user) throw new Error(`User "${input.user_id}" not found`);+ const previousRole = user.role;+ user.role = input.role;+ return { user_id: input.user_id, previous_role: previousRole, new_role: input.role };+ },+});++const updateUserStatus = experimental_createTool("UPDATE_USER_STATUS", {+ name: "Update user status",+ description: "Activate or suspend a user account",+ inputParams: z.object({+ user_id: z.string().describe("The user to update"),+ status: z.enum(["active", "suspended"]).describe("The new account status"),+ reason: z.string().optional().describe("Reason for the status change"),+ }),+ execute: async (input) => {+ const user = userStore[input.user_id];+ if (!user) throw new Error(`User "${input.user_id}" not found`);+ const previousStatus = user.status;+ user.status = input.status;+ return {+ user_id: input.user_id,+ previous_status: previousStatus,+ new_status: input.status,+ reason: input.reason ?? "No reason provided",+ };+ },+});++const userManagement = experimental_createToolkit("USER_MANAGEMENT", {+ name: "User Management",+ description: "Tools for managing user profiles, roles, and account status",+ tools: [setUserRole, updateUserStatus],+});++// ── Agent ─────────────────────────────────────────────────────────++const composio = new Composio({+ apiKey: process.env.COMPOSIO_API_KEY,+ baseURL: process.env.COMPOSIO_BASE_URL || undefined,+ provider: new OpenAIAgentsProvider(),+});++const session = await composio.create(`agent-e2e-${Date.now()}`, {+ toolkits: ["weathermap", "gmail"],+ manageConnections: false,+ experimental: {+ customTools: [getUserDetails, listUserKeys, formatGmailEmail],+ customToolkits: [userManagement],+ },+});++console.log(`Session: ${session.sessionId}\n`);+const tools = await session.tools();++const agent = new Agent({+ name: "Custom Tools Agent",+ instructions: "You are a helpful assistant. Use Composio tools to execute tasks.",+ model: "gpt-5.2",+ tools,+});++const MAX = 3000;+function trunc(obj: unknown): string {+ const json = JSON.stringify(obj, null, 2);+ return json.length > MAX ? json.slice(0, MAX) + "\n ... (truncated)" : json;+}++agent.on("agent_tool_start", (_ctx, tool, details: any) => {+ const input = details.toolCall?.arguments ?? {};+ console.log(`\n ┌─ ${tool.name}`);+ console.log(` │ INPUT:\n${trunc(input)}`);+});+agent.on("agent_tool_end", (_ctx, tool, result: any) => {+ let output: unknown;+ try { output = typeof result === "string" ? JSON.parse(result) : result; } catch { output = result; }+ console.log(` │ OUTPUT:\n${trunc(output)}`);+ console.log(` └─ ${tool.name} done`);+});++const prompt = `Do the following tasks:+1. Get user-1's profile details and list their API keys+2. Promote user-3 (Carol) to developer role and reactivate her account (she was suspended by mistake)+3. Get the current weather in Tokyo`;++console.log(`User: ${prompt}\n`);+const result = await run(agent, prompt);+console.log(`\nAssistant: ${result.finalOutput}`);diff --git a/ts/packages/core/src/experimental/index.ts b/ts/packages/core/src/experimental/index.tsindex cc81a7e33..13c879cd2 100644--- a/ts/packages/core/src/experimental/index.ts+++ b/ts/packages/core/src/experimental/index.ts@@ -7,10 +7,12 @@*/// Custom tools-export { createCustomTool } from '../models/CustomTool';+export { createCustomTool, createCustomToolkit } from '../models/CustomTool';export type {CustomTool,CreateCustomToolParams,CustomToolExecuteFn,SessionContext,+ CustomToolkit,+ CreateCustomToolkitParams,} from '../types/customTool.types';diff --git a/ts/packages/core/src/index.ts b/ts/packages/core/src/index.tsindex 6decb7207..02fcef40c 100644--- a/ts/packages/core/src/index.ts+++ b/ts/packages/core/src/index.ts@@ -29,5 +29,10 @@ export * from './types/ToolRouterSessionFilesMount.types';export * as constants from './utils/constants';export { default as logger } from './utils/logger';++// Experimental custom tools — exported with experimental_ prefix for top-level import+export { createCustomTool as experimental_createTool } from './models/CustomTool';+export { createCustomToolkit as experimental_createToolkit } from './models/CustomTool';+// Error handling exportsexport * from './errors';diff --git a/ts/packages/core/src/models/CustomTool.ts b/ts/packages/core/src/models/CustomTool.tsindex 38bf2a91b..e072755aa 100644--- a/ts/packages/core/src/models/CustomTool.ts+++ b/ts/packages/core/src/models/CustomTool.ts@@ -1,16 +1,23 @@/**- * @fileoverview Standalone factory function for creating custom tools.+ * @fileoverview Factory functions for creating custom tools and toolkits.** Usage:* ```typescript- * import { createCustomTool } from '@composio/core/experimental';- *- * const myTool = createCustomTool({- * slug: 'GET_USER_CONTEXT',- * name: 'Get user context',- * description: 'Retrieve what we know about a user',- * inputParams: z.object({ category: z.string() }),- * execute: async (input) => ({ preferences: await db.find(input.category) }),+ * import { experimental_createTool, experimental_createToolkit } from '@composio/core';+ * // or+ * import { createCustomTool, createCustomToolkit } from '@composio/core/experimental';+ *+ * const grep = createCustomTool('GREP', {+ * name: 'Grep Search',+ * description: 'Search for patterns in files',+ * inputParams: z.object({ pattern: z.string() }),+ * execute: async (input) => ({ matches: [] }),+ * });+ *+ * const devTools = createCustomToolkit('DEV_TOOLS', {+ * name: 'Dev Tools',+ * description: 'Local dev utilities',+ * tools: [grep],* });* ```*/@@ -18,79 +25,74 @@ import * as zodToJsonSchema from 'zod-to-json-schema';import { z } from 'zod/v3';import {CreateCustomToolBaseSchema,+ CreateCustomToolkitBaseSchema,+ CustomToolSlugSchema,type CreateCustomToolParams,+ type CreateCustomToolkitParams,type CustomTool,+ type CustomToolkit,type CustomToolExecuteFn,type CustomToolsMap,type CustomToolsMapEntry,type CustomToolDefinition,+ type CustomToolkitDefinition,type InputParamsSchema,} from '../types/customTool.types';/** Prefix applied by the backend to local tool slugs for disambiguation. */export const LOCAL_TOOL_PREFIX = 'LOCAL_';+/** Maximum allowed length for the final prefixed slug. */+const MAX_PREFIXED_SLUG_LENGTH = 60;+/*** Create a custom tool for use in tool router sessions.** The returned object is a lightweight reference containing the tool's metadata- * and execute function. Pass it to `composio.create(userId, { customTools: [...] })`+ * and execute function. Pass it to `composio.create(userId, { experimental: { customTools: [...] } })`* to bind it to a session.** Just return the result data from `execute`, or throw an error.* The SDK wraps it into the standard response format internally.*- * @param options - Tool definition including slug, schema, and execute function+ * @param slug - Unique tool identifier (alphanumeric, underscores, hyphens; no LOCAL_ prefix)+ * @param options - Tool definition including name, schema, and execute function* @returns A CustomTool to pass to session creation*- * @example No-auth tool (no session needed)+ * @example Standalone tool (no auth)* ```typescript- * const getUserContext = createCustomTool({- * slug: 'GET_USER_CONTEXT',- * name: 'Get user context',- * description: 'Retrieve user preferences and history',- * inputParams: z.object({ category: z.string().default('all') }),- * execute: async (input) => {- * const prefs = await db.userContext.find(input.category);- * return { preferences: prefs };- * },+ * const grep = createCustomTool('GREP', {+ * name: 'Grep Search',+ * description: 'Search for patterns in files',+ * inputParams: z.object({ pattern: z.string(), path: z.string() }),+ * execute: async (input) => ({ matches: [] }),* });* ```*- * @example Tool using session to call other tools+ * @example Tool extending a Composio toolkit (inherits auth)* ```typescript- * const enrichedSearch = createCustomTool({- * slug: 'ENRICHED_SEARCH',- * name: 'Enriched search',- * description: 'Search and enrich results with user context',- * inputParams: z.object({ query: z.string() }),+ * const getImportant = createCustomTool('GET_IMPORTANT_EMAILS', {+ * name: 'Get Important Emails',+ * description: 'Fetch high-priority emails',+ * extendsToolkit: 'gmail',+ * inputParams: z.object({ limit: z.number().default(10) }),* execute: async (input, session) => {- * const results = await session.execute('GOOGLE_SEARCH', { query: input.query });- * return { enriched: results.data, userId: session.userId };- * },- * });- * ```- *- * @example Auth tool with toolkit (requires Composio connection)- * ```typescript- * const getAdAccounts = createCustomTool({- * slug: 'GET_AD_ACCOUNTS',- * name: 'Get ad accounts',- * description: 'Get Meta ad account IDs for the authenticated user',- * toolkit: 'meta_ads',- * inputParams: z.object({ fields: z.string().default('id,name') }),- * execute: async (input, session) => {- * const result = await session.execute('META_ADS_GET_AD_ACCOUNTS', {- * fields: input.fields,- * });- * return result.data;+ * const result = await session.execute('GMAIL_SEARCH', { query: 'is:important' });+ * return { emails: result.data };* },* });* ```*/export function createCustomTool<T extends z.ZodType>(+ slug: string,options: CreateCustomToolParams<T>): CustomTool {+ // Validate slug separately+ const slugResult = CustomToolSlugSchema.safeParse(slug);+ if (!slugResult.success) {+ throw new Error(`createCustomTool: ${slugResult.error.issues[0].message}`);+ }+// Validate string/scalar fields via Zod schemaconst validated = CreateCustomToolBaseSchema.parse(options);@@ -104,7 +106,7 @@ export function createCustomTool<T extends z.ZodType>(const { inputParams, execute } = options;- // Convert Zod schema → JSON Schema (reuses same pattern as legacy CustomTools.createTool)+ // Convert Zod input schema → JSON Schemaconst paramsSchema = zodToJsonSchema.default(inputParams, {name: 'input',}) as InputParamsSchema;@@ -116,41 +118,162 @@ export function createCustomTool<T extends z.ZodType>(...(paramsSchemaJson.required ? { required: paramsSchemaJson.required } : {}),};+ // Convert Zod output schema → JSON Schema (if provided)+ let outputSchema: Record<string, unknown> | undefined;+ if (options.outputParams) {+ const outSchema = zodToJsonSchema.default(options.outputParams, {+ name: 'output',+ }) as { definitions: { output: { type: string; properties: Record<string, unknown>; required?: string[] } } };+ const outJson = outSchema.definitions.output;+ outputSchema = {+ type: 'object',+ properties: outJson.properties,+ ...(outJson.required ? { required: outJson.required } : {}),+ };+ }+return {- slug: validated.slug,+ slug: slugResult.data,name: validated.name,description: validated.description,- toolkit: validated.toolkit,+ extendsToolkit: validated.extendsToolkit,inputSchema,+ outputSchema,inputParams,execute: execute as CustomToolExecuteFn<z.ZodType>,};}/**- * Build a CustomToolsMap from an array of custom tools.+ * Create a custom toolkit that groups related tools.+ *+ * Tools in a toolkit get prefixed as `LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>`.+ * Tools passed here must NOT have `extendsToolkit` set — they inherit the toolkit identity instead.+ *+ * @param slug - Unique toolkit identifier (alphanumeric, underscores, hyphens; no LOCAL_ prefix)+ * @param options - Toolkit definition including name, description, and tools+ * @returns A CustomToolkit to pass to session creation+ *+ * @example+ * ```typescript+ * const devTools = createCustomToolkit('DEV_TOOLS', {+ * name: 'Dev Tools',+ * description: 'Local dev utilities',+ * tools: [grepTool, sedTool],+ * });+ * ```+ */+export function createCustomToolkit(+ slug: string,+ options: CreateCustomToolkitParams+): CustomToolkit {+ // Validate slug+ const slugResult = CustomToolSlugSchema.safeParse(slug);+ if (!slugResult.success) {+ throw new Error(`createCustomToolkit: ${slugResult.error.issues[0].message}`);+ }++ // Validate name/description+ const validated = CreateCustomToolkitBaseSchema.parse(options);++ // Non-empty tools required+ if (!options.tools?.length) {+ throw new Error('createCustomToolkit: at least one tool is required');+ }++ // Reject tools with extendsToolkit+ for (const tool of options.tools) {+ if (tool.extendsToolkit) {+ throw new Error(+ `createCustomToolkit: tool "${tool.slug}" has extendsToolkit set. ` ++ `Tools in a custom toolkit must not use extendsToolkit — they inherit the toolkit identity instead.`+ );+ }+ }++ return {+ slug: slugResult.data,+ name: validated.name,+ description: validated.description,+ tools: options.tools,+ };+}++/**+ * Build a CustomToolsMap from custom tools and toolkits.* Used internally by ToolRouter.create() to construct the per-session routing map.*+ * Prefix rules:+ * - Standalone (no extendsToolkit): `LOCAL_<SLUG>`+ * - Extends toolkit: `LOCAL_<EXTENDS_TOOLKIT>_<SLUG>`+ * - Toolkit tool: `LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>`+ ** @internal- * @param tools - The custom tools to include in the session+ * @param tools - Standalone custom tools+ * @param toolkits - Custom toolkits containing grouped tools* @returns Maps for O(1) lookup by both prefixed and original slug- * @throws If duplicate slugs are detected+ * @throws If duplicate slugs, slug too long, or cross-group collisions*/-export function buildCustomToolsMap(tools: CustomTool[]): CustomToolsMap {+export function buildCustomToolsMap(+ tools: CustomTool[],+ toolkits?: CustomToolkit[]+): CustomToolsMap {const byPrefixed = new Map<string, CustomToolsMapEntry>();const byOriginal = new Map<string, CustomToolsMapEntry>();- for (const handle of tools) {- const upperSlug = handle.slug.toUpperCase();- const prefixedSlug = `${LOCAL_TOOL_PREFIX}${upperSlug}`;+ const addEntry = (handle: CustomTool, prefixedSlug: string) => {+ const originalSlug = handle.slug.toUpperCase();++ // Validate final prefixed slug length+ if (prefixedSlug.length > MAX_PREFIXED_SLUG_LENGTH) {+ const prefix = prefixedSlug.substring(0, prefixedSlug.length - originalSlug.length);+ const available = MAX_PREFIXED_SLUG_LENGTH - prefix.length;+ throw new Error(+ `Custom tool slug "${handle.slug}" is too long. ` ++ `With prefix "${prefix}", the final slug "${prefixedSlug}" exceeds ${MAX_PREFIXED_SLUG_LENGTH} characters. ` ++ `Shorten the slug to at most ${available} characters.`+ );+ }- if (byOriginal.has(upperSlug)) {- throw new Error(`createCustomTool: duplicate slug "${handle.slug}"`);+ // Check cross-group collisions on prefixed slug+ if (byPrefixed.has(prefixedSlug)) {+ throw new Error(`Custom tool slug collision: "${prefixedSlug}" is already registered.`);+ }++ // Check cross-group collisions on original slug+ if (byOriginal.has(originalSlug)) {+ throw new Error(+ `Custom tool slug collision: original slug "${handle.slug}" maps to multiple prefixed slugs. ` ++ `"${byOriginal.get(originalSlug)!.prefixedSlug}" and "${prefixedSlug}" both resolve from "${originalSlug}".`+ );}const entry: CustomToolsMapEntry = { handle, prefixedSlug };byPrefixed.set(prefixedSlug, entry);- byOriginal.set(upperSlug, entry);+ byOriginal.set(originalSlug, entry);+ };++ // Process standalone tools+ for (const handle of tools) {+ const upperSlug = handle.slug.toUpperCase();+ if (handle.extendsToolkit) {+ // LOCAL_<EXTENDS_TOOLKIT>_<SLUG>+ addEntry(handle, `LOCAL_${handle.extendsToolkit.toUpperCase()}_${upperSlug}`);+ } else {+ // LOCAL_<SLUG>+ addEntry(handle, `LOCAL_${upperSlug}`);+ }+ }++ // Process toolkit tools+ if (toolkits) {+ for (const toolkit of toolkits) {+ const tkSlug = toolkit.slug.toUpperCase();+ for (const handle of toolkit.tools) {+ // LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>+ addEntry(handle, `LOCAL_${tkSlug}_${handle.slug.toUpperCase()}`);+ }+ }}return { byPrefixed, byOriginal };@@ -159,6 +282,8 @@ export function buildCustomToolsMap(tools: CustomTool[]): CustomToolsMap {/*** Serialize custom tools into the format expected by the backend session creation API.*+ * Maps `extendsToolkit` → `extends_toolkit` for backend. Omitted for standalone tools.+ ** @internal* @param tools - The custom tools to serialize* @returns Array of CustomToolDefinition for the API payload@@ -171,6 +296,31 @@ export function serializeCustomTools(name: handle.name,description: handle.description,input_schema: handle.inputSchema,- ...(handle.toolkit ? { toolkit: handle.toolkit } : {}),+ ...(handle.outputSchema ? { output_schema: handle.outputSchema } : {}),+ ...(handle.extendsToolkit ? { extends_toolkit: handle.extendsToolkit } : {}),+ }));+}++/**+ * Serialize custom toolkits into the format expected by the backend session creation API.+ *+ * @internal+ * @param toolkits - The custom toolkits to serialize+ * @returns Array of CustomToolkitDefinition for the API payload+ */+export function serializeCustomToolkits(+ toolkits: CustomToolkit[]+): CustomToolkitDefinition[] {+ return toolkits.map(tk => ({+ slug: tk.slug,+ name: tk.name,+ description: tk.description,+ tools: tk.tools.map(t => ({+ slug: t.slug,+ name: t.name,+ description: t.description,+ input_schema: t.inputSchema,+ ...(t.outputSchema ? { output_schema: t.outputSchema } : {}),+ })),}));}diff --git a/ts/packages/core/src/models/SessionContext.ts b/ts/packages/core/src/models/SessionContext.tsindex f92a28633..9c89f74b2 100644--- a/ts/packages/core/src/models/SessionContext.ts+++ b/ts/packages/core/src/models/SessionContext.ts@@ -3,7 +3,10 @@*/import { Composio as ComposioClient } from '@composio/client';import type { SessionContext } from '../types/customTool.types';-import type { ToolExecuteResponse, ToolProxyParams } from '../types/tool.types';+import type { ToolExecuteResponse } from '../types/tool.types';+import type { SessionProxyExecuteParams } from '../types/toolRouter.types';+import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';+import { transformProxyParams } from './proxyParamsTransform';/*** Callback that attempts local tool execution.@@ -66,16 +69,26 @@ export class SessionContextImpl implements SessionContext {/*** Proxy API calls through Composio's auth layer.- * The session-scoped backend endpoint resolves the connected account automatically.- *- * TODO: Wire to session-scoped proxy endpoint (proxyExecuteForSessionRPC).- * Currently a skeleton — will be connected to backend API.+ * The backend resolves the connected account from the toolkit within the session.*/- async proxyExecute(_params: ToolProxyParams): Promise<ToolExecuteResponse> {- // TODO: Call session-scoped proxy endpoint that resolves connected account from session.- // Backend API: apps/apollo/src/lib/toolRouterV2/features/execution/proxyExecuteForSessionRPC.ts- throw new Error(- 'proxyExecute is not yet implemented. Session-scoped proxy endpoint pending backend support.'+ async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolExecuteResponse> {+ const validated = SessionProxyExecuteParamsSchema.safeParse(params);+ if (!validated.success) {+ throw new Error(`Invalid proxy execute parameters: ${validated.error.message}`);+ }++ const body = transformProxyParams(validated.data);++ // TODO: Replace with client.toolRouter.session.proxyExecute() when @composio/client is updated+ 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(+ `/api/v3/tool_router/session/${this.sessionId}/proxy_execute`,+ { body });++ return {+ data: response.data ?? {},+ error: response.error,+ successful: !response.error,+ };}}diff --git a/ts/packages/core/src/models/ToolRouter.ts b/ts/packages/core/src/models/ToolRouter.tsindex cad4c829e..bf9f036c3 100644--- a/ts/packages/core/src/models/ToolRouter.ts+++ b/ts/packages/core/src/models/ToolRouter.ts@@ -38,8 +38,8 @@ import {transformToolRouterToolkitsParams,} from '../lib/toolRouterParams';import { ToolRouterSession } from './ToolRouterSession';-import { buildCustomToolsMap, serializeCustomTools } from './CustomTool';-import type { CustomToolsMap, CustomToolDefinition } from '../types/customTool.types';+import { buildCustomToolsMap, serializeCustomTools, serializeCustomToolkits } from './CustomTool';+import type { CustomToolsMap } from '../types/customTool.types';export class ToolRouter<TToolCollection,@@ -78,15 +78,17 @@ export class ToolRouter<** @example* ```typescript- * import { Composio } from '@composio/core';- * import { CustomTool } from '@composio/core/experimental';+ * import { Composio, experimental_createTool } from '@composio/core';** const composio = new Composio();** const session = await composio.create('user_123', {* toolkits: ['gmail'],* manageConnections: true,- * customTools: [myCustomTool],+ * experimental: {+ * customTools: [myCustomTool],+ * customToolkits: [myToolkit],+ * },* });* ```*/@@ -96,11 +98,29 @@ export class ToolRouter<): Promise<Session<TToolCollection, TTool, TProvider>> {const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});- // Build custom tools map and backend payload from custom tool handles+ // Extract custom tools/toolkits from experimental config+ const customTools = routerConfig.experimental?.customTools;+ const customToolkits = routerConfig.experimental?.customToolkits;let customToolsMap: CustomToolsMap | undefined;- const customTools = routerConfig.customTools;- const payload: SessionCreateParams & { custom_tools?: CustomToolDefinition[] } = {+ // Build the experimental payload for the backend+ const experimentalPayload: Record<string, unknown> = {};++ if (routerConfig.experimental?.assistivePrompt?.userTimezone) {+ experimentalPayload.assistive_prompt_config = {+ user_timezone: routerConfig.experimental.assistivePrompt.userTimezone,+ };+ }++ if (customTools?.length || customToolkits?.length) {+ customToolsMap = buildCustomToolsMap(customTools ?? [], customToolkits);+ experimentalPayload.custom_tools = serializeCustomTools(customTools ?? []);+ if (customToolkits?.length) {+ experimentalPayload.custom_toolkits = serializeCustomToolkits(customToolkits);+ }+ }++ const payload: SessionCreateParams = {user_id: userId,auth_configs: routerConfig.authConfigs,connected_accounts: routerConfig.connectedAccounts,@@ -111,22 +131,11 @@ export class ToolRouter<routerConfig.manageConnections),workbench: transformToolRouterWorkbenchParams(routerConfig.workbench),- experimental: routerConfig.experimental?.assistivePrompt?.userTimezone- ? {- assistive_prompt_config: {- user_timezone: routerConfig.experimental.assistivePrompt.userTimezone,- },- }+ experimental: Object.keys(experimentalPayload).length > 0+ ? experimentalPayload: undefined,};- if (customTools?.length) {- customToolsMap = buildCustomToolsMap(customTools);- // Send definitions to backend for search indexing- // Type assertion: @composio/client doesn't have custom_tools yet- payload.custom_tools = serializeCustomTools(customTools);- }-const session = await this.client.toolRouter.session.create(payload as SessionCreateParams);diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.tsindex 31fa2cb58..7a69fd228 100644--- a/ts/packages/core/src/models/ToolRouterSession.ts+++ b/ts/packages/core/src/models/ToolRouterSession.ts@@ -26,12 +26,14 @@ import { ValidationError } from '../errors';import { Tools } from './Tools';import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';import type { CustomToolsMap, CustomToolsMapEntry, SessionContext } from '../types/customTool.types';-import type { Tool, ToolExecuteResponse } from '../types/tool.types';+import type { ToolExecuteResponse } from '../types/tool.types';+import type { SessionProxyExecuteParams } from '../types/toolRouter.types';+import { SessionProxyExecuteParamsSchema } from '../types/toolRouter.types';import { SessionContextImpl } from './SessionContext';import { findCustomTool, executeCustomTool } from './customToolExecution';+import { transformProxyParams } from './proxyParamsTransform';const COMPOSIO_MULTI_EXECUTE_TOOL = 'COMPOSIO_MULTI_EXECUTE_TOOL';-const COMPOSIO_EXECUTE_LOCAL_TOOL = 'COMPOSIO_EXECUTE_LOCAL_TOOL';export class ToolRouterSession<TToolCollection,@@ -86,19 +88,6 @@ export class ToolRouterSession<if (toolSlug === COMPOSIO_MULTI_EXECUTE_TOOL) {return this.routeMultiExecute(input, ToolsModel, modifiers);}- if (toolSlug === COMPOSIO_EXECUTE_LOCAL_TOOL) {- const slug = String(input.tool_slug ?? '');- const args = (input.arguments as Record<string, unknown> | undefined) ?? {};- const entry = findCustomTool(this.customToolsMap, slug);- if (!entry) {- return {- data: {},- error: `Custom tool "${slug}" not found. If this is a remote tool, execute it via COMPOSIO_MULTI_EXECUTE_TOOL.`,- successful: false,- };- }- return executeCustomTool(entry, args, this.buildSessionContext());- }// Non-multi-execute meta tools always go to backendreturn ToolsModel.executeMetaTool(toolSlug,@@ -123,90 +112,6 @@ export class ToolRouterSession<return wrappedTools as ReturnType<TProvider['wrapTools']>;}- /**- * Returns a dispatcher tool that exposes custom tools for execution.- * Primarily used in MCP flows where remote tools are served via an MCP server- * and custom tools need to be added alongside.- *- * Not included in `session.tools()` — must be explicitly added to the agent's tool set.- *- * @example- * ```typescript- * // MCP flow: remote tools via MCP server, local tools via localTools()- * const localTool = await session.localTools();- * const agent = new Agent({- * tools: [- * hostedMcpTool(session.mcp.url), // remote tools from MCP- * ...localTool, // custom tools- * ],- * });- * ```- */- async localTools(): Promise<ReturnType<TProvider['wrapTools']>> {- if (!this.hasCustomTools()) {- throw new Error('No custom tools are bound to this session.');- }- if (!this.config?.provider) {- throw new Error(- 'A provider is required for session.localTools(). ' +- 'Pass a provider in the Composio constructor.'- );- }-- // Collect local tool slugs and descriptions for the schema- const toolEntries = Array.from(this.customToolsMap!.byOriginal.entries());- const slugDescriptions = toolEntries- .map(([_slug, entry]) => `- ${entry.prefixedSlug}: ${entry.handle.description}`)- .join('\n');-- // Build a synthetic Tool schema for COMPOSIO_EXECUTE_LOCAL_TOOL- const tool: Tool = {- slug: COMPOSIO_EXECUTE_LOCAL_TOOL,- name: 'Execute Local Tool',- description: `Execute a custom tool by slug.\n\nAvailable tools:\n${slugDescriptions}`,- inputParameters: {- type: 'object',- properties: {- tool_slug: {- type: 'string',- description: 'The slug of the local tool to execute',- enum: toolEntries.map(([, entry]) => entry.prefixedSlug),- },- arguments: {- type: 'object',- description: 'Arguments to pass to the tool',- properties: {},- additionalProperties: true,- },- },- required: ['tool_slug'],- },- };-- const executeFn = async (- _toolSlug: string,- input: Record<string, unknown>- ): Promise<ToolExecuteResponse> => {- const slug = String(input.tool_slug ?? '');- const args = (input.arguments as Record<string, unknown> | undefined) ?? {};-- const entry = findCustomTool(this.customToolsMap, slug);- if (!entry) {- return {- data: {},- 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.`,- successful: false,- };- }-- return executeCustomTool(entry, args, this.buildSessionContext());- };-- return this.config.provider.wrapTools([tool], executeFn) as ReturnType<- TProvider['wrapTools']- >;- }-/*** Initiate an authorization flow for a toolkit.* Returns a ConnectionRequest with a redirect URL for the user.@@ -331,6 +236,34 @@ export class ToolRouterSession<return ToolRouterSessionExecuteResponseSchema.parse(transformed);}+ /**+ * 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.+ *+ * @param params - Proxy request parameters (toolkit, endpoint, method, body, headers/query params)+ * @returns The proxied API response+ */+ async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionExecuteResponse> {+ const validated = SessionProxyExecuteParamsSchema.safeParse(params);+ if (!validated.success) {+ throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });+ }++ const body = transformProxyParams(validated.data);++ // TODO: Replace with client.toolRouter.session.proxyExecute() when @composio/client is updated+ 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(+ `/api/v3/tool_router/session/${this.sessionId}/proxy_execute`,+ { body }+ );++ return ToolRouterSessionExecuteResponseSchema.parse({+ data: response.data,+ error: response.error,+ logId: response.log_id,+ });+ }+// ── Private helpers ──────────────────────────────────────────/** Check if this session has any custom tools bound. */@@ -457,18 +390,20 @@ export class ToolRouterSession<}));// Merge and re-index sequentially so there are no collisions- const allResults = [...remoteResults, ...localEntries].map(- (entry: Record<string, unknown>, i) => ({- ...entry,- index: i,- })- );+ const merged: Array<Record<string, unknown>> = [+ ...(remoteResults as Array<Record<string, unknown>>),+ ...localEntries,+ ];+ const allResults = merged.map((entry, i): Record<string, unknown> => ({+ ...entry,+ index: i,+ }));const hasAnyError = localResults.some(r => r.result.error) || !!remoteResult?.error;return {data: { ...remoteData, results: allResults },error: hasAnyError- ? `${allResults.filter((r: Record<string, unknown>) => r.error).length} out of ${allResults.length} tools failed`+ ? `${allResults.filter(r => r.error).length} out of ${allResults.length} tools failed`: null,successful: !hasAnyError,};diff --git a/ts/packages/core/src/models/proxyParamsTransform.ts b/ts/packages/core/src/models/proxyParamsTransform.tsnew file mode 100644index 000000000..7ef89dad1--- /dev/null+++ b/ts/packages/core/src/models/proxyParamsTransform.ts@@ -0,0 +1,34 @@+/**+ * @fileoverview Shared transform for converting SDK SessionProxyExecuteParams+ * to the backend proxy execute request format.+ */+import type { SessionProxyExecuteParams } from '../types/toolRouter.types';++/** Backend session proxy execute request body shape. */+export interface SessionProxyExecuteRequestBody {+ toolkit_slug: string;+ endpoint: string;+ method: string;+ body?: unknown;+ parameters?: Array<{ name: string; type: 'header' | 'query'; value: string }>;+}++/**+ * Transform SDK session proxy params to the backend request format.+ * Converts `in` (query/header) to `type` and stringifies values.+ */+export function transformProxyParams(params: SessionProxyExecuteParams): SessionProxyExecuteRequestBody {+ const parameters = params.parameters?.map(p => ({+ name: p.name,+ type: p.in as 'header' | 'query',+ value: p.value.toString(),+ }));++ return {+ toolkit_slug: params.toolkit,+ endpoint: params.endpoint,+ method: params.method,+ ...(params.body !== undefined ? { body: params.body } : {}),+ ...(parameters?.length ? { parameters } : {}),+ };+}diff --git a/ts/packages/core/src/types/customTool.types.ts b/ts/packages/core/src/types/customTool.types.tsindex 68fc1be4d..abf362932 100644--- a/ts/packages/core/src/types/customTool.types.ts+++ b/ts/packages/core/src/types/customTool.types.ts@@ -1,5 +1,6 @@import { z } from 'zod/v3';import { Tool, ToolProxyParams, ToolExecuteResponse as SdkToolExecuteResponse } from './tool.types';+import type { SessionProxyExecuteParams } from './toolRouter.types';import { ToolExecuteResponse } from '@composio/client/resources/tools';import { ConnectionData } from './connectedAccountAuthStates.types';@@ -74,11 +75,8 @@ export interface SessionContext {toolSlug: string,arguments_: Record<string, unknown>): Promise<SdkToolExecuteResponse>;- /**- * Proxy API calls through Composio's auth layer (resolved from session).- * @todo Not yet implemented — pending backend session-scoped proxy endpoint.- */- proxyExecute(params: ToolProxyParams): Promise<SdkToolExecuteResponse>;+ /** Proxy API calls through Composio's auth layer (resolved from session toolkit). */+ proxyExecute(params: SessionProxyExecuteParams): Promise<SdkToolExecuteResponse>;}/**@@ -94,26 +92,37 @@ export type CustomToolExecuteFn<T extends z.ZodType> = (session: SessionContext) => Promise<Record<string, unknown>>;+/**+ * Zod schema for validating a custom tool slug.+ * Alphanumeric, underscores, and hyphens only. No `LOCAL_` prefix.+ * Length is validated later in `buildCustomToolsMap` with contextual error.+ */+export const CustomToolSlugSchema = z+ .string()+ .min(1, 'slug is required')+ .regex(+ /^[A-Za-z0-9_-]+$/,+ 'slug must only contain alphanumeric characters, underscores, and hyphens'+ )+ .refine(s => !s.toUpperCase().startsWith('LOCAL_'), {+ message:+ 'slug must not start with "LOCAL_" — this prefix is reserved for internal routing.',+ });+/*** Zod schema for validating the string/scalar fields of createCustomTool() options.- * Used internally for validation — inputParams and execute are checked manually.+ * Slug is validated separately as the first argument.+ * Used internally for validation — inputParams, outputParams, and execute are checked manually.*/export const CreateCustomToolBaseSchema = z.object({- slug: z- .string()- .min(1, 'createCustomTool: slug is required')- .refine(s => !s.toUpperCase().startsWith('LOCAL_'), {- message:- 'createCustomTool: slug must not start with "LOCAL_" — this prefix is reserved for internal routing.',- }),name: z.string().min(1, 'createCustomTool: name is required'),description: z.string().min(1, 'createCustomTool: description is required'),/**- * Composio toolkit slug that this tool requires an active connection for.+ * Composio toolkit slug that this tool extends (requires an active connection for).* Set this to the toolkit whose auth your tool needs (e.g. `'meta_ads'`, `'gmail'`).* Leave empty for tools that don't need any Composio-managed authentication.*/- toolkit: z.string().optional(),+ extendsToolkit: z.string().optional(),});/** Options for creating a custom tool via `createCustomTool()`. */@@ -122,25 +131,28 @@ export type CreateCustomToolParams<T extends z.ZodType> = z.infer<> & {/** Zod schema for input parameters */inputParams: T;+ /** Optional Zod schema for output parameters (sent to backend for documentation) */+ outputParams?: z.ZodType;/** The function that executes the tool */execute: CustomToolExecuteFn<T>;};/*** Custom tool definition returned from `createCustomTool()`.- * Pass to `composio.create(userId, { customTools: [...] })` to bind to a session.+ * Pass to `composio.create(userId, { experimental: { customTools: [...] } })` to bind to a session.*/export interface CustomTool {readonly slug: string;readonly name: string;readonly description: string;/**- * Composio toolkit slug that this tool requires an active connection for.- * Set this to the toolkit whose auth your tool needs (e.g. `'meta_ads'`, `'gmail'`).+ * Composio toolkit slug that this tool extends (requires an active connection for).* Undefined means the tool doesn't need any Composio-managed authentication.*/- readonly toolkit?: string;+ readonly extendsToolkit?: string;readonly inputSchema: Record<string, unknown>;+ /** JSON Schema representation of the output (for backend documentation) */+ readonly outputSchema?: Record<string, unknown>;/** @internal Original Zod schema — used for runtime input validation (defaults, coercions, transforms) */readonly inputParams: z.ZodType;/** Direct reference to the execute function — useful for testing */@@ -153,9 +165,54 @@ export interface CustomToolDefinition {name: string;description: string;input_schema: Record<string, unknown>;- toolkit?: string;+ output_schema?: Record<string, unknown>;+ /** Mapped from `extendsToolkit`. Omitted for standalone tools. */+ extends_toolkit?: string;+}++// ────────────────────────────────────────────────────────────────+// Custom toolkit types+// ────────────────────────────────────────────────────────────────++/**+ * Zod schema for validating the string/scalar fields of createCustomToolkit() options.+ * Slug is validated separately as the first argument.+ */+export const CreateCustomToolkitBaseSchema = z.object({+ name: z.string().min(1, 'createCustomToolkit: name is required'),+ description: z.string().min(1, 'createCustomToolkit: description is required'),+});++/** Options for creating a custom toolkit via `createCustomToolkit()`. */+export type CreateCustomToolkitParams = z.infer<typeof CreateCustomToolkitBaseSchema> & {+ /** Tools to include in this toolkit. Must not have `extendsToolkit` set. */+ tools: CustomTool[];+};++/**+ * Custom toolkit definition returned from `createCustomToolkit()`.+ * Pass to `composio.create(userId, { experimental: { customToolkits: [...] } })`.+ */+export interface CustomToolkit {+ readonly slug: string;+ readonly name: string;+ readonly description: string;+ readonly tools: readonly CustomTool[];}+/** Serialized toolkit definition sent to backend. */+export interface CustomToolkitDefinition {+ slug: string;+ name: string;+ description: string;+ /** Nested tools — no extends_toolkit, they inherit the toolkit identity from the parent. */+ tools: Omit<CustomToolDefinition, 'extends_toolkit'>[];+}++// ────────────────────────────────────────────────────────────────+// Internal routing types+// ────────────────────────────────────────────────────────────────+/** @internal Entry in the per-session custom tools routing map. */export type CustomToolsMapEntry = {handle: CustomTool;diff --git a/ts/packages/core/src/types/toolRouter.types.ts b/ts/packages/core/src/types/toolRouter.types.tsindex eaa51483a..e82cb7357 100644--- a/ts/packages/core/src/types/toolRouter.types.ts+++ b/ts/packages/core/src/types/toolRouter.types.ts@@ -3,7 +3,7 @@ import type { BaseComposioProvider } from '../provider/BaseProvider';import { SessionMetaToolOptions } from './modifiers.types';import { ConnectionRequest } from './connectionRequest.types';import type { ToolRouterSessionFilesMount } from '../models/ToolRouterSessionFileMount';-import type { CustomTool } from './customTool.types';+import type { CustomTool, CustomToolkit } from './customTool.types';export const MCPServerTypeSchema = z.enum(['http', 'sse']);export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;@@ -213,15 +213,21 @@ export const ToolRouterCreateSessionConfigSchema = z}).optional().describe('Configuration for assistive prompt generation'),+ customTools: z+ .array(z.custom<CustomTool>())+ .optional()+ .describe(+ 'Custom tools to include in this session. Created via createCustomTool() from @composio/core/experimental.'+ ),+ customToolkits: z+ .array(z.custom<CustomToolkit>())+ .optional()+ .describe(+ 'Custom toolkits to include in this session. Created via createCustomToolkit() from @composio/core/experimental.'+ ),}).optional().describe('Experimental features configuration - not stable, may be modified or removed'),- customTools: z- .array(z.custom<CustomTool>())- .optional()- .describe(- 'Custom tools to include in this session. Created via createCustomTool() from @composio/core/experimental.'- ),}).partial().describe('The config for the tool router session');@@ -425,6 +431,32 @@ export type ToolRouterSessionExecuteFn = (arguments_?: Record<string, unknown>) => Promise<ToolRouterSessionExecuteResponse>;+export const SessionProxyExecuteParamsSchema = z.object({+ /** The toolkit whose connected account to use for auth (e.g. 'gmail', 'github') */+ toolkit: z.string(),+ /** The API endpoint URL to call */+ endpoint: z.string(),+ /** HTTP method */+ method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']),+ /** Request body (for POST/PUT/PATCH) */+ body: z.unknown().optional(),+ /** Query params or headers to include */+ parameters: z+ .array(+ z.object({+ in: z.enum(['query', 'header']),+ name: z.string(),+ value: z.union([z.string(), z.number()]),+ })+ )+ .optional(),+});+export type SessionProxyExecuteParams = z.infer<typeof SessionProxyExecuteParamsSchema>;++export type ToolRouterSessionProxyExecuteFn = (+ params: SessionProxyExecuteParams+) => Promise<ToolRouterSessionExecuteResponse>;+/** Session type returned by ToolRouter.create() and ToolRouter.use() */export interface Session<TToolCollection,@@ -440,8 +472,8 @@ export interface Session<search: ToolRouterSessionSearchFn;/** Execute a tool within the session */execute: ToolRouterSessionExecuteFn;- /** Get provider-wrapped custom tools for MCP flows */- localTools: () => Promise<ReturnType<TProvider['wrapTools']>>;+ /** Proxy an API call through Composio's auth layer using the session's connected account */+ proxyExecute: ToolRouterSessionProxyExecuteFn;/** Experimental features (files, assistive prompt, etc.) */experimental: SessionExperimental;}diff --git a/ts/packages/core/test/models/customTool.test.ts b/ts/packages/core/test/models/customTool.test.tsindex 0f6a8ab11..abb2d2c96 100644--- a/ts/packages/core/test/models/customTool.test.ts+++ b/ts/packages/core/test/models/customTool.test.ts@@ -1,8 +1,15 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { z } from 'zod/v3';-import { createCustomTool, buildCustomToolsMap, serializeCustomTools, LOCAL_TOOL_PREFIX } from '../../src/models/CustomTool';+import {+ createCustomTool,+ createCustomToolkit,+ buildCustomToolsMap,+ serializeCustomTools,+ serializeCustomToolkits,+ LOCAL_TOOL_PREFIX,+} from '../../src/models/CustomTool';import { SessionContextImpl } from '../../src/models/SessionContext';-import type { CustomTool, SessionContext } from '../../src/types/customTool.types';+import type { CustomTool, CustomToolkit, SessionContext } from '../../src/types/customTool.types';// ────────────────────────────────────────────────────────────────// createCustomTool() factory@@ -10,7 +17,6 @@ import type { CustomTool, SessionContext } from '../../src/types/customTool.typedescribe('createCustomTool', () => {const baseOptions = {- slug: 'GET_USER_CONTEXT',name: 'Get user context',description: 'Retrieve what we know about a user',inputParams: z.object({@@ -20,12 +26,12 @@ describe('createCustomTool', () => {};it('should return a valid tool with correct fields', () => {- const tool = createCustomTool(baseOptions);+ const tool = createCustomTool('GET_USER_CONTEXT', baseOptions);expect(tool.slug).toBe('GET_USER_CONTEXT');expect(tool.name).toBe('Get user context');expect(tool.description).toBe('Retrieve what we know about a user');- expect(tool.toolkit).toBeUndefined();+ expect(tool.extendsToolkit).toBeUndefined();expect(tool.execute).toBe(baseOptions.execute);expect(tool.inputSchema).toMatchObject({type: 'object',@@ -37,13 +43,37 @@ describe('createCustomTool', () => {expect(tool.inputParams).toBe(baseOptions.inputParams);});- it('should include toolkit when provided', () => {- const tool = createCustomTool({ ...baseOptions, toolkit: 'meta_ads' });- expect(tool.toolkit).toBe('meta_ads');+ it('should include extendsToolkit when provided', () => {+ const tool = createCustomTool('GET_AD_ACCOUNTS', { ...baseOptions, extendsToolkit: 'meta_ads' });+ expect(tool.extendsToolkit).toBe('meta_ads');+ });++ it('should convert outputParams to JSON Schema when provided', () => {+ const tool = createCustomTool('WITH_OUTPUT', {+ ...baseOptions,+ outputParams: z.object({+ result: z.string(),+ count: z.number(),+ }),+ });++ expect(tool.outputSchema).toMatchObject({+ type: 'object',+ properties: {+ result: { type: 'string' },+ count: { type: 'number' },+ },+ required: ['result', 'count'],+ });+ });++ it('should not have outputSchema when outputParams is not provided', () => {+ const tool = createCustomTool('NO_OUTPUT', baseOptions);+ expect(tool.outputSchema).toBeUndefined();});it('should convert Zod schema with optional fields correctly', () => {- const tool = createCustomTool({+ const tool = createCustomTool('OPT_FIELDS', {...baseOptions,inputParams: z.object({required_field: z.string(),@@ -62,7 +92,7 @@ describe('createCustomTool', () => {});it('should convert Zod schema with defaults correctly', () => {- const tool = createCustomTool({+ const tool = createCustomTool('DEFAULTS', {...baseOptions,inputParams: z.object({category: z.string().default('all'),@@ -77,41 +107,53 @@ describe('createCustomTool', () => {});});- describe('validation', () => {- it('should throw if slug is missing', () => {- expect(() => createCustomTool({ ...baseOptions, slug: '' })).toThrow('slug is required');+ describe('slug validation', () => {+ it('should throw if slug is empty', () => {+ expect(() => createCustomTool('', baseOptions)).toThrow('slug is required');});it('should throw if slug starts with LOCAL_ prefix', () => {- expect(() => createCustomTool({ ...baseOptions, slug: 'LOCAL_MY_TOOL' })).toThrow(- /LOCAL_/- );+ expect(() => createCustomTool('LOCAL_MY_TOOL', baseOptions)).toThrow(/LOCAL_/);});it('should throw if slug starts with local_ prefix (case-insensitive)', () => {- expect(() => createCustomTool({ ...baseOptions, slug: 'local_something' })).toThrow(- /LOCAL_/- );+ expect(() => createCustomTool('local_something', baseOptions)).toThrow(/LOCAL_/);});+ it('should throw if slug contains invalid characters', () => {+ expect(() => createCustomTool('MY TOOL', baseOptions)).toThrow(/alphanumeric/);+ expect(() => createCustomTool('MY.TOOL', baseOptions)).toThrow(/alphanumeric/);+ expect(() => createCustomTool('MY@TOOL', baseOptions)).toThrow(/alphanumeric/);+ });++ it('should allow underscores and hyphens in slug', () => {+ const tool1 = createCustomTool('MY_TOOL', baseOptions);+ expect(tool1.slug).toBe('MY_TOOL');++ const tool2 = createCustomTool('my-tool', baseOptions);+ expect(tool2.slug).toBe('my-tool');+ });+ });++ describe('other validation', () => {it('should throw if name is missing', () => {- expect(() => createCustomTool({ ...baseOptions, name: '' })).toThrow('name is required');+ expect(() => createCustomTool('SLUG', { ...baseOptions, name: '' })).toThrow('name is required');});it('should throw if description is missing', () => {- expect(() => createCustomTool({ ...baseOptions, description: '' })).toThrow(+ expect(() => createCustomTool('SLUG', { ...baseOptions, description: '' })).toThrow('description is required');});it('should throw if inputParams is missing', () => {- expect(() => createCustomTool({ ...baseOptions, inputParams: null as any })).toThrow(+ expect(() => createCustomTool('SLUG', { ...baseOptions, inputParams: null as any })).toThrow('inputParams is required');});it('should throw if execute is not a function', () => {- expect(() => createCustomTool({ ...baseOptions, execute: 'not-fn' as any })).toThrow(+ expect(() => createCustomTool('SLUG', { ...baseOptions, execute: 'not-fn' as any })).toThrow('execute must be a function');});@@ -121,12 +163,11 @@ describe('createCustomTool', () => {it('should allow no-session execute (input only)', async () => {const noSessionExecute = vi.fn().mockResolvedValue({ result: 42 });- const tool = createCustomTool({+ const tool = createCustomTool('NO_SESSION', {...baseOptions,execute: noSessionExecute,});- // Call without session — JS ignores extra paramsconst result = await tool.execute({ category: 'test' } as any);expect(result.result).toBe(42);expect(noSessionExecute).toHaveBeenCalledWith({ category: 'test' });@@ -135,7 +176,7 @@ describe('createCustomTool', () => {it('should allow session-based execute (input + session)', async () => {const sessionExecute = vi.fn().mockResolvedValue({ userId: 'u1' });- const tool = createCustomTool({+ const tool = createCustomTool('WITH_SESSION', {...baseOptions,execute: sessionExecute,});@@ -153,49 +194,204 @@ describe('createCustomTool', () => {});});+// ────────────────────────────────────────────────────────────────+// createCustomToolkit() factory+// ────────────────────────────────────────────────────────────────++describe('createCustomToolkit', () => {+ const baseTool = createCustomTool('GREP', {+ name: 'Grep',+ description: 'Search files',+ inputParams: z.object({ pattern: z.string() }),+ execute: vi.fn().mockResolvedValue({}),+ });++ it('should return a valid toolkit with correct fields', () => {+ const tk = createCustomToolkit('DEV_TOOLS', {+ name: 'Dev Tools',+ description: 'Local dev utilities',+ tools: [baseTool],+ });++ expect(tk.slug).toBe('DEV_TOOLS');+ expect(tk.name).toBe('Dev Tools');+ expect(tk.description).toBe('Local dev utilities');+ expect(tk.tools).toHaveLength(1);+ expect(tk.tools[0].slug).toBe('GREP');+ });++ it('should throw if slug is empty', () => {+ expect(() =>+ createCustomToolkit('', { name: 'X', description: 'X', tools: [baseTool] })+ ).toThrow('slug is required');+ });++ it('should throw if slug starts with LOCAL_', () => {+ expect(() =>+ createCustomToolkit('LOCAL_TK', { name: 'X', description: 'X', tools: [baseTool] })+ ).toThrow(/LOCAL_/);+ });++ it('should throw if slug contains invalid characters', () => {+ expect(() =>+ createCustomToolkit('MY TOOLKIT', { name: 'X', description: 'X', tools: [baseTool] })+ ).toThrow(/alphanumeric/);+ });++ it('should throw if name is missing', () => {+ expect(() =>+ createCustomToolkit('TK', { name: '', description: 'X', tools: [baseTool] })+ ).toThrow('name is required');+ });++ it('should throw if description is missing', () => {+ expect(() =>+ createCustomToolkit('TK', { name: 'X', description: '', tools: [baseTool] })+ ).toThrow('description is required');+ });++ it('should throw if tools array is empty', () => {+ expect(() =>+ createCustomToolkit('TK', { name: 'X', description: 'X', tools: [] })+ ).toThrow('at least one tool is required');+ });++ it('should reject tools with extendsToolkit set', () => {+ const extendsTool = createCustomTool('EXTENDS_TOOL', {+ name: 'Extends',+ description: 'Has extendsToolkit',+ extendsToolkit: 'gmail',+ inputParams: z.object({}),+ execute: vi.fn().mockResolvedValue({}),+ });++ expect(() =>+ createCustomToolkit('TK', { name: 'X', description: 'X', tools: [extendsTool] })+ ).toThrow('extendsToolkit');+ });+});+// ────────────────────────────────────────────────────────────────// buildCustomToolsMap()// ────────────────────────────────────────────────────────────────describe('buildCustomToolsMap', () => {- const makeTool = (slug: string): CustomTool => ({+ const makeTool = (slug: string, extendsToolkit?: string): CustomTool => ({slug,name: `Tool ${slug}`,description: `Description for ${slug}`,+ extendsToolkit,inputSchema: { type: 'object', properties: {} },inputParams: z.object({}),execute: vi.fn(),});- it('should create maps with both prefixed and original slug keys', () => {- const tools = [makeTool('MY_TOOL'), makeTool('OTHER_TOOL')];- const map = buildCustomToolsMap(tools);+ describe('standalone tools (no extendsToolkit)', () => {+ it('should prefix as LOCAL_<SLUG>', () => {+ const map = buildCustomToolsMap([makeTool('MY_TOOL')]);++ expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);+ expect(map.byOriginal.has('MY_TOOL')).toBe(true);+ });++ it('should handle case-insensitive slugs (uppercased internally)', () => {+ const map = buildCustomToolsMap([makeTool('my_tool')]);++ expect(map.byOriginal.has('MY_TOOL')).toBe(true);+ expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);+ });+ });++ describe('tools with extendsToolkit', () => {+ it('should prefix as LOCAL_<EXTENDS_TOOLKIT>_<SLUG>', () => {+ const map = buildCustomToolsMap([makeTool('GET_EMAILS', 'gmail')]);++ expect(map.byPrefixed.has('LOCAL_GMAIL_GET_EMAILS')).toBe(true);+ expect(map.byOriginal.has('GET_EMAILS')).toBe(true);+ });+ });- expect(map.byPrefixed.size).toBe(2);- expect(map.byOriginal.size).toBe(2);+ describe('toolkit tools', () => {+ it('should prefix as LOCAL_<TOOLKIT_SLUG>_<TOOL_SLUG>', () => {+ const sed = makeTool('SED');+ const tk: CustomToolkit = {+ slug: 'DEV_TOOLS',+ name: 'Dev Tools',+ description: 'Utilities',+ tools: [sed],+ };- // Prefixed lookup- expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);- expect(map.byPrefixed.has('LOCAL_OTHER_TOOL')).toBe(true);+ const map = buildCustomToolsMap([], [tk]);- // Original lookup- expect(map.byOriginal.has('MY_TOOL')).toBe(true);- expect(map.byOriginal.has('OTHER_TOOL')).toBe(true);+ expect(map.byPrefixed.has('LOCAL_DEV_TOOLS_SED')).toBe(true);+ expect(map.byOriginal.has('SED')).toBe(true);+ });});- it('should handle case-insensitive slugs (uppercased internally)', () => {- const tool = makeTool('my_tool');- const map = buildCustomToolsMap([tool]);+ describe('mixed tools and toolkits', () => {+ it('should handle standalone + toolkit tools together', () => {+ const grep = makeTool('GREP');+ const sed = makeTool('SED');+ const tk: CustomToolkit = {+ slug: 'DEV_TOOLS',+ name: 'Dev Tools',+ description: 'Utilities',+ tools: [sed],+ };++ const map = buildCustomToolsMap([grep], [tk]);- expect(map.byOriginal.has('MY_TOOL')).toBe(true);- expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);+ expect(map.byPrefixed.size).toBe(2);+ expect(map.byPrefixed.has('LOCAL_GREP')).toBe(true);+ expect(map.byPrefixed.has('LOCAL_DEV_TOOLS_SED')).toBe(true);+ });});- it('should throw on duplicate slugs', () => {- const tools = [makeTool('DUPE'), makeTool('DUPE')];- expect(() => buildCustomToolsMap(tools)).toThrow('duplicate slug "DUPE"');+ describe('collision detection', () => {+ it('should throw on duplicate standalone slugs', () => {+ expect(() => buildCustomToolsMap([makeTool('DUPE'), makeTool('DUPE')])).toThrow(+ 'collision'+ );+ });++ it('should throw on cross-group collision (standalone vs toolkit same original slug)', () => {+ const standalone = makeTool('SED');+ const tkTool = makeTool('SED');+ const tk: CustomToolkit = {+ slug: 'DEV_TOOLS',+ name: 'Dev Tools',+ description: 'Utilities',+ tools: [tkTool],+ };++ expect(() => buildCustomToolsMap([standalone], [tk])).toThrow('collision');+ });});+ describe('length validation', () => {+ it('should throw when prefixed slug exceeds 60 characters with contextual error', () => {+ const longSlug = 'A'.repeat(56); // LOCAL_ + 56 = 62 > 60+ expect(() => buildCustomToolsMap([makeTool(longSlug)])).toThrow('too long');+ });++ it('should show available length in error for toolkit tools', () => {+ const longSlug = 'A'.repeat(50); // LOCAL_DEV_TOOLS_ + 50 = 66 > 60+ const tk: CustomToolkit = {+ slug: 'DEV_TOOLS',+ name: 'Dev Tools',+ description: 'Utilities',+ tools: [makeTool(longSlug)],+ };++ expect(() => buildCustomToolsMap([], [tk])).toThrow(/Shorten the slug to at most/);+ });++ it('should accept slugs that fit within 60 chars', () => {+ const slug = 'A'.repeat(54); // LOCAL_ + 54 = 60 exactly+ const map = buildCustomToolsMap([makeTool(slug)]);+ expect(map.byPrefixed.size).toBe(1);+ });+ });});// ────────────────────────────────────────────────────────────────@@ -203,12 +399,12 @@ describe('buildCustomToolsMap', () => {// ────────────────────────────────────────────────────────────────describe('serializeCustomTools', () => {- it('should serialize tools into backend format', () => {+ it('should serialize tools with extendsToolkit as extends_toolkit', () => {const tool: CustomTool = {slug: 'GET_DATA',name: 'Get Data',description: 'Gets some data',- toolkit: 'my_toolkit',+ extendsToolkit: 'my_toolkit',inputSchema: { type: 'object', properties: { id: { type: 'string' } } },inputParams: z.object({ id: z.string() }),execute: vi.fn(),@@ -221,13 +417,13 @@ describe('serializeCustomTools', () => {slug: 'GET_DATA',name: 'Get Data',description: 'Gets some data',- toolkit: 'my_toolkit',+ extends_toolkit: 'my_toolkit',input_schema: { type: 'object', properties: { id: { type: 'string' } } },},]);});- it('should omit toolkit when not provided', () => {+ it('should omit extends_toolkit when extendsToolkit is not provided', () => {const tool: CustomTool = {slug: 'NO_TOOLKIT',name: 'No Toolkit',@@ -238,7 +434,66 @@ describe('serializeCustomTools', () => {};const result = serializeCustomTools([tool]);- expect(result[0]).not.toHaveProperty('toolkit');+ expect(result[0]).not.toHaveProperty('extends_toolkit');+ });++ it('should include output_schema when outputSchema is present', () => {+ const tool: CustomTool = {+ slug: 'WITH_OUTPUT',+ name: 'With Output',+ description: 'Has output schema',+ inputSchema: { type: 'object', properties: {} },+ outputSchema: { type: 'object', properties: { result: { type: 'string' } } },+ inputParams: z.object({}),+ execute: vi.fn(),+ };++ const result = serializeCustomTools([tool]);+ expect(result[0].output_schema).toEqual({+ type: 'object',+ properties: { result: { type: 'string' } },+ });+ });+});++// ────────────────────────────────────────────────────────────────+// serializeCustomToolkits()+// ────────────────────────────────────────────────────────────────++describe('serializeCustomToolkits', () => {+ it('should serialize toolkits with their tools', () => {+ const tool: CustomTool = {+ slug: 'SED',+ name: 'Sed Replace',+ description: 'Find and replace',+ inputSchema: { type: 'object', properties: { pattern: { type: 'string' } } },+ inputParams: z.object({ pattern: z.string() }),+ execute: vi.fn(),+ };+ const tk: CustomToolkit = {+ slug: 'DEV_TOOLS',+ name: 'Dev Tools',+ description: 'Dev utilities',+ tools: [tool],+ };++ const result = serializeCustomToolkits([tk]);++ expect(result).toEqual([+ {+ slug: 'DEV_TOOLS',+ name: 'Dev Tools',+ description: 'Dev utilities',+ tools: [+ {+ slug: 'SED',+ name: 'Sed Replace',+ description: 'Find and replace',+ input_schema: { type: 'object', properties: { pattern: { type: 'string' } } },+ },+ ],+ },+ ]);});});@@ -299,11 +554,45 @@ describe('SessionContextImpl', () => {expect(result.error).toBe('something went wrong');});- it('should throw on proxyExecute() (not yet implemented)', async () => {+ it('should call session proxy_execute endpoint via proxyExecute()', async () => {+ const mockPost = vi.fn().mockResolvedValue({+ data: { proxy_result: true },+ error: null,+ log_id: 'log_proxy',+ });+ const clientWithPost = { ...mockClient, post: mockPost };+ const ctx = new SessionContextImpl(clientWithPost as any, 'user_1', 'sess_1');++ const result = await ctx.proxyExecute({+ toolkit: 'github',+ endpoint: 'https://api.github.com/user',+ method: 'GET',+ parameters: [{ in: 'header' as const, name: 'X-Custom', value: 'val' }],+ });++ expect(mockPost).toHaveBeenCalledWith(+ '/api/v3/tool_router/session/sess_1/proxy_execute',+ {+ body: {+ toolkit_slug: 'github',+ endpoint: 'https://api.github.com/user',+ method: 'GET',+ parameters: [{ name: 'X-Custom', type: 'header', value: 'val' }],+ },+ }+ );+ expect(result).toEqual({+ data: { proxy_result: true },+ error: null,+ successful: true,+ });+ });++ it('should throw on proxyExecute() with invalid params', async () => {const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');await expect(- ctx.proxyExecute({ endpoint: '/test', method: 'GET' })- ).rejects.toThrow('proxyExecute is not yet implemented');+ ctx.proxyExecute({ toolkit: 'github', endpoint: '/test', method: 'INVALID' as any })+ ).rejects.toThrow('Invalid proxy execute parameters');});describe('sibling local tool routing', () => {@@ -317,7 +606,6 @@ describe('SessionContextImpl', () => {expect(tryLocalExecute).toHaveBeenCalledWith('SIBLING_TOOL', { key: 'val' });expect(result).toEqual({ data: { local: true }, error: null, successful: true });- // Should NOT call remoteexpect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();});diff --git a/ts/packages/core/test/models/customToolRouting.test.ts b/ts/packages/core/test/models/customToolRouting.test.tsindex 70cb65ad4..e016bcedb 100644--- a/ts/packages/core/test/models/customToolRouting.test.ts+++ b/ts/packages/core/test/models/customToolRouting.test.ts@@ -65,8 +65,7 @@ const createMockClient = () => ({// Execute returns data directly (simplified API)const localExecute = vi.fn().mockResolvedValue({ local_result: true });-const customToolHandle = createCustomTool({- slug: 'GET_USER_CONTEXT',+const customToolHandle = createCustomTool('GET_USER_CONTEXT', {name: 'Get user context',description: 'Retrieve user preferences',inputParams: z.object({ category: z.string() }),@@ -77,11 +76,10 @@ const sessionExecute = vi.fn().mockImplementation(async (input: any, session: anuserId: session.userId,}));-const sessionToolHandle = createCustomTool({- slug: 'GET_AD_ACCOUNTS',+const sessionToolHandle = createCustomTool('GET_AD_ACCOUNTS', {name: 'Get ad accounts',description: 'Get ad account IDs',- toolkit: 'meta_ads',+ extendsToolkit: 'meta_ads',inputParams: z.object({ fields: z.string() }),execute: sessionExecute,});@@ -113,7 +111,7 @@ const captureExecuteFn = (provider: MockProvider) => {};// ────────────────────────────────────────────────────────────────-// ToolRouter.create() with customTools+// ToolRouter.create() with customTools under experimental// ────────────────────────────────────────────────────────────────describe('ToolRouter.create() with customTools', () => {@@ -129,14 +127,16 @@ describe('ToolRouter.create() with customTools', () => {});});- it('should send custom_tools in the create payload', async () => {+ it('should send custom_tools under experimental in the create payload', async () => {await router.create('user_1', {toolkits: ['gmail'],- customTools: [customToolHandle],+ experimental: {+ customTools: [customToolHandle],+ },});const payload = mockClient.toolRouter.session.create.mock.calls[0][0];- expect(payload.custom_tools).toEqual([+ expect(payload.experimental.custom_tools).toEqual([{slug: 'GET_USER_CONTEXT',name: 'Get user context',@@ -146,27 +146,33 @@ describe('ToolRouter.create() with customTools', () => {]);});- it('should include toolkit in custom_tools when toolkit is present', async () => {+ it('should include extendsToolkit as extends_toolkit in serialized custom_tools', async () => {await router.create('user_1', {- customTools: [sessionToolHandle],+ experimental: {+ customTools: [sessionToolHandle],+ },});const payload = mockClient.toolRouter.session.create.mock.calls[0][0];- expect(payload.custom_tools[0].toolkit).toBe('meta_ads');+ expect(payload.experimental.custom_tools[0].extends_toolkit).toBe('meta_ads');});- it('should not send custom_tools when customTools is omitted or empty', async () => {+ it('should not send experimental.custom_tools when customTools is omitted or empty', async () => {await router.create('user_1', { toolkits: ['gmail'] });- expect(mockClient.toolRouter.session.create.mock.calls[0][0].custom_tools).toBeUndefined();+ const payload1 = mockClient.toolRouter.session.create.mock.calls[0][0];+ expect(payload1.experimental).toBeUndefined();vi.clearAllMocks();- await router.create('user_1', { customTools: [] });- expect(mockClient.toolRouter.session.create.mock.calls[0][0].custom_tools).toBeUndefined();+ await router.create('user_1', { experimental: { customTools: [] } });+ const payload2 = mockClient.toolRouter.session.create.mock.calls[0][0];+ expect(payload2.experimental).toBeUndefined();});it('should return a session with the correct sessionId', async () => {const session = await router.create('user_1', {- customTools: [customToolHandle],+ experimental: {+ customTools: [customToolHandle],+ },});expect(session.sessionId).toBe('sess_123');@@ -210,14 +216,12 @@ describe('ToolRouterSession execution routing', () => {const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });- // User returns data directly, SDK wraps itexpect(result.data).toEqual({ local_result: true });expect(result.logId).toBe('local');expect(localExecute).toHaveBeenCalledWith({ category: 'prefs' },expect.objectContaining({ userId: 'user_1' }));- // Should NOT call remoteexpect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();});@@ -231,6 +235,17 @@ describe('ToolRouterSession execution routing', () => {expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();});+ it('should route extendsToolkit tool by prefixed slug', async () => {+ const session = createSession(mockClient, [sessionToolHandle]);++ // sessionToolHandle has extendsToolkit: 'meta_ads' → LOCAL_META_ADS_GET_AD_ACCOUNTS+ const result = await session.execute('LOCAL_META_ADS_GET_AD_ACCOUNTS', { fields: 'id' });++ expect(result.data).toEqual({ userId: 'user_1' });+ expect(sessionExecute).toHaveBeenCalled();+ expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();+ });+it('should be case-insensitive for local tool lookup', async () => {const session = createSession(mockClient, [customToolHandle]);@@ -276,14 +291,12 @@ describe('ToolRouterSession execution routing', () => {});it('should provide a working execute() on SessionContext for remote tools', async () => {- // Tool that calls a remote tool via session.execute()const chainedExecute = vi.fn().mockImplementation(async (input: any, session: any) => {const inner = await session.execute('GMAIL_SEND_EMAIL', { to: input.to });return { inner_result: inner.data };});- const chainedTool = createCustomTool({- slug: 'CHAINED_TOOL',+ const chainedTool = createCustomTool('CHAINED_TOOL', {name: 'Chained',description: 'Calls another tool',inputParams: z.object({ to: z.string() }),@@ -293,7 +306,6 @@ describe('ToolRouterSession execution routing', () => {const session = createSession(mockClient, [chainedTool]);await session.execute('CHAINED_TOOL', { to: '[email protected]' });- // The chained tool should have called session.execute, which calls the APIexpect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_123', {tool_slug: 'GMAIL_SEND_EMAIL',arguments: { to: '[email protected]' },@@ -301,23 +313,19 @@ describe('ToolRouterSession execution routing', () => {});it('should route sibling local tools in-process without hitting the API', async () => {- // Tool B — a sibling local toolconst siblingExecute = vi.fn().mockResolvedValue({ siblingData: 'from-B' });- const toolB = createCustomTool({- slug: 'TOOL_B',+ const toolB = createCustomTool('TOOL_B', {name: 'Tool B',description: 'Sibling tool',inputParams: z.object({ key: z.string() }),execute: siblingExecute,});- // Tool A — calls Tool B via session.execute()const toolAExecute = vi.fn().mockImplementation(async (input: any, session: any) => {const inner = await session.execute('TOOL_B', { key: input.value });return { fromA: true, fromB: inner.data };});- const toolA = createCustomTool({- slug: 'TOOL_A',+ const toolA = createCustomTool('TOOL_A', {name: 'Tool A',description: 'Calls sibling tool B',inputParams: z.object({ value: z.string() }),@@ -327,25 +335,21 @@ describe('ToolRouterSession execution routing', () => {const session = createSession(mockClient, [toolA, toolB]);const result = await session.execute('TOOL_A', { value: 'hello' });- // Tool B should have been called in-processexpect(siblingExecute).toHaveBeenCalledWith({ key: 'hello' },expect.objectContaining({ userId: 'user_1' }));- // Result should contain data from both toolsexpect(result.data).toEqual({fromA: true,fromB: { siblingData: 'from-B' },});- // Should NOT have called the remote API for Tool Bexpect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();});});describe('session.execute() — error handling', () => {it('should catch errors thrown by execute function and return error response', async () => {- const throwingTool = createCustomTool({- slug: 'THROWING_TOOL',+ const throwingTool = createCustomTool('THROWING_TOOL', {name: 'Throwing',description: 'Throws an error',inputParams: z.object({}),@@ -366,8 +370,7 @@ describe('ToolRouterSession execution routing', () => {category: input.category,}));- const toolWithDefaults = createCustomTool({- slug: 'DEFAULTS_TOOL',+ const toolWithDefaults = createCustomTool('DEFAULTS_TOOL', {name: 'Defaults',description: 'Tool with default values',inputParams: z.object({ category: z.string().default('all') }),@@ -377,7 +380,6 @@ describe('ToolRouterSession execution routing', () => {const session = createSession(mockClient, [toolWithDefaults]);const result = await session.execute('DEFAULTS_TOOL', {});- // Zod default should be appliedexpect(defaultExecute).toHaveBeenCalledWith({ category: 'all' },expect.anything()@@ -386,8 +388,7 @@ describe('ToolRouterSession execution routing', () => {});it('should return validation error for invalid input', async () => {- const strictTool = createCustomTool({- slug: 'STRICT_TOOL',+ const strictTool = createCustomTool('STRICT_TOOL', {name: 'Strict',description: 'Tool with strict input',inputParams: z.object({ count: z.number() }),@@ -402,8 +403,7 @@ describe('ToolRouterSession execution routing', () => {});it('should handle non-Error throws gracefully', async () => {- const throwingTool = createCustomTool({- slug: 'STRING_THROW',+ const throwingTool = createCustomTool('STRING_THROW', {name: 'String throw',description: 'Throws a string',inputParams: z.object({}),@@ -479,7 +479,6 @@ describe('ToolRouterSession execution routing', () => {sync_response_to_workbench: false,});- // All remote — goes to executeMetaToolexpect(result.data).toEqual({ remote: true });expect(localExecute).not.toHaveBeenCalled();});@@ -496,7 +495,6 @@ describe('ToolRouterSession execution routing', () => {queries: [{ use_case: 'send email' }],});- // COMPOSIO_SEARCH_TOOLS always goes remoteexpect(result.data).toEqual({ remote: true });});@@ -506,18 +504,15 @@ describe('ToolRouterSession execution routing', () => {{ apiKey: 'key', provider: new MockProvider() },'sess_123',{ type: 'http' as const, url: 'https://mcp.example.com/sess_123' }- // No customToolsMap, no userId);const result = await session.tools();- // Should use the standard pathexpect(result).toBe('wrapped-tools');});});describe('COMPOSIO_MULTI_EXECUTE_TOOL — detailed split/merge behavior', () => {- /** Helper: set up provider + session + capture executeFn + get latest Tools mock */const setupMultiExecute = async (client: ReturnType<typeof createMockClient>,customTools: CustomTool[]@@ -533,7 +528,6 @@ describe('ToolRouterSession execution routing', () => {return { executeFn, toolsInstance, provider, session };};- /** Build a backend-shaped results[] response */const backendResponse = (results: Array<{ tool_slug: string; data: any; error?: string }>,) => {@@ -560,7 +554,6 @@ describe('ToolRouterSession execution routing', () => {};};- /** Find a local tool result in the results[] array by slug */const findResult = (results: any[], slug: string) =>results.find((r: any) => r.tool_slug === slug);@@ -579,11 +572,9 @@ describe('ToolRouterSession execution routing', () => {sync_response_to_workbench: false,});- // Results is an array with both remote and local entriesconst { results } = result.data;expect(results).toHaveLength(2);- // Remote result comes first (from backend), local appended afterconst remote = findResult(results, 'GMAIL_SEND_EMAIL');const local = findResult(results, 'LOCAL_GET_USER_CONTEXT');expect(remote.response.data).toEqual({ sent: true });@@ -597,7 +588,7 @@ describe('ToolRouterSession execution routing', () => {const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {tools: [{ tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'batch' } },- { tool_slug: 'LOCAL_GET_AD_ACCOUNTS', arguments: { fields: 'id,name' } },+ { tool_slug: 'LOCAL_META_ADS_GET_AD_ACCOUNTS', arguments: { fields: 'id,name' } },],sync_response_to_workbench: false,});@@ -614,7 +605,7 @@ describe('ToolRouterSession execution routing', () => {const { results } = result.data;expect(results).toHaveLength(2);expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();- expect(findResult(results, 'LOCAL_GET_AD_ACCOUNTS')).toBeDefined();+ expect(findResult(results, 'LOCAL_META_ADS_GET_AD_ACCOUNTS')).toBeDefined();});it('should handle mixed batch with multiple locals + multiple remotes', async () => {@@ -634,21 +625,19 @@ describe('ToolRouterSession execution routing', () => {tools: [{ tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'x' } },{ tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: '[email protected]' } },- { tool_slug: 'LOCAL_GET_AD_ACCOUNTS', arguments: { fields: 'id' } },+ { tool_slug: 'LOCAL_META_ADS_GET_AD_ACCOUNTS', arguments: { fields: 'id' } },{ tool_slug: 'SLACK_POST_MESSAGE', arguments: { channel: '#dev' } },],sync_response_to_workbench: false,});- // All 4 tools should appear in results arrayconst { results } = result.data;expect(results).toHaveLength(4);expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();- expect(findResult(results, 'LOCAL_GET_AD_ACCOUNTS')).toBeDefined();+ expect(findResult(results, 'LOCAL_META_ADS_GET_AD_ACCOUNTS')).toBeDefined();expect(findResult(results, 'GMAIL_SEND_EMAIL')).toBeDefined();expect(findResult(results, 'SLACK_POST_MESSAGE')).toBeDefined();- // Backend only got the 2 remote toolsconst backendTools = toolsInstance.executeMetaTool.mock.calls[0][1].arguments.tools;expect(backendTools).toHaveLength(2);expect(backendTools.map((t: any) => t.tool_slug)).toEqual([@@ -656,15 +645,13 @@ describe('ToolRouterSession execution routing', () => {'SLACK_POST_MESSAGE',]);- // Both local execute fns were calledexpect(localExecute).toHaveBeenCalled();expect(sessionExecute).toHaveBeenCalled();expect(result.successful).toBe(true);});it('should surface errors from both local and remote tools', async () => {- const throwingHandle = createCustomTool({- slug: 'MIXED_THROWER',+ const throwingHandle = createCustomTool('MIXED_THROWER', {name: 'Throws in batch',description: 'Throws',inputParams: z.object({}),@@ -676,7 +663,6 @@ describe('ToolRouterSession execution routing', () => {[customToolHandle, throwingHandle]);- // Remote also returns an error for one tooltoolsInstance.executeMetaTool.mockResolvedValueOnce(backendResponse([{ tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } },@@ -697,21 +683,17 @@ describe('ToolRouterSession execution routing', () => {const { results } = result.data;expect(results).toHaveLength(4);- // Local successconst localOk = findResult(results, 'LOCAL_GET_USER_CONTEXT');expect(localOk.response.successful).toBe(true);- // Local error — data is empty, error is surfacedconst localErr = findResult(results, 'LOCAL_MIXED_THROWER');expect(localErr.response.successful).toBe(false);expect(localErr.response.error).toBe('batch-boom');expect(localErr.error).toBe('batch-boom');- // Remote error is also preserved (not dropped!)const remoteErr = findResult(results, 'SLACK_POST_MESSAGE');expect(remoteErr.response.error).toBe('auth failed');- // Top-level error reflects total failure countexpect(result.successful).toBe(false);expect(result.error).toContain('2 out of 4');});@@ -724,7 +706,6 @@ describe('ToolRouterSession execution routing', () => {sync_response_to_workbench: false,});- // Empty array → fallback to backend with full original inputexpect(toolsInstance.executeMetaTool).toHaveBeenCalledWith('COMPOSIO_MULTI_EXECUTE_TOOL',expect.objectContaining({@@ -742,13 +723,11 @@ describe('ToolRouterSession execution routing', () => {backendResponse([]));- // Malformed: string instead of object — should not crashconst result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {tools: ['not-an-object', null, { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'ok' } }],sync_response_to_workbench: false,});- // The valid local tool should still executeexpect(localExecute).toHaveBeenCalledWith({ category: 'ok' },expect.objectContaining({ userId: 'user_1' })@@ -758,11 +737,9 @@ describe('ToolRouterSession execution routing', () => {});it('should execute local and remote in parallel (not sequentially)', async () => {- // Track call timing to verify parallelismconst callOrder: string[] = [];- const slowLocalHandle = createCustomTool({- slug: 'SLOW_LOCAL',+ const slowLocalHandle = createCustomTool('SLOW_LOCAL', {name: 'Slow local',description: 'Slow',inputParams: z.object({}),@@ -798,16 +775,13 @@ describe('ToolRouterSession execution routing', () => {sync_response_to_workbench: false,});- // Both should start before either ends (parallel execution)const localStartIdx = callOrder.indexOf('local-start');const remoteStartIdx = callOrder.indexOf('remote-start');const localEndIdx = callOrder.indexOf('local-end');const remoteEndIdx = callOrder.indexOf('remote-end');- // Both startedexpect(localStartIdx).toBeGreaterThanOrEqual(0);expect(remoteStartIdx).toBeGreaterThanOrEqual(0);- // Both started before either finishedexpect(Math.max(localStartIdx, remoteStartIdx)).toBeLessThan(Math.min(localEndIdx, remoteEndIdx));@@ -818,14 +792,12 @@ describe('ToolRouterSession execution routing', () => {it('should route each tool to its correct execute function', async () => {const session = createSession(mockClient, [customToolHandle, sessionToolHandle]);- // First toolawait session.execute('GET_USER_CONTEXT', { category: 'prefs' });expect(localExecute).toHaveBeenCalled();expect(sessionExecute).not.toHaveBeenCalled();localExecute.mockClear();- // Second toolawait session.execute('GET_AD_ACCOUNTS', { fields: 'id' });expect(sessionExecute).toHaveBeenCalled();expect(localExecute).not.toHaveBeenCalled();@@ -871,7 +843,6 @@ describe('ToolRouterSession execution routing', () => {const { results } = result.data;expect(results).toHaveLength(3);- // Each tool has its own entryconst local = results.find((r: any) => r.tool_slug === 'LOCAL_GET_USER_CONTEXT');const gmail = results.find((r: any) => r.tool_slug === 'GMAIL_SEND_EMAIL');const slack = results.find((r: any) => r.tool_slug === 'SLACK_POST_MESSAGE');@@ -888,7 +859,7 @@ describe('ToolRouterSession execution routing', () => {const session = new ToolRouterSession(mockClient as unknown as ComposioClient,- { apiKey: 'key' } as any, // no provider+ { apiKey: 'key' } as any,'sess_123',{ type: 'http' as const, url: 'https://mcp.example.com/sess_123' },undefined,@@ -902,116 +873,4 @@ describe('ToolRouterSession execution routing', () => {});});- describe('localTools() method', () => {- it('should return wrapped tools with COMPOSIO_EXECUTE_LOCAL_TOOL slug', async () => {- const provider = new MockProvider();- captureExecuteFn(provider);- const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);-- const result = await session.localTools();-- expect(result).toBe('wrapped-tools-with-routing');- expect(provider.wrapTools).toHaveBeenCalled();-- const tools = (provider as any)._capturedTools;- expect(tools).toHaveLength(1);- expect(tools[0].slug).toBe('COMPOSIO_EXECUTE_LOCAL_TOOL');- });-- it('should route to local tool correctly when executing via localTools()', async () => {- const provider = new MockProvider();- captureExecuteFn(provider);- const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);-- await session.localTools();- const executeFn = (provider as any)._capturedExecuteFn;-- const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {- tool_slug: 'LOCAL_GET_USER_CONTEXT',- arguments: { category: 'test' },- });-- expect(result.data).toEqual({ local_result: true });- expect(result.successful).toBe(true);- expect(localExecute).toHaveBeenCalledWith(- { category: 'test' },- expect.objectContaining({ userId: 'user_1' })- );- });-- it('should return error when executing with invalid slug via localTools()', async () => {- const provider = new MockProvider();- captureExecuteFn(provider);- const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);-- await session.localTools();- const executeFn = (provider as any)._capturedExecuteFn;-- const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {- tool_slug: 'NON_EXISTENT_TOOL',- arguments: {},- });-- expect(result.successful).toBe(false);- expect(result.error).toContain('Custom tool "NON_EXISTENT_TOOL" not found');- expect(result.data).toEqual({});- });-- it('should throw when calling localTools() without custom tools', async () => {- const session = new ToolRouterSession(- mockClient as unknown as ComposioClient,- { apiKey: 'key', provider: new MockProvider() },- 'sess_123',- { type: 'http' as const, url: 'https://mcp.example.com/sess_123' }- // No customToolsMap, no userId- );-- await expect(session.localTools()).rejects.toThrow(- 'No custom tools are bound to this session.'- );- });- });-- describe('COMPOSIO_EXECUTE_LOCAL_TOOL interception in routing', () => {- it('should route COMPOSIO_EXECUTE_LOCAL_TOOL to the correct local tool via session.tools() routing', async () => {- const provider = new MockProvider();- captureExecuteFn(provider);- const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);-- await session.tools();- const executeFn = (provider as any)._capturedExecuteFn;-- const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {- tool_slug: 'LOCAL_GET_USER_CONTEXT',- arguments: { category: 'routing-test' },- });-- expect(result.data).toEqual({ local_result: true });- expect(result.successful).toBe(true);- expect(localExecute).toHaveBeenCalledWith(- { category: 'routing-test' },- expect.objectContaining({ userId: 'user_1' })- );- // Should NOT call remote- expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();- });-- it('should return error for COMPOSIO_EXECUTE_LOCAL_TOOL with unknown slug', async () => {- const provider = new MockProvider();- captureExecuteFn(provider);- const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);-- await session.tools();- const executeFn = (provider as any)._capturedExecuteFn;-- const result = await executeFn('COMPOSIO_EXECUTE_LOCAL_TOOL', {- tool_slug: 'DOES_NOT_EXIST',- arguments: {},- });-- expect(result.successful).toBe(false);- expect(result.error).toContain('Custom tool "DOES_NOT_EXIST" not found');- expect(result.data).toEqual({});- });- });});