@devries-cameron20 / composio-1 / commits / 2e1d70859
Fork 0

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

feat(core): add custom local tools for tool router sessions

Introduce CustomTool() factory and local execution routing so users can define in-process tools that participate in tool router search and execution alongside Composio-hosted tools. - CustomTool() standalone factory (importable from @composio/core/experimental) - SessionContext injected at execution time with userId, sessionId, execute(), proxyExecute() - Local tool definitions sent to backend for BM25 search indexing via session create - ToolRouterSession intercepts COMPOSIO_MULTI_EXECUTE_TOOL to route LOCAL_* tools in-process - session.execute() accepts both original and LOCAL_-prefixed slugs (case-insensitive) - 41 unit tests covering factory, routing, error handling, and SessionContext injection Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 10, 2026 at 15:37 UTC 2e1d708595c63d31315cd7374d55eb0a09cd2854
12 files changed +1285 -54
ts/packages/core/package.json
+14
@@ -74,6 +74,20 @@
74 "default": "./dist/index.cjs"
75 }
76 },
77 + "./experimental": {
78 + "import": {
79 + "types": "./dist/experimental/index.d.mts",
80 + "default": "./dist/experimental/index.mjs"
81 + },
82 + "require": {
83 + "types": "./dist/experimental/index.d.cts",
84 + "default": "./dist/experimental/index.cjs"
85 + },
86 + "default": {
87 + "types": "./dist/experimental/index.d.cts",
88 + "default": "./dist/experimental/index.cjs"
89 + }
90 + },
91 "./platform": {
92 "workerd": {
93 "types": "./dist/platform/workerd.d.mts",
ts/packages/core/src/experimental/index.ts new
+18
@@ -0,0 +1,18 @@
1 +/**
2 + * Experimental APIs for @composio/core.
3 + *
4 + * Import from '@composio/core/experimental'. These APIs may change
5 + * in future releases. When graduating to stable, they will move to
6 + * '@composio/core' — only the import path changes.
7 + */
8 +
9 +// Custom local tools
10 +export { CustomTool } from '../models/CustomTool';
11 +export { SessionContextImpl } from '../models/SessionContext';
12 +export type {
13 + CustomToolHandle,
14 + NewCustomToolOptions,
15 + CustomToolExecuteFn,
16 + CustomToolExecuteResponse,
17 + SessionContext,
18 +} from '../types/customTool.types';
ts/packages/core/src/index.ts
+3
@@ -11,6 +11,9 @@ export { MCP } from './models/MCP';
11 export { RemoteFile } from './models/RemoteFile';
12 export { createConnectionRequest } from './models/ConnectionRequest';
13 export { ToolRouterSession } from './models/ToolRouterSession';
14 +/** @experimental Create custom local tools — also available from '@composio/core/experimental' */
15 +export { CustomTool } from './models/CustomTool';
16 +export { SessionContextImpl } from './models/SessionContext';
17 export * from './types/provider.types';
18 export * from './types/customTool.types';
19 export * from './types/tool.types';
ts/packages/core/src/models/CustomTool.ts new
+166
@@ -0,0 +1,166 @@
1 +/**
2 + * @fileoverview Standalone factory function for creating custom local tools.
3 + *
4 + * Usage:
5 + * ```typescript
6 + * import { CustomTool } from '@composio/core/experimental';
7 + *
8 + * const myTool = CustomTool({
9 + * slug: 'GET_USER_CONTEXT',
10 + * name: 'Get user context',
11 + * description: 'Retrieve what we know about a user',
12 + * inputParams: z.object({ category: z.string() }),
13 + * execute: async (input) => ({ data: { ... }, error: null, successful: true }),
14 + * });
15 + * ```
16 + */
17 +import * as zodToJsonSchema from 'zod-to-json-schema';
18 +import { z } from 'zod/v3';
19 +import type {
20 + NewCustomToolOptions,
21 + CustomToolHandle,
22 + CustomToolExecuteFn,
23 + LocalToolsMap,
24 + LocalToolsMapEntry,
25 + LocalToolDefinition,
26 + InputParamsSchema,
27 +} from '../types/customTool.types';
28 +
29 +/** Prefix applied by the backend to local tool slugs for disambiguation. */
30 +export const LOCAL_TOOL_PREFIX = 'LOCAL_';
31 +
32 +/**
33 + * Create a custom local tool for use in tool router sessions.
34 + *
35 + * The returned handle is a lightweight reference containing the tool's metadata
36 + * and execute function. Pass it to `composio.create(userId, { customTools: [...] })`
37 + * to bind it to a session.
38 + *
39 + * @param options - Tool definition including slug, schema, and execute function
40 + * @returns A CustomToolHandle to pass to session creation
41 + *
42 + * @example No-auth tool
43 + * ```typescript
44 + * const getUserContext = CustomTool({
45 + * slug: 'GET_USER_CONTEXT',
46 + * name: 'Get user context',
47 + * description: 'Retrieve user preferences and history',
48 + * inputParams: z.object({ category: z.string().default('all') }),
49 + * execute: async (input) => ({
50 + * data: await db.userContext.find(input.category),
51 + * error: null,
52 + * successful: true,
53 + * }),
54 + * });
55 + * ```
56 + *
57 + * @example Auth tool with session context
58 + * ```typescript
59 + * const getAdAccounts = CustomTool({
60 + * slug: 'GET_AD_ACCOUNTS',
61 + * name: 'Get ad accounts',
62 + * description: 'Get Meta ad account IDs for the authenticated user',
63 + * toolkit: 'meta_ads',
64 + * inputParams: z.object({ fields: z.string().default('id,name') }),
65 + * execute: async (input, session) => ({
66 + * data: await session.proxyExecute({
67 + * endpoint: '/v21.0/me/adaccounts',
68 + * method: 'GET',
69 + * parameters: [{ in: 'query', name: 'fields', value: input.fields }],
70 + * }),
71 + * error: null,
72 + * successful: true,
73 + * }),
74 + * });
75 + * ```
76 + */
77 +export function CustomTool<T extends z.ZodType>(
78 + options: NewCustomToolOptions<T>
79 +): CustomToolHandle {
80 + const { slug, name, description, inputParams, execute, toolkit } = options;
81 +
82 + if (!slug) {
83 + throw new Error('CustomTool: slug is required');
84 + }
85 + if (!name) {
86 + throw new Error('CustomTool: name is required');
87 + }
88 + if (!description) {
89 + throw new Error('CustomTool: description is required');
90 + }
91 + if (!inputParams) {
92 + throw new Error('CustomTool: inputParams is required');
93 + }
94 + if (typeof execute !== 'function') {
95 + throw new Error('CustomTool: execute must be a function');
96 + }
97 +
98 + // Convert Zod schema → JSON Schema (reuses same pattern as legacy CustomTools.createTool)
99 + const paramsSchema = zodToJsonSchema.default(inputParams, {
100 + name: 'input',
101 + }) as InputParamsSchema;
102 + const paramsSchemaJson = paramsSchema.definitions.input;
103 +
104 + const inputSchema: Record<string, unknown> = {
105 + type: 'object',
106 + properties: paramsSchemaJson.properties,
107 + ...(paramsSchemaJson.required ? { required: paramsSchemaJson.required } : {}),
108 + };
109 +
110 + return {
111 + slug,
112 + name,
113 + description,
114 + toolkit,
115 + inputSchema,
116 + execute: execute as CustomToolExecuteFn<z.ZodType>,
117 + };
118 +}
119 +
120 +/**
121 + * Build a LocalToolsMap from an array of handles.
122 + * Used internally by ToolRouter.create() to construct the per-session routing map.
123 + *
124 + * @internal
125 + * @param handles - The custom tool handles to include in the session
126 + * @returns Maps for O(1) lookup by both prefixed and original slug
127 + * @throws If duplicate slugs are detected
128 + */
129 +export function buildLocalToolsMap(handles: CustomToolHandle[]): LocalToolsMap {
130 + const byPrefixed = new Map<string, LocalToolsMapEntry>();
131 + const byOriginal = new Map<string, LocalToolsMapEntry>();
132 +
133 + for (const handle of handles) {
134 + const upperSlug = handle.slug.toUpperCase();
135 + const prefixedSlug = `${LOCAL_TOOL_PREFIX}${upperSlug}`;
136 +
137 + if (byOriginal.has(upperSlug)) {
138 + throw new Error(`CustomTool: duplicate slug "${handle.slug}"`);
139 + }
140 +
141 + const entry: LocalToolsMapEntry = { handle, prefixedSlug };
142 + byPrefixed.set(prefixedSlug, entry);
143 + byOriginal.set(upperSlug, entry);
144 + }
145 +
146 + return { byPrefixed, byOriginal };
147 +}
148 +
149 +/**
150 + * Serialize custom tool handles into the format expected by the backend session creation API.
151 + *
152 + * @internal
153 + * @param handles - The custom tool handles to serialize
154 + * @returns Array of LocalToolDefinition for the API payload
155 + */
156 +export function serializeLocalTools(
157 + handles: CustomToolHandle[]
158 +): LocalToolDefinition[] {
159 + return handles.map(handle => ({
160 + slug: handle.slug,
161 + name: handle.name,
162 + description: handle.description,
163 + input_schema: handle.inputSchema,
164 + ...(handle.toolkit ? { toolkit: handle.toolkit } : {}),
165 + }));
166 +}
ts/packages/core/src/models/SessionContext.ts new
+61
@@ -0,0 +1,61 @@
1 +/**
2 + * @fileoverview Session context implementation injected into custom tool execute functions.
3 + */
4 +import { Composio as ComposioClient } from '@composio/client';
5 +import type { SessionContext } from '../types/customTool.types';
6 +import type { ToolExecuteResponse, ToolProxyParams } from '../types/tool.types';
7 +
8 +/**
9 + * Concrete implementation of SessionContext.
10 + * Built per local tool invocation inside ToolRouterSession.executeLocalTool().
11 + */
12 +export class SessionContextImpl implements SessionContext {
13 + public readonly userId: string;
14 + public readonly sessionId: string;
15 +
16 + constructor(
17 + private readonly client: ComposioClient,
18 + userId: string,
19 + sessionId: string
20 + ) {
21 + this.userId = userId;
22 + this.sessionId = sessionId;
23 + }
24 +
25 + /**
26 + * Execute any Composio native tool from within a custom tool.
27 + * Delegates to the tool router session execute endpoint.
28 + */
29 + async execute(
30 + toolSlug: string,
31 + arguments_: Record<string, unknown>
32 + ): Promise<ToolExecuteResponse> {
33 + const response = await this.client.toolRouter.session.execute(
34 + this.sessionId,
35 + {
36 + tool_slug: toolSlug,
37 + arguments: arguments_,
38 + }
39 + );
40 + return {
41 + data: response.data,
42 + error: response.error,
43 + successful: !response.error,
44 + };
45 + }
46 +
47 + /**
48 + * Proxy API calls through Composio's auth layer.
49 + * The session-scoped backend endpoint resolves the connected account automatically.
50 + *
51 + * TODO: Wire to session-scoped proxy endpoint (proxyExecuteForSessionRPC).
52 + * Currently a skeleton — will be connected to backend API.
53 + */
54 + async proxyExecute(_params: ToolProxyParams): Promise<ToolExecuteResponse> {
55 + // TODO: Call session-scoped proxy endpoint that resolves connected account from session.
56 + // Backend API: apps/apollo/src/lib/toolRouterV2/features/execution/proxyExecuteForSessionRPC.ts
57 + throw new Error(
58 + 'proxyExecute is not yet implemented. Session-scoped proxy endpoint pending backend support.'
59 + );
60 + }
61 +}
ts/packages/core/src/models/ToolRouter.ts
+23 -20
@@ -38,6 +38,8 @@ import {
38 transformToolRouterToolkitsParams,
39 } from '../lib/toolRouterParams';
40 import { ToolRouterSession } from './ToolRouterSession';
41 +import { buildLocalToolsMap, serializeLocalTools } from './CustomTool';
42 +import type { LocalToolsMap } from '../types/customTool.types';
43
44 export class ToolRouter<
45 TToolCollection,
@@ -77,29 +79,15 @@ export class ToolRouter<
79 * @example
80 * ```typescript
81 * import { Composio } from '@composio/core';
82 + * import { CustomTool } from '@composio/core/experimental';
83 *
84 * const composio = new Composio();
82 - * const userId = 'user_123';
85 *
84 - * const session = await composio.experimental.create(userId, {
86 + * const session = await composio.create('user_123', {
87 * toolkits: ['gmail'],
88 * manageConnections: true,
87 - * tools: {
88 - * gmail: {
89 - * disabled: ['gmail_send_email']
90 - * }
91 - * },
92 - * tags: ['readOnlyHint']
89 + * customTools: [myCustomTool],
90 * });
94 - *
95 - * console.log(session.sessionId);
96 - * console.log(session.mcp.url);
97 - *
98 - * // Get tools formatted for your framework (requires provider)
99 - * const tools = await session.tools();
100 - *
101 - * // Check toolkit connection states
102 - * const toolkits = await session.toolkits();
91 * ```
92 */
93 async create(
@@ -108,7 +96,11 @@ export class ToolRouter<
96 ): Promise<Session<TToolCollection, TTool, TProvider>> {
97 const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});
98
111 - const payload: SessionCreateParams = {
99 + // Build local tools map and backend payload from custom tool handles
100 + let localToolsMap: LocalToolsMap | undefined;
101 + const customTools = routerConfig.customTools;
102 +
103 + const payload: SessionCreateParams & { local_tools?: unknown } = {
104 user_id: userId,
105 auth_configs: routerConfig.authConfigs,
106 connected_accounts: routerConfig.connectedAccounts,
@@ -128,7 +120,16 @@ export class ToolRouter<
120 : undefined,
121 };
122
131 - const session = await this.client.toolRouter.session.create(payload);
123 + if (customTools?.length) {
124 + localToolsMap = buildLocalToolsMap(customTools);
125 + // Send definitions to backend for BM25 search indexing
126 + // Type assertion: @composio/client doesn't have local_tools yet (Hermes PR #8453)
127 + payload.local_tools = serializeLocalTools(customTools);
128 + }
129 +
130 + const session = await this.client.toolRouter.session.create(
131 + payload as SessionCreateParams
132 + );
133
134 const assistivePrompt =
135 session.experimental?.assistive_prompt;
@@ -138,7 +139,9 @@ export class ToolRouter<
139 this.config,
140 session.session_id,
141 this.createMCPServerConfig(session.mcp),
141 - { assistivePrompt }
142 + { assistivePrompt },
143 + localToolsMap,
144 + userId
145 );
146 }
147
ts/packages/core/src/models/ToolRouterSession.ts
+120 -33
@@ -25,6 +25,11 @@ import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';
25 import { ValidationError } from '../errors';
26 import { Tools } from './Tools';
27 import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';
28 +import type { LocalToolsMap, LocalToolsMapEntry } from '../types/customTool.types';
29 +import type { ToolExecuteResponse } from '../types/tool.types';
30 +import { SessionContextImpl } from './SessionContext';
31 +
32 +const COMPOSIO_MULTI_EXECUTE_TOOL = 'COMPOSIO_MULTI_EXECUTE_TOOL';
33
34 export class ToolRouterSession<
35 TToolCollection,
@@ -40,7 +45,9 @@ export class ToolRouterSession<
45 private readonly config: ComposioConfig<TProvider> | undefined,
46 sessionId: string,
47 mcp: ToolRouterMCPServerConfig,
43 - experimentalOverrides?: Pick<SessionExperimental, 'assistivePrompt'>
48 + experimentalOverrides?: Pick<SessionExperimental, 'assistivePrompt'>,
49 + private readonly localToolsMap?: LocalToolsMap,
50 + private readonly userId?: string
51 ) {
52 this.sessionId = sessionId;
53 this.mcp = mcp;
@@ -54,6 +61,9 @@ export class ToolRouterSession<
61 /**
62 * Get the tools available in the session, formatted for your AI framework.
63 * Requires a provider to be configured in the Composio constructor.
64 + *
65 + * When custom tools are bound to the session, execution of COMPOSIO_MULTI_EXECUTE_TOOL
66 + * is intercepted: local tools are executed in-process, remote tools are sent to the backend.
67 */
68 async tools(modifiers?: SessionMetaToolOptions): Promise<ReturnType<TProvider['wrapTools']>> {
69 const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
@@ -61,6 +71,38 @@ export class ToolRouterSession<
71 this.sessionId,
72 modifiers?.modifySchema ? { modifySchema: modifiers.modifySchema } : undefined
73 );
74 +
75 + if (this.hasLocalTools()) {
76 + // Create an execute function that routes between local and remote execution
77 + const routingExecuteFn = async (
78 + toolSlug: string,
79 + input: Record<string, unknown>
80 + ): Promise<ToolExecuteResponse> => {
81 + // Intercept COMPOSIO_MULTI_EXECUTE_TOOL and check if the inner tool is local
82 + if (toolSlug === COMPOSIO_MULTI_EXECUTE_TOOL) {
83 + const innerSlug = String((input as Record<string, unknown>).tool_slug ?? '');
84 + const entry = this.findLocalTool(innerSlug);
85 + if (entry) {
86 + return this.executeLocalTool(
87 + entry,
88 + (input as Record<string, unknown>).arguments as Record<string, unknown> ?? {}
89 + );
90 + }
91 + }
92 + // Default: send to backend
93 + return ToolsModel.executeMetaTool(
94 + toolSlug,
95 + { sessionId: this.sessionId, arguments: input },
96 + modifiers
97 + );
98 + };
99 +
100 + return this.config?.provider?.wrapTools(tools, routingExecuteFn) as ReturnType<
101 + TProvider['wrapTools']
102 + >;
103 + }
104 +
105 + // Standard path (no local tools)
106 const wrappedTools = ToolsModel.wrapToolsForToolRouter(this.sessionId, tools, modifiers);
107 return wrappedTools as ReturnType<TProvider['wrapTools']>;
108 }
@@ -141,20 +183,6 @@ export class ToolRouterSession<
183 /**
184 * Search for tools by semantic use case.
185 * Returns relevant tools for the given query with schemas and guidance.
144 - *
145 - * @param params - Search parameters
146 - * @param params.query - Semantic use-case query (e.g. "send emails", "create GitHub issues")
147 - * @param params.toolkits - Optional toolkit slugs to filter by
148 - * @returns Search results with matching tools and schemas
149 - *
150 - * @example
151 - * ```typescript
152 - * const session = await composio.toolRouter.use('session_123');
153 - * const results = await session.search({
154 - * query: 'send emails and notify Slack',
155 - * toolkits: ['gmail', 'slack'],
156 - * });
157 - * ```
186 */
187 async search(params: {
188 query: string;
@@ -171,30 +199,30 @@ export class ToolRouterSession<
199 /**
200 * Execute a tool within the session.
201 *
174 - * @param toolSlug - The tool slug to execute (e.g. "GMAIL_SEND_EMAIL")
175 - * @param arguments_ - Optional tool arguments. Defaults to empty object if omitted.
176 - * @returns The tool execution result
177 - *
178 - * @example
179 - * ```typescript
180 - * const session = await composio.toolRouter.use('session_123');
181 - * const result = await session.execute('GMAIL_SEND_EMAIL', {
182 - * to: 'user@example.com',
183 - * subject: 'Hello',
184 - * body: 'Hi!',
185 - * });
186 - * ```
202 + * For custom local tools, accepts both the original slug (e.g. "GET_USER_CONTEXT")
203 + * and the prefixed slug (e.g. "LOCAL_GET_USER_CONTEXT"). Local tools are executed
204 + * in-process; remote tools are sent to the Composio backend.
205 *
188 - * @example
189 - * ```typescript
190 - * // Execute with no arguments
191 - * const result = await session.execute('HACKERNEWS_GET_USER');
192 - * ```
206 + * @param toolSlug - The tool slug to execute
207 + * @param arguments_ - Optional tool arguments
208 + * @returns The tool execution result
209 */
210 async execute(
211 toolSlug: string,
212 arguments_?: Record<string, unknown>
213 ): Promise<ToolRouterSessionExecuteResponse> {
214 + // Check if this is a local tool (by original or prefixed slug)
215 + const entry = this.findLocalTool(toolSlug);
216 + if (entry) {
217 + const result = await this.executeLocalTool(entry, arguments_ ?? {});
218 + return {
219 + data: result.data,
220 + error: result.error,
221 + logId: 'local',
222 + };
223 + }
224 +
225 + // Remote execution
226 const response = await this.client.toolRouter.session.execute(this.sessionId, {
227 tool_slug: toolSlug,
228 arguments: arguments_ ?? {},
@@ -202,4 +230,63 @@ export class ToolRouterSession<
230 const transformed = transformExecuteResponse(response);
231 return ToolRouterSessionExecuteResponseSchema.parse(transformed);
232 }
233 +
234 + // ── Private helpers ──────────────────────────────────────────
235 +
236 + /** Check if this session has any local tools bound. */
237 + private hasLocalTools(): boolean {
238 + return (this.localToolsMap?.byPrefixed.size ?? 0) > 0;
239 + }
240 +
241 + /**
242 + * Find a local tool entry by slug.
243 + * Checks both the prefixed map (LOCAL_X — agent path) and original map (X — programmatic path).
244 + */
245 + private findLocalTool(slug: string): LocalToolsMapEntry | undefined {
246 + if (!this.localToolsMap) return undefined;
247 + const upper = slug.toUpperCase();
248 + return this.localToolsMap.byPrefixed.get(upper) ?? this.localToolsMap.byOriginal.get(upper);
249 + }
250 +
251 + /**
252 + * Execute a local tool in-process.
253 + * Builds a SessionContext, validates input, and calls the user's execute function.
254 + */
255 + private async executeLocalTool(
256 + entry: LocalToolsMapEntry,
257 + arguments_: Record<string, unknown>
258 + ): Promise<ToolExecuteResponse> {
259 + const { handle } = entry;
260 +
261 + // Validate input against the Zod schema
262 + // The handle was created from a Zod schema, but we stored the execute fn.
263 + // We need to re-validate at execution time. The inputParams is on the original options,
264 + // but the handle doesn't store the Zod schema — only the JSON Schema.
265 + // The execute function itself should handle its input. We trust the LLM/caller here
266 + // and let the execute function handle validation. If the user used Zod in their execute,
267 + // it will validate there.
268 +
269 + // Build session context
270 + const sessionContext = new SessionContextImpl(
271 + this.client,
272 + this.userId ?? '',
273 + this.sessionId
274 + );
275 +
276 + try {
277 + const result = await handle.execute(arguments_, sessionContext);
278 + return {
279 + data: result.data,
280 + error: result.error,
281 + successful: result.successful,
282 + };
283 + } catch (err: unknown) {
284 + const message = err instanceof Error ? err.message : String(err);
285 + return {
286 + data: {},
287 + error: message,
288 + successful: false,
289 + };
290 + }
291 + }
292 }
ts/packages/core/src/types/customTool.types.ts
+98 -1
@@ -1,8 +1,12 @@
1 import { z } from 'zod/v3';
2 -import { Tool, ToolProxyParams } from './tool.types';
2 +import { Tool, ToolProxyParams, ToolExecuteResponse as SdkToolExecuteResponse } from './tool.types';
3 import { ToolExecuteResponse } from '@composio/client/resources/tools';
4 import { ConnectionData } from './connectedAccountAuthStates.types';
5
6 +// ────────────────────────────────────────────────────────────────
7 +// Legacy custom tool types (used by composio.tools.createCustomTool)
8 +// ────────────────────────────────────────────────────────────────
9 +
10 type BaseCustomToolOptions<T extends z.ZodType> = {
11 name: string;
12 description?: string;
@@ -53,3 +57,96 @@ export interface ExecuteMetadata {
57 userId: string;
58 connectedAccountId?: string;
59 }
60 +
61 +// ────────────────────────────────────────────────────────────────
62 +// New custom tool types (for tool router integration via CustomTool())
63 +// ────────────────────────────────────────────────────────────────
64 +
65 +/**
66 + * Session context injected into custom tool execute functions at runtime.
67 + * Provides identity context and methods to call other tools or proxy API requests.
68 + */
69 +export interface SessionContext {
70 + /** The user ID for this session */
71 + readonly userId: string;
72 + /** The tool router session ID */
73 + readonly sessionId: string;
74 + /** Execute any Composio native tool from within a custom tool */
75 + execute(
76 + toolSlug: string,
77 + arguments_: Record<string, unknown>
78 + ): Promise<SdkToolExecuteResponse>;
79 + /** Proxy API calls through Composio's auth layer (resolved from session) */
80 + proxyExecute(params: ToolProxyParams): Promise<SdkToolExecuteResponse>;
81 +}
82 +
83 +/** Response shape returned by custom tool execute functions. */
84 +export type CustomToolExecuteResponse = {
85 + data: Record<string, unknown>;
86 + error: string | null;
87 + successful: boolean;
88 +};
89 +
90 +/**
91 + * Execute function for custom tools.
92 + * Supports two call patterns:
93 + * - `(input) => result` — for tools that don't need session context
94 + * - `(input, session) => result` — for tools that need to call other tools or proxy APIs
95 + */
96 +export type CustomToolExecuteFn<T extends z.ZodType> = (
97 + input: z.infer<T>,
98 + session: SessionContext
99 +) => Promise<CustomToolExecuteResponse>;
100 +
101 +/** Options for creating a custom local tool via `CustomTool()`. */
102 +export type NewCustomToolOptions<T extends z.ZodType> = {
103 + /** Unique slug identifier (e.g. 'GET_USER_CONTEXT') */
104 + slug: string;
105 + /** Human-readable name */
106 + name: string;
107 + /** Description — required for search indexing */
108 + description: string;
109 + /** Zod schema for input parameters */
110 + inputParams: T;
111 + /** Optional toolkit slug for auth-based tools (e.g. 'meta_ads') */
112 + toolkit?: string;
113 + /** The function that executes the tool */
114 + execute: CustomToolExecuteFn<T>;
115 +};
116 +
117 +/**
118 + * Handle returned from `CustomTool()`.
119 + * Pass to `composio.create(userId, { customTools: [...] })` to bind to a session.
120 + */
121 +export interface CustomToolHandle {
122 + readonly slug: string;
123 + readonly name: string;
124 + readonly description: string;
125 + readonly toolkit?: string;
126 + readonly inputSchema: Record<string, unknown>;
127 + /** Direct reference to the execute function — useful for testing */
128 + readonly execute: CustomToolExecuteFn<z.ZodType>;
129 +}
130 +
131 +/** Serialized tool definition sent to backend for BM25 search indexing. */
132 +export interface LocalToolDefinition {
133 + slug: string;
134 + name: string;
135 + description: string;
136 + input_schema: Record<string, unknown>;
137 + toolkit?: string;
138 +}
139 +
140 +/** @internal Entry in the per-session local tools routing map. */
141 +export type LocalToolsMapEntry = {
142 + handle: CustomToolHandle;
143 + prefixedSlug: string;
144 +};
145 +
146 +/** @internal Lookup maps used by ToolRouterSession for routing. */
147 +export type LocalToolsMap = {
148 + /** Lookup by prefixed slug (e.g. LOCAL_GET_USER_CONTEXT) — used for agent execution path */
149 + byPrefixed: Map<string, LocalToolsMapEntry>;
150 + /** Lookup by original slug (e.g. GET_USER_CONTEXT) — used for programmatic session.execute() */
151 + byOriginal: Map<string, LocalToolsMapEntry>;
152 +};
ts/packages/core/src/types/toolRouter.types.ts
+7
@@ -3,6 +3,7 @@ import type { BaseComposioProvider } from '../provider/BaseProvider';
3 import { SessionMetaToolOptions } from './modifiers.types';
4 import { ConnectionRequest } from './connectionRequest.types';
5 import type { ToolRouterSessionFilesMount } from '../models/ToolRouterSessionFileMount';
6 +import type { CustomToolHandle } from './customTool.types';
7
8 export const MCPServerTypeSchema = z.enum(['http', 'sse']);
9 export type MCPServerType = z.infer<typeof MCPServerTypeSchema>;
@@ -215,6 +216,12 @@ export const ToolRouterCreateSessionConfigSchema = z
216 })
217 .optional()
218 .describe('Experimental features configuration - not stable, may be modified or removed'),
219 + customTools: z
220 + .array(z.custom<CustomToolHandle>())
221 + .optional()
222 + .describe(
223 + 'Custom local tools to include in this session. Created via CustomTool() from @composio/core/experimental.'
224 + ),
225 })
226 .partial()
227 .describe('The config for the tool router session');
ts/packages/core/test/models/customTool.test.ts new
+320
@@ -0,0 +1,320 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import { z } from 'zod/v3';
3 +import { CustomTool, buildLocalToolsMap, serializeLocalTools, LOCAL_TOOL_PREFIX } from '../../src/models/CustomTool';
4 +import { SessionContextImpl } from '../../src/models/SessionContext';
5 +import type { CustomToolHandle, SessionContext } from '../../src/types/customTool.types';
6 +
7 +// ────────────────────────────────────────────────────────────────
8 +// CustomTool() factory
9 +// ────────────────────────────────────────────────────────────────
10 +
11 +describe('CustomTool', () => {
12 + const baseOptions = {
13 + slug: 'GET_USER_CONTEXT',
14 + name: 'Get user context',
15 + description: 'Retrieve what we know about a user',
16 + inputParams: z.object({
17 + category: z.string().describe('The category'),
18 + }),
19 + execute: vi.fn().mockResolvedValue({
20 + data: { result: 'ok' },
21 + error: null,
22 + successful: true,
23 + }),
24 + };
25 +
26 + it('should return a valid handle with correct fields', () => {
27 + const handle = CustomTool(baseOptions);
28 +
29 + expect(handle.slug).toBe('GET_USER_CONTEXT');
30 + expect(handle.name).toBe('Get user context');
31 + expect(handle.description).toBe('Retrieve what we know about a user');
32 + expect(handle.toolkit).toBeUndefined();
33 + expect(handle.execute).toBe(baseOptions.execute);
34 + expect(handle.inputSchema).toMatchObject({
35 + type: 'object',
36 + properties: {
37 + category: { type: 'string', description: 'The category' },
38 + },
39 + required: ['category'],
40 + });
41 + });
42 +
43 + it('should include toolkit when provided', () => {
44 + const handle = CustomTool({ ...baseOptions, toolkit: 'meta_ads' });
45 + expect(handle.toolkit).toBe('meta_ads');
46 + });
47 +
48 + it('should convert Zod schema with optional fields correctly', () => {
49 + const handle = CustomTool({
50 + ...baseOptions,
51 + inputParams: z.object({
52 + required_field: z.string(),
53 + optional_field: z.number().optional(),
54 + }),
55 + });
56 +
57 + expect(handle.inputSchema).toMatchObject({
58 + type: 'object',
59 + properties: {
60 + required_field: { type: 'string' },
61 + optional_field: { type: 'number' },
62 + },
63 + required: ['required_field'],
64 + });
65 + });
66 +
67 + it('should convert Zod schema with defaults correctly', () => {
68 + const handle = CustomTool({
69 + ...baseOptions,
70 + inputParams: z.object({
71 + category: z.string().default('all'),
72 + }),
73 + });
74 +
75 + expect(handle.inputSchema).toMatchObject({
76 + type: 'object',
77 + properties: {
78 + category: expect.objectContaining({ type: 'string' }),
79 + },
80 + });
81 + });
82 +
83 + describe('validation', () => {
84 + it('should throw if slug is missing', () => {
85 + expect(() => CustomTool({ ...baseOptions, slug: '' })).toThrow('slug is required');
86 + });
87 +
88 + it('should throw if name is missing', () => {
89 + expect(() => CustomTool({ ...baseOptions, name: '' })).toThrow('name is required');
90 + });
91 +
92 + it('should throw if description is missing', () => {
93 + expect(() => CustomTool({ ...baseOptions, description: '' })).toThrow(
94 + 'description is required'
95 + );
96 + });
97 +
98 + it('should throw if inputParams is missing', () => {
99 + expect(() => CustomTool({ ...baseOptions, inputParams: null as any })).toThrow(
100 + 'inputParams is required'
101 + );
102 + });
103 +
104 + it('should throw if execute is not a function', () => {
105 + expect(() => CustomTool({ ...baseOptions, execute: 'not-fn' as any })).toThrow(
106 + 'execute must be a function'
107 + );
108 + });
109 + });
110 +
111 + describe('execute function signatures', () => {
112 + it('should allow no-session execute (input only)', async () => {
113 + const noSessionExecute = vi.fn().mockResolvedValue({
114 + data: { result: 42 },
115 + error: null,
116 + successful: true,
117 + });
118 +
119 + const handle = CustomTool({
120 + ...baseOptions,
121 + execute: noSessionExecute,
122 + });
123 +
124 + // Call without session — JS ignores extra params
125 + const result = await handle.execute({ category: 'test' } as any);
126 + expect(result.data.result).toBe(42);
127 + expect(noSessionExecute).toHaveBeenCalledWith({ category: 'test' });
128 + });
129 +
130 + it('should allow session-based execute (input + session)', async () => {
131 + const sessionExecute = vi.fn().mockResolvedValue({
132 + data: { userId: 'u1' },
133 + error: null,
134 + successful: true,
135 + });
136 +
137 + const handle = CustomTool({
138 + ...baseOptions,
139 + execute: sessionExecute,
140 + });
141 +
142 + const mockSession: SessionContext = {
143 + userId: 'user_1',
144 + sessionId: 'sess_1',
145 + execute: vi.fn(),
146 + proxyExecute: vi.fn(),
147 + };
148 +
149 + const result = await handle.execute({ category: 'test' }, mockSession);
150 + expect(result.data.userId).toBe('u1');
151 + expect(sessionExecute).toHaveBeenCalledWith({ category: 'test' }, mockSession);
152 + });
153 + });
154 +});
155 +
156 +// ────────────────────────────────────────────────────────────────
157 +// buildLocalToolsMap()
158 +// ────────────────────────────────────────────────────────────────
159 +
160 +describe('buildLocalToolsMap', () => {
161 + const makeHandle = (slug: string): CustomToolHandle => ({
162 + slug,
163 + name: `Tool ${slug}`,
164 + description: `Description for ${slug}`,
165 + inputSchema: { type: 'object', properties: {} },
166 + execute: vi.fn(),
167 + });
168 +
169 + it('should create maps with both prefixed and original slug keys', () => {
170 + const handles = [makeHandle('MY_TOOL'), makeHandle('OTHER_TOOL')];
171 + const map = buildLocalToolsMap(handles);
172 +
173 + expect(map.byPrefixed.size).toBe(2);
174 + expect(map.byOriginal.size).toBe(2);
175 +
176 + // Prefixed lookup
177 + expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
178 + expect(map.byPrefixed.has('LOCAL_OTHER_TOOL')).toBe(true);
179 +
180 + // Original lookup
181 + expect(map.byOriginal.has('MY_TOOL')).toBe(true);
182 + expect(map.byOriginal.has('OTHER_TOOL')).toBe(true);
183 + });
184 +
185 + it('should store correct prefixedSlug on each entry', () => {
186 + const handles = [makeHandle('FOO')];
187 + const map = buildLocalToolsMap(handles);
188 +
189 + const entry = map.byPrefixed.get('LOCAL_FOO');
190 + expect(entry?.prefixedSlug).toBe('LOCAL_FOO');
191 + expect(entry?.handle.slug).toBe('FOO');
192 + });
193 +
194 + it('should handle case-insensitive slugs (uppercased internally)', () => {
195 + const handle = makeHandle('my_tool');
196 + const map = buildLocalToolsMap([handle]);
197 +
198 + expect(map.byOriginal.has('MY_TOOL')).toBe(true);
199 + expect(map.byPrefixed.has('LOCAL_MY_TOOL')).toBe(true);
200 + });
201 +
202 + it('should throw on duplicate slugs', () => {
203 + const handles = [makeHandle('DUPE'), makeHandle('DUPE')];
204 + expect(() => buildLocalToolsMap(handles)).toThrow('duplicate slug "DUPE"');
205 + });
206 +
207 + it('should return empty maps for empty input', () => {
208 + const map = buildLocalToolsMap([]);
209 + expect(map.byPrefixed.size).toBe(0);
210 + expect(map.byOriginal.size).toBe(0);
211 + });
212 +});
213 +
214 +// ────────────────────────────────────────────────────────────────
215 +// serializeLocalTools()
216 +// ────────────────────────────────────────────────────────────────
217 +
218 +describe('serializeLocalTools', () => {
219 + it('should serialize handles into backend format', () => {
220 + const handle: CustomToolHandle = {
221 + slug: 'GET_DATA',
222 + name: 'Get Data',
223 + description: 'Gets some data',
224 + toolkit: 'my_toolkit',
225 + inputSchema: { type: 'object', properties: { id: { type: 'string' } } },
226 + execute: vi.fn(),
227 + };
228 +
229 + const result = serializeLocalTools([handle]);
230 +
231 + expect(result).toEqual([
232 + {
233 + slug: 'GET_DATA',
234 + name: 'Get Data',
235 + description: 'Gets some data',
236 + toolkit: 'my_toolkit',
237 + input_schema: { type: 'object', properties: { id: { type: 'string' } } },
238 + },
239 + ]);
240 + });
241 +
242 + it('should omit toolkit when not provided', () => {
243 + const handle: CustomToolHandle = {
244 + slug: 'NO_TOOLKIT',
245 + name: 'No Toolkit',
246 + description: 'No toolkit tool',
247 + inputSchema: { type: 'object', properties: {} },
248 + execute: vi.fn(),
249 + };
250 +
251 + const result = serializeLocalTools([handle]);
252 + expect(result[0]).not.toHaveProperty('toolkit');
253 + });
254 +});
255 +
256 +// ────────────────────────────────────────────────────────────────
257 +// SessionContextImpl
258 +// ────────────────────────────────────────────────────────────────
259 +
260 +describe('SessionContextImpl', () => {
261 + const mockClient = {
262 + toolRouter: {
263 + session: {
264 + execute: vi.fn(),
265 + },
266 + },
267 + };
268 +
269 + beforeEach(() => {
270 + vi.clearAllMocks();
271 + });
272 +
273 + it('should expose userId and sessionId', () => {
274 + const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
275 + expect(ctx.userId).toBe('user_1');
276 + expect(ctx.sessionId).toBe('sess_1');
277 + });
278 +
279 + it('should delegate execute() to client.toolRouter.session.execute()', async () => {
280 + mockClient.toolRouter.session.execute.mockResolvedValue({
281 + data: { result: 'ok' },
282 + error: null,
283 + log_id: 'log_1',
284 + });
285 +
286 + const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
287 + const result = await ctx.execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' });
288 +
289 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_1', {
290 + tool_slug: 'GMAIL_SEND_EMAIL',
291 + arguments: { to: 'test@test.com' },
292 + });
293 + expect(result).toEqual({
294 + data: { result: 'ok' },
295 + error: null,
296 + successful: true,
297 + });
298 + });
299 +
300 + it('should set successful=false when execute() returns an error', async () => {
301 + mockClient.toolRouter.session.execute.mockResolvedValue({
302 + data: {},
303 + error: 'something went wrong',
304 + log_id: 'log_2',
305 + });
306 +
307 + const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
308 + const result = await ctx.execute('BAD_TOOL', {});
309 +
310 + expect(result.successful).toBe(false);
311 + expect(result.error).toBe('something went wrong');
312 + });
313 +
314 + it('should throw on proxyExecute() (not yet implemented)', async () => {
315 + const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
316 + await expect(
317 + ctx.proxyExecute({ endpoint: '/test', method: 'GET' })
318 + ).rejects.toThrow('proxyExecute is not yet implemented');
319 + });
320 +});
ts/packages/core/test/models/customToolRouting.test.ts new
+454
@@ -0,0 +1,454 @@
1 +import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import { z } from 'zod/v3';
3 +import { ToolRouter } from '../../src/models/ToolRouter';
4 +import { ToolRouterSession } from '../../src/models/ToolRouterSession';
5 +import { CustomTool, buildLocalToolsMap } from '../../src/models/CustomTool';
6 +import { MockProvider } from '../utils/mocks/provider.mock';
7 +import ComposioClient from '@composio/client';
8 +import { Tools } from '../../src/models/Tools';
9 +import type { CustomToolHandle } from '../../src/types/customTool.types';
10 +
11 +// Mock telemetry
12 +vi.mock('../../src/telemetry/Telemetry', () => ({
13 + telemetry: { instrument: vi.fn() },
14 +}));
15 +
16 +// Mock Tools class
17 +vi.mock('../../src/models/Tools', () => ({
18 + Tools: vi.fn().mockImplementation(() => ({
19 + getRawToolRouterMetaTools: vi.fn().mockResolvedValue([
20 + { slug: 'COMPOSIO_SEARCH_TOOLS', name: 'Search Tools' },
21 + { slug: 'COMPOSIO_MULTI_EXECUTE_TOOL', name: 'Multi Execute' },
22 + ]),
23 + wrapToolsForToolRouter: vi.fn().mockReturnValue('wrapped-tools'),
24 + executeMetaTool: vi.fn().mockResolvedValue({
25 + data: { remote: true },
26 + error: null,
27 + successful: true,
28 + }),
29 + })),
30 +}));
31 +
32 +// ── Fixtures ─────────────────────────────────────────────────────
33 +
34 +const createMockClient = () => ({
35 + baseURL: 'https://api.composio.dev',
36 + apiKey: 'test-api-key',
37 + toolRouter: {
38 + session: {
39 + create: vi.fn().mockResolvedValue({
40 + session_id: 'sess_123',
41 + mcp: { type: 'http', url: 'https://mcp.example.com/sess_123' },
42 + tool_router_tools: [],
43 + }),
44 + retrieve: vi.fn(),
45 + link: vi.fn(),
46 + toolkits: vi.fn(),
47 + executeMeta: vi.fn(),
48 + search: vi.fn(),
49 + execute: vi.fn().mockResolvedValue({
50 + data: { remote_result: true },
51 + error: null,
52 + log_id: 'log_remote',
53 + }),
54 + tools: vi.fn(),
55 + },
56 + },
57 + tools: {
58 + list: vi.fn(),
59 + retrieve: vi.fn(),
60 + execute: vi.fn(),
61 + proxy: vi.fn(),
62 + },
63 +});
64 +
65 +const localExecute = vi.fn().mockResolvedValue({
66 + data: { local_result: true },
67 + error: null,
68 + successful: true,
69 +});
70 +
71 +const customToolHandle = CustomTool({
72 + slug: 'GET_USER_CONTEXT',
73 + name: 'Get user context',
74 + description: 'Retrieve user preferences',
75 + inputParams: z.object({ category: z.string() }),
76 + execute: localExecute,
77 +});
78 +
79 +const sessionExecute = vi.fn().mockImplementation(async (input: any, session: any) => ({
80 + data: { userId: session.userId },
81 + error: null,
82 + successful: true,
83 +}));
84 +
85 +const sessionToolHandle = CustomTool({
86 + slug: 'GET_AD_ACCOUNTS',
87 + name: 'Get ad accounts',
88 + description: 'Get ad account IDs',
89 + toolkit: 'meta_ads',
90 + inputParams: z.object({ fields: z.string() }),
91 + execute: sessionExecute,
92 +});
93 +
94 +// ────────────────────────────────────────────────────────────────
95 +// ToolRouter.create() with customTools
96 +// ────────────────────────────────────────────────────────────────
97 +
98 +describe('ToolRouter.create() with customTools', () => {
99 + let mockClient: ReturnType<typeof createMockClient>;
100 + let router: ToolRouter<unknown, unknown, MockProvider>;
101 +
102 + beforeEach(() => {
103 + vi.clearAllMocks();
104 + mockClient = createMockClient();
105 + router = new ToolRouter(mockClient as unknown as ComposioClient, {
106 + apiKey: 'test-key',
107 + provider: new MockProvider(),
108 + });
109 + });
110 +
111 + it('should send local_tools in the create payload', async () => {
112 + await router.create('user_1', {
113 + toolkits: ['gmail'],
114 + customTools: [customToolHandle],
115 + });
116 +
117 + const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
118 + expect(payload.local_tools).toEqual([
119 + {
120 + slug: 'GET_USER_CONTEXT',
121 + name: 'Get user context',
122 + description: 'Retrieve user preferences',
123 + input_schema: customToolHandle.inputSchema,
124 + },
125 + ]);
126 + });
127 +
128 + it('should include toolkit in local_tools when present', async () => {
129 + await router.create('user_1', {
130 + customTools: [sessionToolHandle],
131 + });
132 +
133 + const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
134 + expect(payload.local_tools[0].toolkit).toBe('meta_ads');
135 + });
136 +
137 + it('should not send local_tools when customTools is omitted', async () => {
138 + await router.create('user_1', { toolkits: ['gmail'] });
139 +
140 + const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
141 + expect(payload.local_tools).toBeUndefined();
142 + });
143 +
144 + it('should not send local_tools when customTools is empty', async () => {
145 + await router.create('user_1', { customTools: [] });
146 +
147 + const payload = mockClient.toolRouter.session.create.mock.calls[0][0];
148 + expect(payload.local_tools).toBeUndefined();
149 + });
150 +
151 + it('should return a session with the correct sessionId', async () => {
152 + const session = await router.create('user_1', {
153 + customTools: [customToolHandle],
154 + });
155 +
156 + expect(session.sessionId).toBe('sess_123');
157 + });
158 +});
159 +
160 +// ────────────────────────────────────────────────────────────────
161 +// ToolRouterSession — execution routing
162 +// ────────────────────────────────────────────────────────────────
163 +
164 +describe('ToolRouterSession execution routing', () => {
165 + let mockClient: ReturnType<typeof createMockClient>;
166 +
167 + const createSession = (
168 + client: ReturnType<typeof createMockClient>,
169 + customTools: CustomToolHandle[] = []
170 + ) => {
171 + const localToolsMap = customTools.length ? buildLocalToolsMap(customTools) : undefined;
172 +
173 + return new ToolRouterSession(
174 + client as unknown as ComposioClient,
175 + { apiKey: 'key', provider: new MockProvider() },
176 + 'sess_123',
177 + { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
178 + undefined,
179 + localToolsMap,
180 + 'user_1'
181 + );
182 + };
183 +
184 + beforeEach(() => {
185 + vi.clearAllMocks();
186 + mockClient = createMockClient();
187 + localExecute.mockClear();
188 + sessionExecute.mockClear();
189 + });
190 +
191 + describe('session.execute() routing', () => {
192 + it('should route local tool by original slug to in-process execution', async () => {
193 + const session = createSession(mockClient, [customToolHandle]);
194 +
195 + const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
196 +
197 + expect(result.data).toEqual({ local_result: true });
198 + expect(result.logId).toBe('local');
199 + expect(localExecute).toHaveBeenCalledWith(
200 + { category: 'prefs' },
201 + expect.objectContaining({ userId: 'user_1', sessionId: 'sess_123' })
202 + );
203 + // Should NOT call remote
204 + expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
205 + });
206 +
207 + it('should route local tool by prefixed slug to in-process execution', async () => {
208 + const session = createSession(mockClient, [customToolHandle]);
209 +
210 + const result = await session.execute('LOCAL_GET_USER_CONTEXT', { category: 'all' });
211 +
212 + expect(result.data).toEqual({ local_result: true });
213 + expect(localExecute).toHaveBeenCalled();
214 + expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
215 + });
216 +
217 + it('should be case-insensitive for local tool lookup', async () => {
218 + const session = createSession(mockClient, [customToolHandle]);
219 +
220 + const result = await session.execute('get_user_context', { category: 'test' });
221 +
222 + expect(result.data).toEqual({ local_result: true });
223 + });
224 +
225 + it('should route non-local tool to remote execution', async () => {
226 + const session = createSession(mockClient, [customToolHandle]);
227 +
228 + await session.execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' });
229 +
230 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_123', {
231 + tool_slug: 'GMAIL_SEND_EMAIL',
232 + arguments: { to: 'test@test.com' },
233 + });
234 + expect(localExecute).not.toHaveBeenCalled();
235 + });
236 +
237 + it('should route all tools to remote when no customTools are bound', async () => {
238 + const session = createSession(mockClient);
239 +
240 + await session.execute('GET_USER_CONTEXT', { category: 'test' });
241 +
242 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalled();
243 + expect(localExecute).not.toHaveBeenCalled();
244 + });
245 + });
246 +
247 + describe('session.execute() — SessionContext injection', () => {
248 + it('should inject SessionContext with correct userId and sessionId', async () => {
249 + const session = createSession(mockClient, [sessionToolHandle]);
250 +
251 + await session.execute('GET_AD_ACCOUNTS', { fields: 'id' });
252 +
253 + expect(sessionExecute).toHaveBeenCalledWith(
254 + { fields: 'id' },
255 + expect.objectContaining({
256 + userId: 'user_1',
257 + sessionId: 'sess_123',
258 + })
259 + );
260 + });
261 +
262 + it('should provide a working execute() on SessionContext', async () => {
263 + // Tool that calls another tool via session.execute()
264 + const chainedExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
265 + const inner = await session.execute('GMAIL_SEND_EMAIL', { to: input.to });
266 + return { data: { inner_result: inner.data }, error: null, successful: true };
267 + });
268 +
269 + const chainedTool = CustomTool({
270 + slug: 'CHAINED_TOOL',
271 + name: 'Chained',
272 + description: 'Calls another tool',
273 + inputParams: z.object({ to: z.string() }),
274 + execute: chainedExecute,
275 + });
276 +
277 + const session = createSession(mockClient, [chainedTool]);
278 + await session.execute('CHAINED_TOOL', { to: 'test@test.com' });
279 +
280 + // The chained tool should have called session.execute, which calls the API
281 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_123', {
282 + tool_slug: 'GMAIL_SEND_EMAIL',
283 + arguments: { to: 'test@test.com' },
284 + });
285 + });
286 + });
287 +
288 + describe('session.execute() — error handling', () => {
289 + it('should catch errors thrown by execute function and return error response', async () => {
290 + const throwingTool = CustomTool({
291 + slug: 'THROWING_TOOL',
292 + name: 'Throwing',
293 + description: 'Throws an error',
294 + inputParams: z.object({}),
295 + execute: async () => {
296 + throw new Error('boom');
297 + },
298 + });
299 +
300 + const session = createSession(mockClient, [throwingTool]);
301 + const result = await session.execute('THROWING_TOOL', {});
302 +
303 + expect(result.error).toBe('boom');
304 + expect(result.data).toEqual({});
305 + });
306 +
307 + it('should handle non-Error throws gracefully', async () => {
308 + const throwingTool = CustomTool({
309 + slug: 'STRING_THROW',
310 + name: 'String throw',
311 + description: 'Throws a string',
312 + inputParams: z.object({}),
313 + execute: async () => {
314 + throw 'string error';
315 + },
316 + });
317 +
318 + const session = createSession(mockClient, [throwingTool]);
319 + const result = await session.execute('STRING_THROW', {});
320 +
321 + expect(result.error).toBe('string error');
322 + });
323 + });
324 +
325 + describe('session.tools() — COMPOSIO_MULTI_EXECUTE_TOOL routing', () => {
326 + it('should route local tools via COMPOSIO_MULTI_EXECUTE_TOOL to in-process execution', async () => {
327 + const provider = new MockProvider();
328 + // Mock wrapTools to capture the execute function and call it
329 + provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
330 + // Store executeFn so we can call it
331 + (provider as any)._capturedExecuteFn = executeFn;
332 + return 'wrapped-tools-with-routing';
333 + });
334 +
335 + const session = new ToolRouterSession(
336 + mockClient as unknown as ComposioClient,
337 + { apiKey: 'key', provider },
338 + 'sess_123',
339 + { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
340 + undefined,
341 + buildLocalToolsMap([customToolHandle]),
342 + 'user_1'
343 + );
344 +
345 + await session.tools();
346 +
347 + // Now simulate the LLM calling COMPOSIO_MULTI_EXECUTE_TOOL with a local tool
348 + const executeFn = (provider as any)._capturedExecuteFn;
349 + expect(executeFn).toBeDefined();
350 +
351 + const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
352 + tool_slug: 'LOCAL_GET_USER_CONTEXT',
353 + arguments: { category: 'test' },
354 + });
355 +
356 + expect(result.data).toEqual({ local_result: true });
357 + expect(localExecute).toHaveBeenCalledWith(
358 + { category: 'test' },
359 + expect.objectContaining({ userId: 'user_1', sessionId: 'sess_123' })
360 + );
361 + });
362 +
363 + it('should route remote tools via COMPOSIO_MULTI_EXECUTE_TOOL to backend', async () => {
364 + const provider = new MockProvider();
365 + provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
366 + (provider as any)._capturedExecuteFn = executeFn;
367 + return 'wrapped';
368 + });
369 +
370 + const session = new ToolRouterSession(
371 + mockClient as unknown as ComposioClient,
372 + { apiKey: 'key', provider },
373 + 'sess_123',
374 + { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
375 + undefined,
376 + buildLocalToolsMap([customToolHandle]),
377 + 'user_1'
378 + );
379 +
380 + await session.tools();
381 +
382 + const executeFn = (provider as any)._capturedExecuteFn;
383 + const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
384 + tool_slug: 'GMAIL_SEND_EMAIL',
385 + arguments: { to: 'test@test.com' },
386 + });
387 +
388 + // Should have gone to remote via executeMetaTool
389 + expect(result.data).toEqual({ remote: true });
390 + expect(localExecute).not.toHaveBeenCalled();
391 + });
392 +
393 + it('should route non-MULTI_EXECUTE meta tools to backend', async () => {
394 + const provider = new MockProvider();
395 + provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
396 + (provider as any)._capturedExecuteFn = executeFn;
397 + return 'wrapped';
398 + });
399 +
400 + const session = new ToolRouterSession(
401 + mockClient as unknown as ComposioClient,
402 + { apiKey: 'key', provider },
403 + 'sess_123',
404 + { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
405 + undefined,
406 + buildLocalToolsMap([customToolHandle]),
407 + 'user_1'
408 + );
409 +
410 + await session.tools();
411 +
412 + const executeFn = (provider as any)._capturedExecuteFn;
413 + const result = await executeFn('COMPOSIO_SEARCH_TOOLS', {
414 + queries: [{ use_case: 'send email' }],
415 + });
416 +
417 + // COMPOSIO_SEARCH_TOOLS always goes remote
418 + expect(result.data).toEqual({ remote: true });
419 + });
420 +
421 + it('should use standard wrapToolsForToolRouter when no local tools', async () => {
422 + const session = new ToolRouterSession(
423 + mockClient as unknown as ComposioClient,
424 + { apiKey: 'key', provider: new MockProvider() },
425 + 'sess_123',
426 + { type: 'http' as const, url: 'https://mcp.example.com/sess_123' }
427 + // No localToolsMap, no userId
428 + );
429 +
430 + const result = await session.tools();
431 +
432 + // Should use the standard path
433 + expect(result).toBe('wrapped-tools');
434 + });
435 + });
436 +
437 + describe('multiple custom tools', () => {
438 + it('should route each tool to its correct execute function', async () => {
439 + const session = createSession(mockClient, [customToolHandle, sessionToolHandle]);
440 +
441 + // First tool
442 + await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
443 + expect(localExecute).toHaveBeenCalled();
444 + expect(sessionExecute).not.toHaveBeenCalled();
445 +
446 + localExecute.mockClear();
447 +
448 + // Second tool
449 + await session.execute('GET_AD_ACCOUNTS', { fields: 'id' });
450 + expect(sessionExecute).toHaveBeenCalled();
451 + expect(localExecute).not.toHaveBeenCalled();
452 + });
453 + });
454 +});
ts/packages/core/tsdown.config.ts
+1
@@ -7,6 +7,7 @@ export default defineConfig({
7 copy: [{ from: 'pack/generated/*', to: '.', flatten: false }],
8 entry: [
9 'src/index.ts',
10 + 'src/experimental/index.ts',
11
12 // #platform
13 'src/platform/node.ts',