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

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

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

Synced Nov 22, 03:15 UTC

refactor(core): simplify custom tool DX and fix multi-execute routing

- Simplify execute return: users just return data or throw, SDK wraps into { data, error, successful } internally - Fix COMPOSIO_MULTI_EXECUTE_TOOL to handle tools[] array payload (was incorrectly reading singular tool_slug) - Split mixed local+remote tools in one call: local run in-process, remote forwarded to backend, results merged - Rename toolkit → connectedToolkit with comment explaining auth semantics - Add JSDoc examples: no-auth without session, no-auth with session, auth tool with connectedToolkit - Remove CustomToolExecuteResponse from public exports (internal only) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 10, 2026 at 16:15 UTC 20e8e3a16d1b118bf018d3d157e25acf742077f4
6 files changed +239 -134
ts/packages/core/src/experimental/index.ts
-1
@@ -13,6 +13,5 @@ export type {
13 CustomToolHandle,
14 NewCustomToolOptions,
15 CustomToolExecuteFn,
16 - CustomToolExecuteResponse,
16 SessionContext,
17 } from '../types/customTool.types';
ts/packages/core/src/models/CustomTool.ts
+33 -18
@@ -10,7 +10,7 @@
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 }),
13 + * execute: async (input) => ({ preferences: await db.find(input.category) }),
14 * });
15 * ```
16 */
@@ -36,48 +36,63 @@ export const LOCAL_TOOL_PREFIX = 'LOCAL_';
36 * and execute function. Pass it to `composio.create(userId, { customTools: [...] })`
37 * to bind it to a session.
38 *
39 + * Just return the result data from `execute`, or throw an error.
40 + * The SDK wraps it into the standard response format internally.
41 + *
42 * @param options - Tool definition including slug, schema, and execute function
43 * @returns A CustomToolHandle to pass to session creation
44 *
42 - * @example No-auth tool
45 + * @example No-auth tool (no session needed)
46 * ```typescript
47 * const getUserContext = CustomTool({
48 * slug: 'GET_USER_CONTEXT',
49 * name: 'Get user context',
50 * description: 'Retrieve user preferences and history',
51 * 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 - * }),
52 + * execute: async (input) => {
53 + * const prefs = await db.userContext.find(input.category);
54 + * return { preferences: prefs };
55 + * },
56 + * });
57 + * ```
58 + *
59 + * @example No-auth tool using session to call other tools
60 + * ```typescript
61 + * const enrichedSearch = CustomTool({
62 + * slug: 'ENRICHED_SEARCH',
63 + * name: 'Enriched search',
64 + * description: 'Search and enrich results with user context',
65 + * inputParams: z.object({ query: z.string() }),
66 + * execute: async (input, session) => {
67 + * const results = await session.execute('GOOGLE_SEARCH', { query: input.query });
68 + * return { enriched: results.data, userId: session.userId };
69 + * },
70 * });
71 * ```
72 *
57 - * @example Auth tool with session context
73 + * @example Auth tool with connectedToolkit (requires Composio connection)
74 * ```typescript
75 * const getAdAccounts = CustomTool({
76 * slug: 'GET_AD_ACCOUNTS',
77 * name: 'Get ad accounts',
78 * description: 'Get Meta ad account IDs for the authenticated user',
63 - * toolkit: 'meta_ads',
79 + * connectedToolkit: 'meta_ads',
80 * inputParams: z.object({ fields: z.string().default('id,name') }),
65 - * execute: async (input, session) => ({
66 - * data: await session.proxyExecute({
81 + * execute: async (input, session) => {
82 + * const result = await session.proxyExecute({
83 * endpoint: '/v21.0/me/adaccounts',
84 * method: 'GET',
85 * parameters: [{ in: 'query', name: 'fields', value: input.fields }],
70 - * }),
71 - * error: null,
72 - * successful: true,
73 - * }),
86 + * });
87 + * return result.data;
88 + * },
89 * });
90 * ```
91 */
92 export function CustomTool<T extends z.ZodType>(
93 options: NewCustomToolOptions<T>
94 ): CustomToolHandle {
80 - const { slug, name, description, inputParams, execute, toolkit } = options;
95 + const { slug, name, description, inputParams, execute, connectedToolkit } = options;
96
97 if (!slug) {
98 throw new Error('CustomTool: slug is required');
@@ -111,7 +126,7 @@ export function CustomTool<T extends z.ZodType>(
126 slug,
127 name,
128 description,
114 - toolkit,
129 + connectedToolkit,
130 inputSchema,
131 inputParams,
132 execute: execute as CustomToolExecuteFn<z.ZodType>,
@@ -162,6 +177,6 @@ export function serializeLocalTools(
177 name: handle.name,
178 description: handle.description,
179 input_schema: handle.inputSchema,
165 - ...(handle.toolkit ? { toolkit: handle.toolkit } : {}),
180 + ...(handle.connectedToolkit ? { toolkit: handle.connectedToolkit } : {}),
181 }));
182 }
ts/packages/core/src/models/ToolRouterSession.ts
+111 -14
@@ -73,21 +73,15 @@ export class ToolRouterSession<
73 );
74
75 if (this.hasLocalTools()) {
76 - // Create an execute function that routes between local and remote execution
76 + // Create an execute function that splits local/remote tools in COMPOSIO_MULTI_EXECUTE_TOOL
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
81 if (toolSlug === COMPOSIO_MULTI_EXECUTE_TOOL) {
83 - const innerSlug = String(input.tool_slug ?? '');
84 - const entry = this.findLocalTool(innerSlug);
85 - if (entry) {
86 - const innerArgs = (input.arguments as Record<string, unknown> | undefined) ?? {};
87 - return this.executeLocalTool(entry, innerArgs);
88 - }
82 + return this.routeMultiExecute(input, ToolsModel, modifiers);
83 }
90 - // Default: send to backend
84 + // Non-multi-execute meta tools always go to backend
85 return ToolsModel.executeMetaTool(
86 toolSlug,
87 { sessionId: this.sessionId, arguments: input },
@@ -246,9 +240,111 @@ export class ToolRouterSession<
240 return this.localToolsMap.byPrefixed.get(upper) ?? this.localToolsMap.byOriginal.get(upper);
241 }
242
243 + /** Parse an individual tool item from COMPOSIO_MULTI_EXECUTE_TOOL's tools array */
244 + private parseToolItem(item: unknown): { tool_slug: string; arguments: Record<string, unknown> } {
245 + const obj = item as Record<string, unknown>;
246 + return {
247 + tool_slug: String(obj.tool_slug ?? ''),
248 + arguments: (obj.arguments as Record<string, unknown> | undefined) ?? {},
249 + };
250 + }
251 +
252 + /**
253 + * Route a COMPOSIO_MULTI_EXECUTE_TOOL call.
254 + * Splits the tools[] array into local and remote, executes each appropriately,
255 + * and merges results preserving original order.
256 + */
257 + private async routeMultiExecute(
258 + input: Record<string, unknown>,
259 + ToolsModel: Tools<TToolCollection, TTool, TProvider>,
260 + modifiers?: SessionMetaToolOptions
261 + ): Promise<ToolExecuteResponse> {
262 + const toolItems = input.tools as unknown[];
263 + if (!Array.isArray(toolItems) || toolItems.length === 0) {
264 + // Fallback: send to backend as-is
265 + return ToolsModel.executeMetaTool(
266 + COMPOSIO_MULTI_EXECUTE_TOOL,
267 + { sessionId: this.sessionId, arguments: input },
268 + modifiers
269 + );
270 + }
271 +
272 + const parsed = toolItems.map(item => this.parseToolItem(item));
273 +
274 + // Partition into local and remote
275 + const localIndices: number[] = [];
276 + const remoteIndices: number[] = [];
277 + for (let i = 0; i < parsed.length; i++) {
278 + const entry = this.findLocalTool(parsed[i].tool_slug);
279 + if (entry) {
280 + localIndices.push(i);
281 + } else {
282 + remoteIndices.push(i);
283 + }
284 + }
285 +
286 + // All remote — just forward entire payload
287 + if (localIndices.length === 0) {
288 + return ToolsModel.executeMetaTool(
289 + COMPOSIO_MULTI_EXECUTE_TOOL,
290 + { sessionId: this.sessionId, arguments: input },
291 + modifiers
292 + );
293 + }
294 +
295 + // Execute local tools in parallel
296 + const results: Array<{ index: number; result: ToolExecuteResponse }> = [];
297 +
298 + const localPromises = localIndices.map(async i => {
299 + const entry = this.findLocalTool(parsed[i].tool_slug)!;
300 + const result = await this.executeLocalTool(entry, parsed[i].arguments);
301 + results.push({ index: i, result });
302 + });
303 +
304 + // Execute remote tools via backend (if any)
305 + let remotePromise: Promise<void> | undefined;
306 + if (remoteIndices.length > 0) {
307 + const remoteToolItems = remoteIndices.map(i => toolItems[i]);
308 + const remoteInput = { ...input, tools: remoteToolItems };
309 + remotePromise = ToolsModel.executeMetaTool(
310 + COMPOSIO_MULTI_EXECUTE_TOOL,
311 + { sessionId: this.sessionId, arguments: remoteInput },
312 + modifiers
313 + ).then(remoteResult => {
314 + // The backend returns a single merged response for all remote tools.
315 + // We assign it to the first remote index and mark it as the remote batch result.
316 + for (const i of remoteIndices) {
317 + results.push({ index: i, result: remoteResult });
318 + }
319 + });
320 + }
321 +
322 + await Promise.all([...localPromises, ...(remotePromise ? [remotePromise] : [])]);
323 +
324 + // If only local tools, return the single/first result
325 + if (remoteIndices.length === 0 && results.length === 1) {
326 + return results[0].result;
327 + }
328 +
329 + // Merge: collect all data keyed by tool slug
330 + const mergedData: Record<string, unknown> = {};
331 + for (const { index, result } of results) {
332 + mergedData[parsed[index].tool_slug] = result.data;
333 + }
334 + const anyError = results.find(r => r.result.error)?.result.error ?? null;
335 + return {
336 + data: mergedData,
337 + error: anyError,
338 + successful: !anyError,
339 + };
340 + }
341 +
342 /**
343 * Execute a local tool in-process.
251 - * Builds a SessionContext, validates input, and calls the user's execute function.
344 + * Builds a SessionContext, validates input, calls the user's execute function,
345 + * and wraps the result into the standard response format.
346 + *
347 + * Users just return data or throw — we wrap it here.
348 */
349 private async executeLocalTool(
350 entry: LocalToolsMapEntry,
@@ -275,11 +371,12 @@ export class ToolRouterSession<
371 );
372
373 try {
278 - const result = await handle.execute(parsed.data, sessionContext);
374 + // User's execute returns data directly — we wrap into { data, error, successful }
375 + const data = await handle.execute(parsed.data, sessionContext);
376 return {
280 - data: result.data,
281 - error: result.error,
282 - successful: result.successful,
377 + data: data ?? {},
378 + error: null,
379 + successful: true,
380 };
381 } catch (err: unknown) {
382 const message = err instanceof Error ? err.message : String(err);
ts/packages/core/src/types/customTool.types.ts
+16 -13
@@ -80,23 +80,18 @@ export interface SessionContext {
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 -
83 /**
84 * Execute function for custom tools.
85 + * Just return the result data, or throw an error. The SDK wraps it internally.
86 + *
87 * 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
88 + * - `(input) => data` — for tools that don't need session context
89 + * - `(input, session) => data` — for tools that need to call other tools or proxy APIs
90 */
91 export type CustomToolExecuteFn<T extends z.ZodType> = (
92 input: z.infer<T>,
93 session: SessionContext
99 -) => Promise<CustomToolExecuteResponse>;
94 +) => Promise<Record<string, unknown>>;
95
96 /** Options for creating a custom local tool via `CustomTool()`. */
97 export type NewCustomToolOptions<T extends z.ZodType> = {
@@ -108,8 +103,11 @@ export type NewCustomToolOptions<T extends z.ZodType> = {
103 description: string;
104 /** Zod schema for input parameters */
105 inputParams: T;
111 - /** Optional toolkit slug for auth-based tools (e.g. 'meta_ads') */
112 - toolkit?: string;
106 + /**
107 + * Composio toolkit slug requiring an active connection (e.g. 'meta_ads').
108 + * If not provided, the tool does not need Composio auth.
109 + */
110 + connectedToolkit?: string;
111 /** The function that executes the tool */
112 execute: CustomToolExecuteFn<T>;
113 };
@@ -122,7 +120,11 @@ export interface CustomToolHandle {
120 readonly slug: string;
121 readonly name: string;
122 readonly description: string;
125 - readonly toolkit?: string;
123 + /**
124 + * Composio toolkit slug requiring an active connection.
125 + * Undefined means the tool does not need Composio auth.
126 + */
127 + readonly connectedToolkit?: string;
128 readonly inputSchema: Record<string, unknown>;
129 /** @internal Original Zod schema — used for runtime input validation (defaults, coercions, transforms) */
130 readonly inputParams: z.ZodType;
@@ -136,6 +138,7 @@ export interface LocalToolDefinition {
138 name: string;
139 description: string;
140 input_schema: Record<string, unknown>;
141 + /** Maps connectedToolkit → toolkit in the backend payload */
142 toolkit?: string;
143 }
144
ts/packages/core/test/models/customTool.test.ts
+11 -23
@@ -16,11 +16,7 @@ describe('CustomTool', () => {
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 - }),
19 + execute: vi.fn().mockResolvedValue({ result: 'ok' }),
20 };
21
22 it('should return a valid handle with correct fields', () => {
@@ -29,7 +25,7 @@ describe('CustomTool', () => {
25 expect(handle.slug).toBe('GET_USER_CONTEXT');
26 expect(handle.name).toBe('Get user context');
27 expect(handle.description).toBe('Retrieve what we know about a user');
32 - expect(handle.toolkit).toBeUndefined();
28 + expect(handle.connectedToolkit).toBeUndefined();
29 expect(handle.execute).toBe(baseOptions.execute);
30 expect(handle.inputSchema).toMatchObject({
31 type: 'object',
@@ -41,9 +37,9 @@ describe('CustomTool', () => {
37 expect(handle.inputParams).toBe(baseOptions.inputParams);
38 });
39
44 - it('should include toolkit when provided', () => {
45 - const handle = CustomTool({ ...baseOptions, toolkit: 'meta_ads' });
46 - expect(handle.toolkit).toBe('meta_ads');
40 + it('should include connectedToolkit when provided', () => {
41 + const handle = CustomTool({ ...baseOptions, connectedToolkit: 'meta_ads' });
42 + expect(handle.connectedToolkit).toBe('meta_ads');
43 });
44
45 it('should convert Zod schema with optional fields correctly', () => {
@@ -111,11 +107,7 @@ describe('CustomTool', () => {
107
108 describe('execute function signatures', () => {
109 it('should allow no-session execute (input only)', async () => {
114 - const noSessionExecute = vi.fn().mockResolvedValue({
115 - data: { result: 42 },
116 - error: null,
117 - successful: true,
118 - });
110 + const noSessionExecute = vi.fn().mockResolvedValue({ result: 42 });
111
112 const handle = CustomTool({
113 ...baseOptions,
@@ -124,16 +116,12 @@ describe('CustomTool', () => {
116
117 // Call without session — JS ignores extra params
118 const result = await handle.execute({ category: 'test' } as any);
127 - expect(result.data.result).toBe(42);
119 + expect(result.result).toBe(42);
120 expect(noSessionExecute).toHaveBeenCalledWith({ category: 'test' });
121 });
122
123 it('should allow session-based execute (input + session)', async () => {
132 - const sessionExecute = vi.fn().mockResolvedValue({
133 - data: { userId: 'u1' },
134 - error: null,
135 - successful: true,
136 - });
124 + const sessionExecute = vi.fn().mockResolvedValue({ userId: 'u1' });
125
126 const handle = CustomTool({
127 ...baseOptions,
@@ -148,7 +136,7 @@ describe('CustomTool', () => {
136 };
137
138 const result = await handle.execute({ category: 'test' }, mockSession);
151 - expect(result.data.userId).toBe('u1');
139 + expect(result.userId).toBe('u1');
140 expect(sessionExecute).toHaveBeenCalledWith({ category: 'test' }, mockSession);
141 });
142 });
@@ -223,7 +211,7 @@ describe('serializeLocalTools', () => {
211 slug: 'GET_DATA',
212 name: 'Get Data',
213 description: 'Gets some data',
226 - toolkit: 'my_toolkit',
214 + connectedToolkit: 'my_toolkit',
215 inputSchema: { type: 'object', properties: { id: { type: 'string' } } },
216 inputParams: z.object({ id: z.string() }),
217 execute: vi.fn(),
@@ -242,7 +230,7 @@ describe('serializeLocalTools', () => {
230 ]);
231 });
232
245 - it('should omit toolkit when not provided', () => {
233 + it('should omit toolkit when connectedToolkit not provided', () => {
234 const handle: CustomToolHandle = {
235 slug: 'NO_TOOLKIT',
236 name: 'No Toolkit',
ts/packages/core/test/models/customToolRouting.test.ts
+68 -65
@@ -62,11 +62,8 @@ const createMockClient = () => ({
62 },
63 });
64
65 -const localExecute = vi.fn().mockResolvedValue({
66 - data: { local_result: true },
67 - error: null,
68 - successful: true,
69 -});
65 +// Execute returns data directly (simplified API)
66 +const localExecute = vi.fn().mockResolvedValue({ local_result: true });
67
68 const customToolHandle = CustomTool({
69 slug: 'GET_USER_CONTEXT',
@@ -77,16 +74,14 @@ const customToolHandle = CustomTool({
74 });
75
76 const sessionExecute = vi.fn().mockImplementation(async (input: any, session: any) => ({
80 - data: { userId: session.userId },
81 - error: null,
82 - successful: true,
77 + userId: session.userId,
78 }));
79
80 const sessionToolHandle = CustomTool({
81 slug: 'GET_AD_ACCOUNTS',
82 name: 'Get ad accounts',
83 description: 'Get ad account IDs',
89 - toolkit: 'meta_ads',
84 + connectedToolkit: 'meta_ads',
85 inputParams: z.object({ fields: z.string() }),
86 execute: sessionExecute,
87 });
@@ -125,7 +120,7 @@ describe('ToolRouter.create() with customTools', () => {
120 ]);
121 });
122
128 - it('should include toolkit in local_tools when present', async () => {
123 + it('should include toolkit in local_tools when connectedToolkit is present', async () => {
124 await router.create('user_1', {
125 customTools: [sessionToolHandle],
126 });
@@ -194,6 +189,7 @@ describe('ToolRouterSession execution routing', () => {
189
190 const result = await session.execute('GET_USER_CONTEXT', { category: 'prefs' });
191
192 + // User returns data directly, SDK wraps it
193 expect(result.data).toEqual({ local_result: true });
194 expect(result.logId).toBe('local');
195 expect(localExecute).toHaveBeenCalledWith(
@@ -263,7 +259,7 @@ describe('ToolRouterSession execution routing', () => {
259 // Tool that calls another tool via session.execute()
260 const chainedExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
261 const inner = await session.execute('GMAIL_SEND_EMAIL', { to: input.to });
266 - return { data: { inner_result: inner.data }, error: null, successful: true };
262 + return { inner_result: inner.data };
263 });
264
265 const chainedTool = CustomTool({
@@ -306,9 +302,7 @@ describe('ToolRouterSession execution routing', () => {
302
303 it('should apply Zod defaults when input is missing optional fields', async () => {
304 const defaultExecute = vi.fn().mockImplementation(async (input: any) => ({
309 - data: { category: input.category },
310 - error: null,
311 - successful: true,
305 + category: input.category,
306 }));
307
308 const toolWithDefaults = CustomTool({
@@ -364,35 +358,43 @@ describe('ToolRouterSession execution routing', () => {
358 });
359 });
360
367 - describe('session.tools() — COMPOSIO_MULTI_EXECUTE_TOOL routing', () => {
368 - it('should route local tools via COMPOSIO_MULTI_EXECUTE_TOOL to in-process execution', async () => {
369 - const provider = new MockProvider();
370 - // Mock wrapTools to capture the execute function and call it
371 - provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
372 - // Store executeFn so we can call it
373 - (provider as any)._capturedExecuteFn = executeFn;
374 - return 'wrapped-tools-with-routing';
375 - });
376 -
377 - const session = new ToolRouterSession(
378 - mockClient as unknown as ComposioClient,
361 + describe('session.tools() — COMPOSIO_MULTI_EXECUTE_TOOL routing with tools[] array', () => {
362 + const createSessionWithProvider = (
363 + client: ReturnType<typeof createMockClient>,
364 + provider: MockProvider,
365 + customTools: CustomToolHandle[]
366 + ) => {
367 + return new ToolRouterSession(
368 + client as unknown as ComposioClient,
369 { apiKey: 'key', provider },
370 'sess_123',
371 { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
372 undefined,
383 - buildLocalToolsMap([customToolHandle]),
373 + buildLocalToolsMap(customTools),
374 'user_1'
375 );
376 + };
377
387 - await session.tools();
378 + const captureExecuteFn = (provider: MockProvider) => {
379 + provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
380 + (provider as any)._capturedExecuteFn = executeFn;
381 + return 'wrapped-tools-with-routing';
382 + });
383 + };
384
389 - // Now simulate the LLM calling COMPOSIO_MULTI_EXECUTE_TOOL with a local tool
385 + it('should route all-local tools[] to in-process execution', async () => {
386 + const provider = new MockProvider();
387 + captureExecuteFn(provider);
388 + const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
389 +
390 + await session.tools();
391 const executeFn = (provider as any)._capturedExecuteFn;
391 - expect(executeFn).toBeDefined();
392
393 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
394 - tool_slug: 'LOCAL_GET_USER_CONTEXT',
395 - arguments: { category: 'test' },
394 + tools: [
395 + { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'test' } },
396 + ],
397 + sync_response_to_workbench: false,
398 });
399
400 expect(result.data).toEqual({ local_result: true });
@@ -402,56 +404,57 @@ describe('ToolRouterSession execution routing', () => {
404 );
405 });
406
405 - it('should route remote tools via COMPOSIO_MULTI_EXECUTE_TOOL to backend', async () => {
407 + it('should route all-remote tools[] to backend', async () => {
408 const provider = new MockProvider();
407 - provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
408 - (provider as any)._capturedExecuteFn = executeFn;
409 - return 'wrapped';
410 - });
411 -
412 - const session = new ToolRouterSession(
413 - mockClient as unknown as ComposioClient,
414 - { apiKey: 'key', provider },
415 - 'sess_123',
416 - { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
417 - undefined,
418 - buildLocalToolsMap([customToolHandle]),
419 - 'user_1'
420 - );
409 + captureExecuteFn(provider);
410 + const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
411
412 await session.tools();
423 -
413 const executeFn = (provider as any)._capturedExecuteFn;
414 +
415 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
426 - tool_slug: 'GMAIL_SEND_EMAIL',
427 - arguments: { to: 'test@test.com' },
416 + tools: [
417 + { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'test@test.com' } },
418 + ],
419 + sync_response_to_workbench: false,
420 });
421
430 - // Should have gone to remote via executeMetaTool
422 + // All remote — goes to executeMetaTool
423 expect(result.data).toEqual({ remote: true });
424 expect(localExecute).not.toHaveBeenCalled();
425 });
426
435 - it('should route non-MULTI_EXECUTE meta tools to backend', async () => {
427 + it('should split mixed local+remote tools and merge results', async () => {
428 const provider = new MockProvider();
437 - provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
438 - (provider as any)._capturedExecuteFn = executeFn;
439 - return 'wrapped';
429 + captureExecuteFn(provider);
430 + const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
431 +
432 + await session.tools();
433 + const executeFn = (provider as any)._capturedExecuteFn;
434 +
435 + const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
436 + tools: [
437 + { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'prefs' } },
438 + { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'test@test.com' } },
439 + ],
440 + sync_response_to_workbench: false,
441 });
442
442 - const session = new ToolRouterSession(
443 - mockClient as unknown as ComposioClient,
444 - { apiKey: 'key', provider },
445 - 'sess_123',
446 - { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
447 - undefined,
448 - buildLocalToolsMap([customToolHandle]),
449 - 'user_1'
450 - );
443 + // Both should have been called
444 + expect(localExecute).toHaveBeenCalled();
445 + // Remote goes to backend — merged results keyed by slug
446 + expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
447 + expect(result.data).toHaveProperty('GMAIL_SEND_EMAIL');
448 + });
449
452 - await session.tools();
450 + it('should route non-MULTI_EXECUTE meta tools to backend', async () => {
451 + const provider = new MockProvider();
452 + captureExecuteFn(provider);
453 + const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
454
455 + await session.tools();
456 const executeFn = (provider as any)._capturedExecuteFn;
457 +
458 const result = await executeFn('COMPOSIO_SEARCH_TOOLS', {
459 queries: [{ use_case: 'send email' }],
460 });