@devries-cameron20 / composio Mirror · read-only / commits / 19f4a3a30
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

fix: sibling local tool routing, extract execution helpers, fix merge logic

- SessionContextImpl now routes to sibling local tools in-process before falling back to the backend API (fixes session.execute() from within a custom tool calling another local tool) - Extract findLocalTool() and executeLocalTool() into standalone localToolExecution.ts, shared by ToolRouterSession and SessionContextImpl - Fix routeMultiExecute merge: append local results to backend's results[] array instead of flat keyed merge. Errors from both local and remote tools are now preserved (no silent dropping). - Update localTools() docstring with MCP usage example Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 10, 2026 at 21:18 UTC 19f4a3a305b392ac632774df4b8f316a33d83871
5 files changed +354 -155
ts/packages/core/src/models/SessionContext.ts
+26 -4
@@ -5,9 +5,22 @@ 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 + * Callback that attempts local tool execution.
10 + * Returns a Promise if the slug matches a local tool, or undefined to fall back to remote.
11 + */
12 +export type TryLocalExecuteFn = (
13 + slug: string,
14 + args: Record<string, unknown>
15 +) => Promise<ToolExecuteResponse> | undefined;
16 +
17 /**
18 * Concrete implementation of SessionContext.
10 - * Built per local tool invocation inside ToolRouterSession.executeLocalTool().
19 + * Built per local tool invocation inside ToolRouterSession.
20 + *
21 + * When `tryLocalExecute` is provided, `execute()` checks sibling local tools first
22 + * before falling back to the backend API. This allows local tool A to call local
23 + * tool B via `session.execute('B', ...)` without hitting the network.
24 */
25 export class SessionContextImpl implements SessionContext {
26 public readonly userId: string;
@@ -15,19 +28,28 @@ export class SessionContextImpl implements SessionContext {
28 constructor(
29 private readonly client: ComposioClient,
30 userId: string,
18 - private readonly sessionId: string
31 + private readonly sessionId: string,
32 + private readonly tryLocalExecute?: TryLocalExecuteFn
33 ) {
34 this.userId = userId;
35 }
36
37 /**
24 - * Execute any Composio native tool from within a custom tool.
25 - * Delegates to the tool router session execute endpoint.
38 + * Execute any tool from within a custom tool.
39 + * Routes to sibling local tools in-process when available,
40 + * otherwise delegates to the backend API.
41 */
42 async execute(
43 toolSlug: string,
44 arguments_: Record<string, unknown>
45 ): Promise<ToolExecuteResponse> {
46 + // Try local tool first (sibling routing)
47 + const localResult = this.tryLocalExecute?.(toolSlug, arguments_);
48 + if (localResult) {
49 + return localResult;
50 + }
51 +
52 + // Fall back to remote execution
53 const response = await this.client.toolRouter.session.execute(
54 this.sessionId,
55 {
ts/packages/core/src/models/ToolRouterSession.ts
+58 -83
@@ -25,9 +25,10 @@ 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';
28 +import type { LocalToolsMap, LocalToolsMapEntry, SessionContext } from '../types/customTool.types';
29 import type { Tool, ToolExecuteResponse } from '../types/tool.types';
30 import { SessionContextImpl } from './SessionContext';
31 +import { findLocalTool, executeLocalTool } from './localToolExecution';
32
33 const COMPOSIO_MULTI_EXECUTE_TOOL = 'COMPOSIO_MULTI_EXECUTE_TOOL';
34 const COMPOSIO_EXECUTE_LOCAL_TOOL = 'COMPOSIO_EXECUTE_LOCAL_TOOL';
@@ -88,7 +89,7 @@ export class ToolRouterSession<
89 if (toolSlug === COMPOSIO_EXECUTE_LOCAL_TOOL) {
90 const slug = String(input.tool_slug ?? '');
91 const args = (input.arguments as Record<string, unknown> | undefined) ?? {};
91 - const entry = this.findLocalTool(slug);
92 + const entry = findLocalTool(this.localToolsMap, slug);
93 if (!entry) {
94 return {
95 data: {},
@@ -96,7 +97,7 @@ export class ToolRouterSession<
97 successful: false,
98 };
99 }
99 - return this.executeLocalTool(entry, args);
100 + return executeLocalTool(entry, args, this.buildSessionContext());
101 }
102 // Non-multi-execute meta tools always go to backend
103 return ToolsModel.executeMetaTool(
@@ -123,16 +124,22 @@ export class ToolRouterSession<
124 }
125
126 /**
126 - * Get a tool for executing local custom tools individually.
127 - * Use this for MCP flows or when you need explicit control over local tool execution.
127 + * Returns a dispatcher tool that exposes local custom tools for execution.
128 + * Primarily used in MCP flows where remote tools are served via an MCP server
129 + * and local tools need to be added alongside.
130 *
131 * Not included in `session.tools()` — must be explicitly added to the agent's tool set.
132 *
133 * @example
134 * ```typescript
133 - * const tools = await session.tools();
135 + * // MCP flow: remote tools via MCP server, local tools via localTools()
136 * const localTool = await session.localTools();
135 - * const agent = new Agent({ tools: [...tools, ...localTool] });
137 + * const agent = new Agent({
138 + * tools: [
139 + * hostedMcpTool(session.mcp.url), // remote tools from MCP
140 + * ...localTool, // local custom tools
141 + * ],
142 + * });
143 * ```
144 */
145 async localTools(): Promise<ReturnType<TProvider['wrapTools']>> {
@@ -183,7 +190,7 @@ export class ToolRouterSession<
190 const slug = String(input.tool_slug ?? '');
191 const args = (input.arguments as Record<string, unknown> | undefined) ?? {};
192
186 - const entry = this.findLocalTool(slug);
193 + const entry = findLocalTool(this.localToolsMap, slug);
194 if (!entry) {
195 return {
196 data: {},
@@ -192,7 +199,7 @@ export class ToolRouterSession<
199 };
200 }
201
195 - return this.executeLocalTool(entry, args);
202 + return executeLocalTool(entry, args, this.buildSessionContext());
203 };
204
205 return this.config.provider.wrapTools([tool], executeFn) as ReturnType<
@@ -305,9 +312,9 @@ export class ToolRouterSession<
312 arguments_?: Record<string, unknown>
313 ): Promise<ToolRouterSessionExecuteResponse> {
314 // Check if this is a local tool (by original or prefixed slug)
308 - const entry = this.findLocalTool(toolSlug);
315 + const entry = findLocalTool(this.localToolsMap, toolSlug);
316 if (entry) {
310 - const result = await this.executeLocalTool(entry, arguments_ ?? {});
317 + const result = await executeLocalTool(entry, arguments_ ?? {}, this.buildSessionContext());
318 return {
319 data: result.data,
320 error: result.error,
@@ -332,13 +339,21 @@ export class ToolRouterSession<
339 }
340
341 /**
335 - * Find a local tool entry by slug.
336 - * Checks both the prefixed map (LOCAL_X — agent path) and original map (X — programmatic path).
342 + * Build a SessionContext for local tool execution.
343 + * Includes sibling routing: session.execute() inside a custom tool checks
344 + * local tools first before falling back to the backend API.
345 */
338 - private findLocalTool(slug: string): LocalToolsMapEntry | undefined {
339 - if (!this.localToolsMap) return undefined;
340 - const upper = slug.toUpperCase();
341 - return this.localToolsMap.byPrefixed.get(upper) ?? this.localToolsMap.byOriginal.get(upper);
346 + private buildSessionContext(): SessionContext {
347 + return new SessionContextImpl(
348 + this.client,
349 + this.userId!,
350 + this.sessionId,
351 + (slug, args) => {
352 + const entry = findLocalTool(this.localToolsMap, slug);
353 + if (!entry) return undefined;
354 + return executeLocalTool(entry, args, this.buildSessionContext());
355 + }
356 + );
357 }
358
359 /** Parse an individual tool item from COMPOSIO_MULTI_EXECUTE_TOOL's tools array */
@@ -379,7 +394,7 @@ export class ToolRouterSession<
394 const localItems: Array<{ index: number; entry: LocalToolsMapEntry }> = [];
395 const remoteIndices: number[] = [];
396 for (let i = 0; i < parsed.length; i++) {
382 - const entry = this.findLocalTool(parsed[i].tool_slug);
397 + const entry = findLocalTool(this.localToolsMap, parsed[i].tool_slug);
398 if (entry) {
399 localItems.push({ index: i, entry });
400 } else {
@@ -398,7 +413,7 @@ export class ToolRouterSession<
413
414 // Execute local tools in parallel
415 const localPromises = localItems.map(async ({ index, entry }) => {
401 - const result = await this.executeLocalTool(entry, parsed[index].arguments);
416 + const result = await executeLocalTool(entry, parsed[index].arguments, this.buildSessionContext());
417 return { index, result };
418 });
419
@@ -419,79 +434,39 @@ export class ToolRouterSession<
434 remotePromise,
435 ]);
436
422 - // If only local tools, return the single/first result
437 + // If only local tools, return the single/first result unwrapped
438 if (remoteIndices.length === 0 && localResults.length === 1) {
439 return localResults[0].result;
440 }
441
427 - // Merge: remote results first (remote may write to session files), then local
428 - const mergedData: Record<string, unknown> = {};
442 + // Merge results into the backend's results[] format.
443 + // Backend returns: { results: [{ response, tool_slug, index }], total_count, ... }
444 + // We append local tool results in the same shape.
445 + const remoteData = (remoteResult?.data ?? {}) as Record<string, unknown>;
446 + const remoteResults = (Array.isArray(remoteData.results) ? remoteData.results : []) as unknown[];
447
430 - // Remote batch data first (backend returns data keyed by tool slug)
431 - if (remoteResult?.data && typeof remoteResult.data === 'object') {
432 - Object.assign(mergedData, remoteResult.data);
433 - }
448 + // Build local result entries matching backend format
449 + const localEntries = localResults.map(({ index, result }) => ({
450 + response: {
451 + successful: result.successful,
452 + data: result.data,
453 + ...(result.error ? { error: result.error } : {}),
454 + },
455 + tool_slug: parsed[index].tool_slug,
456 + index,
457 + ...(result.error ? { error: result.error } : {}),
458 + }));
459
435 - // Local results last
436 - for (const { index, result } of localResults) {
437 - mergedData[parsed[index].tool_slug] = result.data;
438 - }
460 + const allResults = [...remoteResults, ...localEntries];
461 + const hasAnyError = localResults.some(r => r.result.error) || !!remoteResult?.error;
462
440 - const anyLocalError = localResults.find(r => r.result.error)?.result.error;
441 - const anyError = anyLocalError ?? remoteResult?.error ?? null;
463 return {
443 - data: mergedData,
444 - error: anyError,
445 - successful: !anyError,
464 + data: { ...remoteData, results: allResults },
465 + error: hasAnyError
466 + ? `${allResults.filter((r: any) => r.error).length} out of ${allResults.length} tools failed`
467 + : null,
468 + successful: !hasAnyError,
469 };
470 }
471
449 - /**
450 - * Execute a local tool in-process.
451 - * Builds a SessionContext, validates input, calls the user's execute function,
452 - * and wraps the result into the standard response format.
453 - *
454 - * Users just return data or throw — we wrap it here.
455 - */
456 - private async executeLocalTool(
457 - entry: LocalToolsMapEntry,
458 - arguments_: Record<string, unknown>
459 - ): Promise<ToolExecuteResponse> {
460 - const { handle } = entry;
461 -
462 - // Validate and transform input using the original Zod schema.
463 - // This applies defaults, coercions, and transforms (e.g. z.string().default('all')).
464 - const parsed = handle.inputParams.safeParse(arguments_);
465 - if (!parsed.success) {
466 - return {
467 - data: {},
468 - error: `Input validation failed: ${parsed.error.message}`,
469 - successful: false,
470 - };
471 - }
472 -
473 - // Build session context
474 - const sessionContext = new SessionContextImpl(
475 - this.client,
476 - this.userId!,
477 - this.sessionId
478 - );
479 -
480 - try {
481 - // User's execute returns data directly — we wrap into { data, error, successful }
482 - const data = await handle.execute(parsed.data, sessionContext);
483 - return {
484 - data: data ?? {},
485 - error: null,
486 - successful: true,
487 - };
488 - } catch (err: unknown) {
489 - const message = err instanceof Error ? err.message : String(err);
490 - return {
491 - data: {},
492 - error: message,
493 - successful: false,
494 - };
495 - }
496 - }
472 }
ts/packages/core/src/models/localToolExecution.ts new
+62
@@ -0,0 +1,62 @@
1 +/**
2 + * @fileoverview Standalone functions for local tool lookup and execution.
3 + * Extracted from ToolRouterSession for reuse in SessionContextImpl (sibling routing).
4 + */
5 +import type { LocalToolsMap, LocalToolsMapEntry, SessionContext } from '../types/customTool.types';
6 +import type { ToolExecuteResponse } from '../types/tool.types';
7 +
8 +/**
9 + * Find a local tool entry by slug.
10 + * Checks both the prefixed map (LOCAL_X — agent path) and original map (X — programmatic path).
11 + */
12 +export function findLocalTool(
13 + map: LocalToolsMap | undefined,
14 + slug: string
15 +): LocalToolsMapEntry | undefined {
16 + if (!map) return undefined;
17 + const upper = slug.toUpperCase();
18 + return map.byPrefixed.get(upper) ?? map.byOriginal.get(upper);
19 +}
20 +
21 +/**
22 + * Execute a local tool in-process.
23 + * Validates input via the Zod schema, calls the user's execute function,
24 + * and wraps the result into the standard response format.
25 + *
26 + * Callers provide a pre-built SessionContext (which may include sibling local routing).
27 + */
28 +export async function executeLocalTool(
29 + entry: LocalToolsMapEntry,
30 + arguments_: Record<string, unknown>,
31 + sessionContext: SessionContext
32 +): Promise<ToolExecuteResponse> {
33 + const { handle } = entry;
34 +
35 + // Validate and transform input using the original Zod schema.
36 + // This applies defaults, coercions, and transforms (e.g. z.string().default('all')).
37 + const parsed = handle.inputParams.safeParse(arguments_);
38 + if (!parsed.success) {
39 + return {
40 + data: {},
41 + error: `Input validation failed: ${parsed.error.message}`,
42 + successful: false,
43 + };
44 + }
45 +
46 + try {
47 + // User's execute returns data directly — we wrap into { data, error, successful }
48 + const data = await handle.execute(parsed.data, sessionContext);
49 + return {
50 + data: data ?? {},
51 + error: null,
52 + successful: true,
53 + };
54 + } catch (err: unknown) {
55 + const message = err instanceof Error ? err.message : String(err);
56 + return {
57 + data: {},
58 + error: message,
59 + successful: false,
60 + };
61 + }
62 +}
ts/packages/core/test/models/customTool.test.ts
+49
@@ -305,4 +305,53 @@ describe('SessionContextImpl', () => {
305 ctx.proxyExecute({ endpoint: '/test', method: 'GET' })
306 ).rejects.toThrow('proxyExecute is not yet implemented');
307 });
308 +
309 + describe('sibling local tool routing', () => {
310 + it('should route to local tool when tryLocalExecute matches', async () => {
311 + const tryLocalExecute = vi.fn().mockReturnValue(
312 + Promise.resolve({ data: { local: true }, error: null, successful: true })
313 + );
314 +
315 + const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', tryLocalExecute);
316 + const result = await ctx.execute('SIBLING_TOOL', { key: 'val' });
317 +
318 + expect(tryLocalExecute).toHaveBeenCalledWith('SIBLING_TOOL', { key: 'val' });
319 + expect(result).toEqual({ data: { local: true }, error: null, successful: true });
320 + // Should NOT call remote
321 + expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
322 + });
323 +
324 + it('should fall back to remote when tryLocalExecute returns undefined', async () => {
325 + const tryLocalExecute = vi.fn().mockReturnValue(undefined);
326 + mockClient.toolRouter.session.execute.mockResolvedValue({
327 + data: { remote: true },
328 + error: null,
329 + log_id: 'log_3',
330 + });
331 +
332 + const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', tryLocalExecute);
333 + const result = await ctx.execute('REMOTE_TOOL', { key: 'val' });
334 +
335 + expect(tryLocalExecute).toHaveBeenCalledWith('REMOTE_TOOL', { key: 'val' });
336 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_1', {
337 + tool_slug: 'REMOTE_TOOL',
338 + arguments: { key: 'val' },
339 + });
340 + expect(result).toEqual({ data: { remote: true }, error: null, successful: true });
341 + });
342 +
343 + it('should delegate to remote when no tryLocalExecute is provided', async () => {
344 + mockClient.toolRouter.session.execute.mockResolvedValue({
345 + data: { remote: true },
346 + error: null,
347 + log_id: 'log_4',
348 + });
349 +
350 + const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
351 + const result = await ctx.execute('ANY_TOOL', {});
352 +
353 + expect(mockClient.toolRouter.session.execute).toHaveBeenCalled();
354 + expect(result.successful).toBe(true);
355 + });
356 + });
357 });
ts/packages/core/test/models/customToolRouting.test.ts
+159 -68
@@ -275,8 +275,8 @@ describe('ToolRouterSession execution routing', () => {
275 );
276 });
277
278 - it('should provide a working execute() on SessionContext', async () => {
279 - // Tool that calls another tool via session.execute()
278 + it('should provide a working execute() on SessionContext for remote tools', async () => {
279 + // Tool that calls a remote tool via session.execute()
280 const chainedExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
281 const inner = await session.execute('GMAIL_SEND_EMAIL', { to: input.to });
282 return { inner_result: inner.data };
@@ -299,6 +299,47 @@ describe('ToolRouterSession execution routing', () => {
299 arguments: { to: 'test@test.com' },
300 });
301 });
302 +
303 + it('should route sibling local tools in-process without hitting the API', async () => {
304 + // Tool B — a sibling local tool
305 + const siblingExecute = vi.fn().mockResolvedValue({ siblingData: 'from-B' });
306 + const toolB = createCustomTool({
307 + slug: 'TOOL_B',
308 + name: 'Tool B',
309 + description: 'Sibling tool',
310 + inputParams: z.object({ key: z.string() }),
311 + execute: siblingExecute,
312 + });
313 +
314 + // Tool A — calls Tool B via session.execute()
315 + const toolAExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
316 + const inner = await session.execute('TOOL_B', { key: input.value });
317 + return { fromA: true, fromB: inner.data };
318 + });
319 + const toolA = createCustomTool({
320 + slug: 'TOOL_A',
321 + name: 'Tool A',
322 + description: 'Calls sibling tool B',
323 + inputParams: z.object({ value: z.string() }),
324 + execute: toolAExecute,
325 + });
326 +
327 + const session = createSession(mockClient, [toolA, toolB]);
328 + const result = await session.execute('TOOL_A', { value: 'hello' });
329 +
330 + // Tool B should have been called in-process
331 + expect(siblingExecute).toHaveBeenCalledWith(
332 + { key: 'hello' },
333 + expect.objectContaining({ userId: 'user_1' })
334 + );
335 + // Result should contain data from both tools
336 + expect(result.data).toEqual({
337 + fromA: true,
338 + fromB: { siblingData: 'from-B' },
339 + });
340 + // Should NOT have called the remote API for Tool B
341 + expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
342 + });
343 });
344
345 describe('session.execute() — error handling', () => {
@@ -492,14 +533,43 @@ describe('ToolRouterSession execution routing', () => {
533 return { executeFn, toolsInstance, provider, session };
534 };
535
495 - it('should merge results with remote keys first, local keys last', async () => {
536 + /** Build a backend-shaped results[] response */
537 + const backendResponse = (
538 + results: Array<{ tool_slug: string; data: any; error?: string }>,
539 + ) => {
540 + const items = results.map((r, i) => ({
541 + response: {
542 + successful: !r.error,
543 + data: r.data,
544 + ...(r.error ? { error: r.error } : {}),
545 + },
546 + tool_slug: r.tool_slug,
547 + index: i,
548 + ...(r.error ? { error: r.error } : {}),
549 + }));
550 + const errorCount = results.filter(r => r.error).length;
551 + return {
552 + data: {
553 + results: items,
554 + total_count: results.length,
555 + success_count: results.length - errorCount,
556 + error_count: errorCount,
557 + },
558 + error: errorCount > 0 ? `${errorCount} out of ${results.length} tools failed` : null,
559 + successful: errorCount === 0,
560 + };
561 + };
562 +
563 + /** Find a local tool result in the results[] array by slug */
564 + const findResult = (results: any[], slug: string) =>
565 + results.find((r: any) => r.tool_slug === slug);
566 +
567 + it('should append local results to remote results array', async () => {
568 const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
569
498 - toolsInstance.executeMetaTool.mockResolvedValueOnce({
499 - data: { GMAIL_SEND_EMAIL: { sent: true } },
500 - error: null,
501 - successful: true,
502 - });
570 + toolsInstance.executeMetaTool.mockResolvedValueOnce(
571 + backendResponse([{ tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } }])
572 + );
573
574 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
575 tools: [
@@ -509,11 +579,16 @@ describe('ToolRouterSession execution routing', () => {
579 sync_response_to_workbench: false,
580 });
581
512 - // Verify ordering: remote keys come before local keys
513 - const keys = Object.keys(result.data);
514 - const remoteIdx = keys.indexOf('GMAIL_SEND_EMAIL');
515 - const localIdx = keys.indexOf('LOCAL_GET_USER_CONTEXT');
516 - expect(remoteIdx).toBeLessThan(localIdx);
582 + // Results is an array with both remote and local entries
583 + const { results } = result.data;
584 + expect(results).toHaveLength(2);
585 +
586 + // Remote result comes first (from backend), local appended after
587 + const remote = findResult(results, 'GMAIL_SEND_EMAIL');
588 + const local = findResult(results, 'LOCAL_GET_USER_CONTEXT');
589 + expect(remote.response.data).toEqual({ sent: true });
590 + expect(local.response.data).toEqual({ local_result: true });
591 + expect(local.response.successful).toBe(true);
592 });
593
594 it('should handle multiple local tools in same batch', async () => {
@@ -535,8 +610,11 @@ describe('ToolRouterSession execution routing', () => {
610 { fields: 'id,name' },
611 expect.objectContaining({ userId: 'user_1' })
612 );
538 - expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
539 - expect(result.data).toHaveProperty('LOCAL_GET_AD_ACCOUNTS');
613 +
614 + const { results } = result.data;
615 + expect(results).toHaveLength(2);
616 + expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();
617 + expect(findResult(results, 'LOCAL_GET_AD_ACCOUNTS')).toBeDefined();
618 });
619
620 it('should handle mixed batch with multiple locals + multiple remotes', async () => {
@@ -545,14 +623,12 @@ describe('ToolRouterSession execution routing', () => {
623 [customToolHandle, sessionToolHandle]
624 );
625
548 - toolsInstance.executeMetaTool.mockResolvedValueOnce({
549 - data: {
550 - GMAIL_SEND_EMAIL: { sent: true },
551 - SLACK_POST_MESSAGE: { ts: '999' },
552 - },
553 - error: null,
554 - successful: true,
555 - });
626 + toolsInstance.executeMetaTool.mockResolvedValueOnce(
627 + backendResponse([
628 + { tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } },
629 + { tool_slug: 'SLACK_POST_MESSAGE', data: { ts: '999' } },
630 + ])
631 + );
632
633 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
634 tools: [
@@ -564,12 +640,13 @@ describe('ToolRouterSession execution routing', () => {
640 sync_response_to_workbench: false,
641 });
642
567 - // All 4 tools should appear in result
568 - expect(Object.keys(result.data)).toHaveLength(4);
569 - expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
570 - expect(result.data).toHaveProperty('LOCAL_GET_AD_ACCOUNTS');
571 - expect(result.data).toHaveProperty('GMAIL_SEND_EMAIL');
572 - expect(result.data).toHaveProperty('SLACK_POST_MESSAGE');
643 + // All 4 tools should appear in results array
644 + const { results } = result.data;
645 + expect(results).toHaveLength(4);
646 + expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();
647 + expect(findResult(results, 'LOCAL_GET_AD_ACCOUNTS')).toBeDefined();
648 + expect(findResult(results, 'GMAIL_SEND_EMAIL')).toBeDefined();
649 + expect(findResult(results, 'SLACK_POST_MESSAGE')).toBeDefined();
650
651 // Backend only got the 2 remote tools
652 const backendTools = toolsInstance.executeMetaTool.mock.calls[0][1].arguments.tools;
@@ -582,9 +659,10 @@ describe('ToolRouterSession execution routing', () => {
659 // Both local execute fns were called
660 expect(localExecute).toHaveBeenCalled();
661 expect(sessionExecute).toHaveBeenCalled();
662 + expect(result.successful).toBe(true);
663 });
664
587 - it('should still succeed when one local tool errors in a mixed batch', async () => {
665 + it('should surface errors from both local and remote tools', async () => {
666 const throwingHandle = createCustomTool({
667 slug: 'MIXED_THROWER',
668 name: 'Throws in batch',
@@ -598,30 +676,44 @@ describe('ToolRouterSession execution routing', () => {
676 [customToolHandle, throwingHandle]
677 );
678
601 - toolsInstance.executeMetaTool.mockResolvedValueOnce({
602 - data: { GMAIL_SEND_EMAIL: { sent: true } },
603 - error: null,
604 - successful: true,
605 - });
679 + // Remote also returns an error for one tool
680 + toolsInstance.executeMetaTool.mockResolvedValueOnce(
681 + backendResponse([
682 + { tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } },
683 + { tool_slug: 'SLACK_POST_MESSAGE', data: { message: 'auth failed' }, error: 'auth failed' },
684 + ])
685 + );
686
687 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
688 tools: [
689 { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'ok' } },
690 { tool_slug: 'LOCAL_MIXED_THROWER', arguments: {} },
691 { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'a@b.com' } },
692 + { tool_slug: 'SLACK_POST_MESSAGE', arguments: { channel: '#dev' } },
693 ],
694 sync_response_to_workbench: false,
695 });
696
616 - // Successful local tool still has its data
617 - expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
618 - // Throwing tool has empty data
619 - expect(result.data.LOCAL_MIXED_THROWER).toEqual({});
620 - // Remote tool still ran
621 - expect(result.data).toHaveProperty('GMAIL_SEND_EMAIL');
622 - // Error is surfaced
623 - expect(result.error).toBe('batch-boom');
697 + const { results } = result.data;
698 + expect(results).toHaveLength(4);
699 +
700 + // Local success
701 + const localOk = findResult(results, 'LOCAL_GET_USER_CONTEXT');
702 + expect(localOk.response.successful).toBe(true);
703 +
704 + // Local error — data is empty, error is surfaced
705 + const localErr = findResult(results, 'LOCAL_MIXED_THROWER');
706 + expect(localErr.response.successful).toBe(false);
707 + expect(localErr.response.error).toBe('batch-boom');
708 + expect(localErr.error).toBe('batch-boom');
709 +
710 + // Remote error is also preserved (not dropped!)
711 + const remoteErr = findResult(results, 'SLACK_POST_MESSAGE');
712 + expect(remoteErr.response.error).toBe('auth failed');
713 +
714 + // Top-level error reflects total failure count
715 expect(result.successful).toBe(false);
716 + expect(result.error).toContain('2 out of 4');
717 });
718
719 it('should forward to backend when tools array is empty', async () => {
@@ -646,11 +738,9 @@ describe('ToolRouterSession execution routing', () => {
738 it('should handle non-object items in tools array gracefully', async () => {
739 const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
740
649 - toolsInstance.executeMetaTool.mockResolvedValueOnce({
650 - data: {},
651 - error: null,
652 - successful: true,
653 - });
741 + toolsInstance.executeMetaTool.mockResolvedValueOnce(
742 + backendResponse([])
743 + );
744
745 // Malformed: string instead of object — should not crash
746 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
@@ -663,7 +753,8 @@ describe('ToolRouterSession execution routing', () => {
753 { category: 'ok' },
754 expect.objectContaining({ userId: 'user_1' })
755 );
666 - expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
756 + const { results } = result.data;
757 + expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();
758 });
759
760 it('should execute local and remote in parallel (not sequentially)', async () => {
@@ -696,7 +787,7 @@ describe('ToolRouterSession execution routing', () => {
787 callOrder.push('remote-start');
788 await new Promise(r => setTimeout(r, 50));
789 callOrder.push('remote-end');
699 - return { data: { GMAIL_SEND_EMAIL: { sent: true } }, error: null, successful: true };
790 + return backendResponse([{ tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } }]);
791 });
792
793 await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
@@ -741,27 +832,26 @@ describe('ToolRouterSession execution routing', () => {
832 });
833 });
834
744 - describe('remote batch duplication fix — each remote tool gets its own result', () => {
745 - it('should return per-tool keyed results when multiple remote tools are in a mixed batch', async () => {
835 + describe('per-tool results — each tool gets its own entry in results[]', () => {
836 + it('should return per-tool results for mixed local+remote batch', async () => {
837 const provider = new MockProvider();
838 captureExecuteFn(provider);
839 const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
840
750 - // Mock executeMetaTool to return data keyed by slug (like real backend)
751 - const toolsInstance = (Tools as any).mock.results[
752 - (Tools as any).mock.results.length - 1
753 - ]?.value;
754 -
841 await session.tools();
842
757 - // Re-mock executeMetaTool after session.tools() created the Tools instance
843 const latestToolsInstance = (Tools as any).mock.results[
844 (Tools as any).mock.results.length - 1
845 ].value;
846 latestToolsInstance.executeMetaTool.mockResolvedValueOnce({
847 data: {
763 - GMAIL_SEND_EMAIL: { message_id: 'msg_1' },
764 - SLACK_POST_MESSAGE: { ts: '123456' },
848 + results: [
849 + { response: { successful: true, data: { message_id: 'msg_1' } }, tool_slug: 'GMAIL_SEND_EMAIL', index: 0 },
850 + { response: { successful: true, data: { ts: '123456' } }, tool_slug: 'SLACK_POST_MESSAGE', index: 1 },
851 + ],
852 + total_count: 2,
853 + success_count: 2,
854 + error_count: 0,
855 },
856 error: null,
857 successful: true,
@@ -778,16 +868,17 @@ describe('ToolRouterSession execution routing', () => {
868 sync_response_to_workbench: false,
869 });
870
781 - // Local tool result keyed by its slug
782 - expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
783 - expect(result.data.LOCAL_GET_USER_CONTEXT).toEqual({ local_result: true });
871 + const { results } = result.data;
872 + expect(results).toHaveLength(3);
873
785 - // Each remote tool gets its own keyed result, not the entire batch blob
786 - expect(result.data).toHaveProperty('GMAIL_SEND_EMAIL');
787 - expect(result.data.GMAIL_SEND_EMAIL).toEqual({ message_id: 'msg_1' });
874 + // Each tool has its own entry
875 + const local = results.find((r: any) => r.tool_slug === 'LOCAL_GET_USER_CONTEXT');
876 + const gmail = results.find((r: any) => r.tool_slug === 'GMAIL_SEND_EMAIL');
877 + const slack = results.find((r: any) => r.tool_slug === 'SLACK_POST_MESSAGE');
878
789 - expect(result.data).toHaveProperty('SLACK_POST_MESSAGE');
790 - expect(result.data.SLACK_POST_MESSAGE).toEqual({ ts: '123456' });
879 + expect(local.response.data).toEqual({ local_result: true });
880 + expect(gmail.response.data).toEqual({ message_id: 'msg_1' });
881 + expect(slack.response.data).toEqual({ ts: '123456' });
882 });
883 });
884