Skip to content

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

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

Dhawal Upadhyay19f4a3a305b3
diff --git a/ts/packages/core/src/models/SessionContext.ts b/ts/packages/core/src/models/SessionContext.ts
index 4e74c65da..f92a28633 100644
--- a/ts/packages/core/src/models/SessionContext.ts
+++ b/ts/packages/core/src/models/SessionContext.ts
@@ -5,9 +5,22 @@ import { Composio as ComposioClient } from '@composio/client';
import type { SessionContext } from '../types/customTool.types';
import type { ToolExecuteResponse, ToolProxyParams } from '../types/tool.types';
+/**
+ * Callback that attempts local tool execution.
+ * Returns a Promise if the slug matches a local tool, or undefined to fall back to remote.
+ */
+export type TryLocalExecuteFn = (
+ slug: string,
+ args: Record<string, unknown>
+) => Promise<ToolExecuteResponse> | undefined;
+
/**
* Concrete implementation of SessionContext.
- * Built per local tool invocation inside ToolRouterSession.executeLocalTool().
+ * Built per local tool invocation inside ToolRouterSession.
+ *
+ * When `tryLocalExecute` is provided, `execute()` checks sibling local tools first
+ * before falling back to the backend API. This allows local tool A to call local
+ * tool B via `session.execute('B', ...)` without hitting the network.
*/
export class SessionContextImpl implements SessionContext {
public readonly userId: string;
@@ -15,19 +28,28 @@ export class SessionContextImpl implements SessionContext {
constructor(
private readonly client: ComposioClient,
userId: string,
- private readonly sessionId: string
+ private readonly sessionId: string,
+ private readonly tryLocalExecute?: TryLocalExecuteFn
) {
this.userId = userId;
}
/**
- * Execute any Composio native tool from within a custom tool.
- * Delegates to the tool router session execute endpoint.
+ * Execute any tool from within a custom tool.
+ * Routes to sibling local tools in-process when available,
+ * otherwise delegates to the backend API.
*/
async execute(
toolSlug: string,
arguments_: Record<string, unknown>
): Promise<ToolExecuteResponse> {
+ // Try local tool first (sibling routing)
+ const localResult = this.tryLocalExecute?.(toolSlug, arguments_);
+ if (localResult) {
+ return localResult;
+ }
+
+ // Fall back to remote execution
const response = await this.client.toolRouter.session.execute(
this.sessionId,
{
diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.ts
index 69c6733e0..585cc385c 100644
--- a/ts/packages/core/src/models/ToolRouterSession.ts
+++ b/ts/packages/core/src/models/ToolRouterSession.ts
@@ -25,9 +25,10 @@ import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';
import { ValidationError } from '../errors';
import { Tools } from './Tools';
import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';
-import type { LocalToolsMap, LocalToolsMapEntry } from '../types/customTool.types';
+import type { LocalToolsMap, LocalToolsMapEntry, SessionContext } from '../types/customTool.types';
import type { Tool, ToolExecuteResponse } from '../types/tool.types';
import { SessionContextImpl } from './SessionContext';
+import { findLocalTool, executeLocalTool } from './localToolExecution';
const COMPOSIO_MULTI_EXECUTE_TOOL = 'COMPOSIO_MULTI_EXECUTE_TOOL';
const COMPOSIO_EXECUTE_LOCAL_TOOL = 'COMPOSIO_EXECUTE_LOCAL_TOOL';
@@ -88,7 +89,7 @@ export class ToolRouterSession<
if (toolSlug === COMPOSIO_EXECUTE_LOCAL_TOOL) {
const slug = String(input.tool_slug ?? '');
const args = (input.arguments as Record<string, unknown> | undefined) ?? {};
- const entry = this.findLocalTool(slug);
+ const entry = findLocalTool(this.localToolsMap, slug);
if (!entry) {
return {
data: {},
@@ -96,7 +97,7 @@ export class ToolRouterSession<
successful: false,
};
}
- return this.executeLocalTool(entry, args);
+ return executeLocalTool(entry, args, this.buildSessionContext());
}
// Non-multi-execute meta tools always go to backend
return ToolsModel.executeMetaTool(
@@ -123,16 +124,22 @@ export class ToolRouterSession<
}
/**
- * Get a tool for executing local custom tools individually.
- * Use this for MCP flows or when you need explicit control over local tool execution.
+ * Returns a dispatcher tool that exposes local custom tools for execution.
+ * Primarily used in MCP flows where remote tools are served via an MCP server
+ * and local tools need to be added alongside.
*
* Not included in `session.tools()` — must be explicitly added to the agent's tool set.
*
* @example
* ```typescript
- * const tools = await session.tools();
+ * // MCP flow: remote tools via MCP server, local tools via localTools()
* const localTool = await session.localTools();
- * const agent = new Agent({ tools: [...tools, ...localTool] });
+ * const agent = new Agent({
+ * tools: [
+ * hostedMcpTool(session.mcp.url), // remote tools from MCP
+ * ...localTool, // local custom tools
+ * ],
+ * });
* ```
*/
async localTools(): Promise<ReturnType<TProvider['wrapTools']>> {
@@ -183,7 +190,7 @@ export class ToolRouterSession<
const slug = String(input.tool_slug ?? '');
const args = (input.arguments as Record<string, unknown> | undefined) ?? {};
- const entry = this.findLocalTool(slug);
+ const entry = findLocalTool(this.localToolsMap, slug);
if (!entry) {
return {
data: {},
@@ -192,7 +199,7 @@ export class ToolRouterSession<
};
}
- return this.executeLocalTool(entry, args);
+ return executeLocalTool(entry, args, this.buildSessionContext());
};
return this.config.provider.wrapTools([tool], executeFn) as ReturnType<
@@ -305,9 +312,9 @@ export class ToolRouterSession<
arguments_?: Record<string, unknown>
): Promise<ToolRouterSessionExecuteResponse> {
// Check if this is a local tool (by original or prefixed slug)
- const entry = this.findLocalTool(toolSlug);
+ const entry = findLocalTool(this.localToolsMap, toolSlug);
if (entry) {
- const result = await this.executeLocalTool(entry, arguments_ ?? {});
+ const result = await executeLocalTool(entry, arguments_ ?? {}, this.buildSessionContext());
return {
data: result.data,
error: result.error,
@@ -332,13 +339,21 @@ export class ToolRouterSession<
}
/**
- * Find a local tool entry by slug.
- * Checks both the prefixed map (LOCAL_X — agent path) and original map (X — programmatic path).
+ * Build a SessionContext for local tool execution.
+ * Includes sibling routing: session.execute() inside a custom tool checks
+ * local tools first before falling back to the backend API.
*/
- private findLocalTool(slug: string): LocalToolsMapEntry | undefined {
- if (!this.localToolsMap) return undefined;
- const upper = slug.toUpperCase();
- return this.localToolsMap.byPrefixed.get(upper) ?? this.localToolsMap.byOriginal.get(upper);
+ private buildSessionContext(): SessionContext {
+ return new SessionContextImpl(
+ this.client,
+ this.userId!,
+ this.sessionId,
+ (slug, args) => {
+ const entry = findLocalTool(this.localToolsMap, slug);
+ if (!entry) return undefined;
+ return executeLocalTool(entry, args, this.buildSessionContext());
+ }
+ );
}
/** Parse an individual tool item from COMPOSIO_MULTI_EXECUTE_TOOL's tools array */
@@ -379,7 +394,7 @@ export class ToolRouterSession<
const localItems: Array<{ index: number; entry: LocalToolsMapEntry }> = [];
const remoteIndices: number[] = [];
for (let i = 0; i < parsed.length; i++) {
- const entry = this.findLocalTool(parsed[i].tool_slug);
+ const entry = findLocalTool(this.localToolsMap, parsed[i].tool_slug);
if (entry) {
localItems.push({ index: i, entry });
} else {
@@ -398,7 +413,7 @@ export class ToolRouterSession<
// Execute local tools in parallel
const localPromises = localItems.map(async ({ index, entry }) => {
- const result = await this.executeLocalTool(entry, parsed[index].arguments);
+ const result = await executeLocalTool(entry, parsed[index].arguments, this.buildSessionContext());
return { index, result };
});
@@ -419,79 +434,39 @@ export class ToolRouterSession<
remotePromise,
]);
- // If only local tools, return the single/first result
+ // If only local tools, return the single/first result unwrapped
if (remoteIndices.length === 0 && localResults.length === 1) {
return localResults[0].result;
}
- // Merge: remote results first (remote may write to session files), then local
- const mergedData: Record<string, unknown> = {};
+ // Merge results into the backend's results[] format.
+ // Backend returns: { results: [{ response, tool_slug, index }], total_count, ... }
+ // We append local tool results in the same shape.
+ const remoteData = (remoteResult?.data ?? {}) as Record<string, unknown>;
+ const remoteResults = (Array.isArray(remoteData.results) ? remoteData.results : []) as unknown[];
- // Remote batch data first (backend returns data keyed by tool slug)
- if (remoteResult?.data && typeof remoteResult.data === 'object') {
- Object.assign(mergedData, remoteResult.data);
- }
+ // Build local result entries matching backend format
+ const localEntries = localResults.map(({ index, result }) => ({
+ response: {
+ successful: result.successful,
+ data: result.data,
+ ...(result.error ? { error: result.error } : {}),
+ },
+ tool_slug: parsed[index].tool_slug,
+ index,
+ ...(result.error ? { error: result.error } : {}),
+ }));
- // Local results last
- for (const { index, result } of localResults) {
- mergedData[parsed[index].tool_slug] = result.data;
- }
+ const allResults = [...remoteResults, ...localEntries];
+ const hasAnyError = localResults.some(r => r.result.error) || !!remoteResult?.error;
- const anyLocalError = localResults.find(r => r.result.error)?.result.error;
- const anyError = anyLocalError ?? remoteResult?.error ?? null;
return {
- data: mergedData,
- error: anyError,
- successful: !anyError,
+ data: { ...remoteData, results: allResults },
+ error: hasAnyError
+ ? `${allResults.filter((r: any) => r.error).length} out of ${allResults.length} tools failed`
+ : null,
+ successful: !hasAnyError,
};
}
- /**
- * Execute a local tool in-process.
- * Builds a SessionContext, validates input, calls the user's execute function,
- * and wraps the result into the standard response format.
- *
- * Users just return data or throw — we wrap it here.
- */
- private async executeLocalTool(
- entry: LocalToolsMapEntry,
- arguments_: Record<string, unknown>
- ): Promise<ToolExecuteResponse> {
- const { handle } = entry;
-
- // Validate and transform input using the original Zod schema.
- // This applies defaults, coercions, and transforms (e.g. z.string().default('all')).
- const parsed = handle.inputParams.safeParse(arguments_);
- if (!parsed.success) {
- return {
- data: {},
- error: `Input validation failed: ${parsed.error.message}`,
- successful: false,
- };
- }
-
- // Build session context
- const sessionContext = new SessionContextImpl(
- this.client,
- this.userId!,
- this.sessionId
- );
-
- try {
- // User's execute returns data directly — we wrap into { data, error, successful }
- const data = await handle.execute(parsed.data, sessionContext);
- return {
- data: data ?? {},
- error: null,
- successful: true,
- };
- } catch (err: unknown) {
- const message = err instanceof Error ? err.message : String(err);
- return {
- data: {},
- error: message,
- successful: false,
- };
- }
- }
}
diff --git a/ts/packages/core/src/models/localToolExecution.ts b/ts/packages/core/src/models/localToolExecution.ts
new file mode 100644
index 000000000..31944edde
--- /dev/null
+++ b/ts/packages/core/src/models/localToolExecution.ts
@@ -0,0 +1,62 @@
+/**
+ * @fileoverview Standalone functions for local tool lookup and execution.
+ * Extracted from ToolRouterSession for reuse in SessionContextImpl (sibling routing).
+ */
+import type { LocalToolsMap, LocalToolsMapEntry, SessionContext } from '../types/customTool.types';
+import type { ToolExecuteResponse } from '../types/tool.types';
+
+/**
+ * Find a local tool entry by slug.
+ * Checks both the prefixed map (LOCAL_X — agent path) and original map (X — programmatic path).
+ */
+export function findLocalTool(
+ map: LocalToolsMap | undefined,
+ slug: string
+): LocalToolsMapEntry | undefined {
+ if (!map) return undefined;
+ const upper = slug.toUpperCase();
+ return map.byPrefixed.get(upper) ?? map.byOriginal.get(upper);
+}
+
+/**
+ * Execute a local tool in-process.
+ * Validates input via the Zod schema, calls the user's execute function,
+ * and wraps the result into the standard response format.
+ *
+ * Callers provide a pre-built SessionContext (which may include sibling local routing).
+ */
+export async function executeLocalTool(
+ entry: LocalToolsMapEntry,
+ arguments_: Record<string, unknown>,
+ sessionContext: SessionContext
+): Promise<ToolExecuteResponse> {
+ const { handle } = entry;
+
+ // Validate and transform input using the original Zod schema.
+ // This applies defaults, coercions, and transforms (e.g. z.string().default('all')).
+ const parsed = handle.inputParams.safeParse(arguments_);
+ if (!parsed.success) {
+ return {
+ data: {},
+ error: `Input validation failed: ${parsed.error.message}`,
+ successful: false,
+ };
+ }
+
+ try {
+ // User's execute returns data directly — we wrap into { data, error, successful }
+ const data = await handle.execute(parsed.data, sessionContext);
+ return {
+ data: data ?? {},
+ error: null,
+ successful: true,
+ };
+ } catch (err: unknown) {
+ const message = err instanceof Error ? err.message : String(err);
+ return {
+ data: {},
+ error: message,
+ successful: false,
+ };
+ }
+}
diff --git a/ts/packages/core/test/models/customTool.test.ts b/ts/packages/core/test/models/customTool.test.ts
index 4e6b28e52..73c1308c5 100644
--- a/ts/packages/core/test/models/customTool.test.ts
+++ b/ts/packages/core/test/models/customTool.test.ts
@@ -305,4 +305,53 @@ describe('SessionContextImpl', () => {
ctx.proxyExecute({ endpoint: '/test', method: 'GET' })
).rejects.toThrow('proxyExecute is not yet implemented');
});
+
+ describe('sibling local tool routing', () => {
+ it('should route to local tool when tryLocalExecute matches', async () => {
+ const tryLocalExecute = vi.fn().mockReturnValue(
+ Promise.resolve({ data: { local: true }, error: null, successful: true })
+ );
+
+ const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', tryLocalExecute);
+ const result = await ctx.execute('SIBLING_TOOL', { key: 'val' });
+
+ expect(tryLocalExecute).toHaveBeenCalledWith('SIBLING_TOOL', { key: 'val' });
+ expect(result).toEqual({ data: { local: true }, error: null, successful: true });
+ // Should NOT call remote
+ expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
+ });
+
+ it('should fall back to remote when tryLocalExecute returns undefined', async () => {
+ const tryLocalExecute = vi.fn().mockReturnValue(undefined);
+ mockClient.toolRouter.session.execute.mockResolvedValue({
+ data: { remote: true },
+ error: null,
+ log_id: 'log_3',
+ });
+
+ const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', tryLocalExecute);
+ const result = await ctx.execute('REMOTE_TOOL', { key: 'val' });
+
+ expect(tryLocalExecute).toHaveBeenCalledWith('REMOTE_TOOL', { key: 'val' });
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith('sess_1', {
+ tool_slug: 'REMOTE_TOOL',
+ arguments: { key: 'val' },
+ });
+ expect(result).toEqual({ data: { remote: true }, error: null, successful: true });
+ });
+
+ it('should delegate to remote when no tryLocalExecute is provided', async () => {
+ mockClient.toolRouter.session.execute.mockResolvedValue({
+ data: { remote: true },
+ error: null,
+ log_id: 'log_4',
+ });
+
+ const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
+ const result = await ctx.execute('ANY_TOOL', {});
+
+ expect(mockClient.toolRouter.session.execute).toHaveBeenCalled();
+ expect(result.successful).toBe(true);
+ });
+ });
});
diff --git a/ts/packages/core/test/models/customToolRouting.test.ts b/ts/packages/core/test/models/customToolRouting.test.ts
index 1ccf9bf1d..27eff0151 100644
--- a/ts/packages/core/test/models/customToolRouting.test.ts
+++ b/ts/packages/core/test/models/customToolRouting.test.ts
@@ -275,8 +275,8 @@ describe('ToolRouterSession execution routing', () => {
);
});
- it('should provide a working execute() on SessionContext', async () => {
- // Tool that calls another tool via session.execute()
+ it('should provide a working execute() on SessionContext for remote tools', async () => {
+ // Tool that calls a remote tool via session.execute()
const chainedExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
const inner = await session.execute('GMAIL_SEND_EMAIL', { to: input.to });
return { inner_result: inner.data };
@@ -299,6 +299,47 @@ describe('ToolRouterSession execution routing', () => {
arguments: { to: '[email protected]' },
});
});
+
+ it('should route sibling local tools in-process without hitting the API', async () => {
+ // Tool B — a sibling local tool
+ const siblingExecute = vi.fn().mockResolvedValue({ siblingData: 'from-B' });
+ const toolB = createCustomTool({
+ slug: 'TOOL_B',
+ name: 'Tool B',
+ description: 'Sibling tool',
+ inputParams: z.object({ key: z.string() }),
+ execute: siblingExecute,
+ });
+
+ // Tool A — calls Tool B via session.execute()
+ const toolAExecute = vi.fn().mockImplementation(async (input: any, session: any) => {
+ const inner = await session.execute('TOOL_B', { key: input.value });
+ return { fromA: true, fromB: inner.data };
+ });
+ const toolA = createCustomTool({
+ slug: 'TOOL_A',
+ name: 'Tool A',
+ description: 'Calls sibling tool B',
+ inputParams: z.object({ value: z.string() }),
+ execute: toolAExecute,
+ });
+
+ const session = createSession(mockClient, [toolA, toolB]);
+ const result = await session.execute('TOOL_A', { value: 'hello' });
+
+ // Tool B should have been called in-process
+ expect(siblingExecute).toHaveBeenCalledWith(
+ { key: 'hello' },
+ expect.objectContaining({ userId: 'user_1' })
+ );
+ // Result should contain data from both tools
+ expect(result.data).toEqual({
+ fromA: true,
+ fromB: { siblingData: 'from-B' },
+ });
+ // Should NOT have called the remote API for Tool B
+ expect(mockClient.toolRouter.session.execute).not.toHaveBeenCalled();
+ });
});
describe('session.execute() — error handling', () => {
@@ -492,14 +533,43 @@ describe('ToolRouterSession execution routing', () => {
return { executeFn, toolsInstance, provider, session };
};
- it('should merge results with remote keys first, local keys last', async () => {
+ /** Build a backend-shaped results[] response */
+ const backendResponse = (
+ results: Array<{ tool_slug: string; data: any; error?: string }>,
+ ) => {
+ const items = results.map((r, i) => ({
+ response: {
+ successful: !r.error,
+ data: r.data,
+ ...(r.error ? { error: r.error } : {}),
+ },
+ tool_slug: r.tool_slug,
+ index: i,
+ ...(r.error ? { error: r.error } : {}),
+ }));
+ const errorCount = results.filter(r => r.error).length;
+ return {
+ data: {
+ results: items,
+ total_count: results.length,
+ success_count: results.length - errorCount,
+ error_count: errorCount,
+ },
+ error: errorCount > 0 ? `${errorCount} out of ${results.length} tools failed` : null,
+ successful: errorCount === 0,
+ };
+ };
+
+ /** Find a local tool result in the results[] array by slug */
+ const findResult = (results: any[], slug: string) =>
+ results.find((r: any) => r.tool_slug === slug);
+
+ it('should append local results to remote results array', async () => {
const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
- toolsInstance.executeMetaTool.mockResolvedValueOnce({
- data: { GMAIL_SEND_EMAIL: { sent: true } },
- error: null,
- successful: true,
- });
+ toolsInstance.executeMetaTool.mockResolvedValueOnce(
+ backendResponse([{ tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } }])
+ );
const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
tools: [
@@ -509,11 +579,16 @@ describe('ToolRouterSession execution routing', () => {
sync_response_to_workbench: false,
});
- // Verify ordering: remote keys come before local keys
- const keys = Object.keys(result.data);
- const remoteIdx = keys.indexOf('GMAIL_SEND_EMAIL');
- const localIdx = keys.indexOf('LOCAL_GET_USER_CONTEXT');
- expect(remoteIdx).toBeLessThan(localIdx);
+ // Results is an array with both remote and local entries
+ const { results } = result.data;
+ expect(results).toHaveLength(2);
+
+ // Remote result comes first (from backend), local appended after
+ const remote = findResult(results, 'GMAIL_SEND_EMAIL');
+ const local = findResult(results, 'LOCAL_GET_USER_CONTEXT');
+ expect(remote.response.data).toEqual({ sent: true });
+ expect(local.response.data).toEqual({ local_result: true });
+ expect(local.response.successful).toBe(true);
});
it('should handle multiple local tools in same batch', async () => {
@@ -535,8 +610,11 @@ describe('ToolRouterSession execution routing', () => {
{ fields: 'id,name' },
expect.objectContaining({ userId: 'user_1' })
);
- expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
- expect(result.data).toHaveProperty('LOCAL_GET_AD_ACCOUNTS');
+
+ const { results } = result.data;
+ expect(results).toHaveLength(2);
+ expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();
+ expect(findResult(results, 'LOCAL_GET_AD_ACCOUNTS')).toBeDefined();
});
it('should handle mixed batch with multiple locals + multiple remotes', async () => {
@@ -545,14 +623,12 @@ describe('ToolRouterSession execution routing', () => {
[customToolHandle, sessionToolHandle]
);
- toolsInstance.executeMetaTool.mockResolvedValueOnce({
- data: {
- GMAIL_SEND_EMAIL: { sent: true },
- SLACK_POST_MESSAGE: { ts: '999' },
- },
- error: null,
- successful: true,
- });
+ toolsInstance.executeMetaTool.mockResolvedValueOnce(
+ backendResponse([
+ { tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } },
+ { tool_slug: 'SLACK_POST_MESSAGE', data: { ts: '999' } },
+ ])
+ );
const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
tools: [
@@ -564,12 +640,13 @@ describe('ToolRouterSession execution routing', () => {
sync_response_to_workbench: false,
});
- // All 4 tools should appear in result
- expect(Object.keys(result.data)).toHaveLength(4);
- expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
- expect(result.data).toHaveProperty('LOCAL_GET_AD_ACCOUNTS');
- expect(result.data).toHaveProperty('GMAIL_SEND_EMAIL');
- expect(result.data).toHaveProperty('SLACK_POST_MESSAGE');
+ // All 4 tools should appear in results array
+ const { results } = result.data;
+ expect(results).toHaveLength(4);
+ expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();
+ expect(findResult(results, 'LOCAL_GET_AD_ACCOUNTS')).toBeDefined();
+ expect(findResult(results, 'GMAIL_SEND_EMAIL')).toBeDefined();
+ expect(findResult(results, 'SLACK_POST_MESSAGE')).toBeDefined();
// Backend only got the 2 remote tools
const backendTools = toolsInstance.executeMetaTool.mock.calls[0][1].arguments.tools;
@@ -582,9 +659,10 @@ describe('ToolRouterSession execution routing', () => {
// Both local execute fns were called
expect(localExecute).toHaveBeenCalled();
expect(sessionExecute).toHaveBeenCalled();
+ expect(result.successful).toBe(true);
});
- it('should still succeed when one local tool errors in a mixed batch', async () => {
+ it('should surface errors from both local and remote tools', async () => {
const throwingHandle = createCustomTool({
slug: 'MIXED_THROWER',
name: 'Throws in batch',
@@ -598,30 +676,44 @@ describe('ToolRouterSession execution routing', () => {
[customToolHandle, throwingHandle]
);
- toolsInstance.executeMetaTool.mockResolvedValueOnce({
- data: { GMAIL_SEND_EMAIL: { sent: true } },
- error: null,
- successful: true,
- });
+ // Remote also returns an error for one tool
+ toolsInstance.executeMetaTool.mockResolvedValueOnce(
+ backendResponse([
+ { tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } },
+ { tool_slug: 'SLACK_POST_MESSAGE', data: { message: 'auth failed' }, error: 'auth failed' },
+ ])
+ );
const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
tools: [
{ tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'ok' } },
{ tool_slug: 'LOCAL_MIXED_THROWER', arguments: {} },
{ tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: '[email protected]' } },
+ { tool_slug: 'SLACK_POST_MESSAGE', arguments: { channel: '#dev' } },
],
sync_response_to_workbench: false,
});
- // Successful local tool still has its data
- expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
- // Throwing tool has empty data
- expect(result.data.LOCAL_MIXED_THROWER).toEqual({});
- // Remote tool still ran
- expect(result.data).toHaveProperty('GMAIL_SEND_EMAIL');
- // Error is surfaced
- expect(result.error).toBe('batch-boom');
+ const { results } = result.data;
+ expect(results).toHaveLength(4);
+
+ // Local success
+ const localOk = findResult(results, 'LOCAL_GET_USER_CONTEXT');
+ expect(localOk.response.successful).toBe(true);
+
+ // Local error — data is empty, error is surfaced
+ const localErr = findResult(results, 'LOCAL_MIXED_THROWER');
+ expect(localErr.response.successful).toBe(false);
+ expect(localErr.response.error).toBe('batch-boom');
+ expect(localErr.error).toBe('batch-boom');
+
+ // Remote error is also preserved (not dropped!)
+ const remoteErr = findResult(results, 'SLACK_POST_MESSAGE');
+ expect(remoteErr.response.error).toBe('auth failed');
+
+ // Top-level error reflects total failure count
expect(result.successful).toBe(false);
+ expect(result.error).toContain('2 out of 4');
});
it('should forward to backend when tools array is empty', async () => {
@@ -646,11 +738,9 @@ describe('ToolRouterSession execution routing', () => {
it('should handle non-object items in tools array gracefully', async () => {
const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
- toolsInstance.executeMetaTool.mockResolvedValueOnce({
- data: {},
- error: null,
- successful: true,
- });
+ toolsInstance.executeMetaTool.mockResolvedValueOnce(
+ backendResponse([])
+ );
// Malformed: string instead of object — should not crash
const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
@@ -663,7 +753,8 @@ describe('ToolRouterSession execution routing', () => {
{ category: 'ok' },
expect.objectContaining({ userId: 'user_1' })
);
- expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
+ const { results } = result.data;
+ expect(findResult(results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();
});
it('should execute local and remote in parallel (not sequentially)', async () => {
@@ -696,7 +787,7 @@ describe('ToolRouterSession execution routing', () => {
callOrder.push('remote-start');
await new Promise(r => setTimeout(r, 50));
callOrder.push('remote-end');
- return { data: { GMAIL_SEND_EMAIL: { sent: true } }, error: null, successful: true };
+ return backendResponse([{ tool_slug: 'GMAIL_SEND_EMAIL', data: { sent: true } }]);
});
await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
@@ -741,27 +832,26 @@ describe('ToolRouterSession execution routing', () => {
});
});
- describe('remote batch duplication fix — each remote tool gets its own result', () => {
- it('should return per-tool keyed results when multiple remote tools are in a mixed batch', async () => {
+ describe('per-tool results — each tool gets its own entry in results[]', () => {
+ it('should return per-tool results for mixed local+remote batch', async () => {
const provider = new MockProvider();
captureExecuteFn(provider);
const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
- // Mock executeMetaTool to return data keyed by slug (like real backend)
- const toolsInstance = (Tools as any).mock.results[
- (Tools as any).mock.results.length - 1
- ]?.value;
-
await session.tools();
- // Re-mock executeMetaTool after session.tools() created the Tools instance
const latestToolsInstance = (Tools as any).mock.results[
(Tools as any).mock.results.length - 1
].value;
latestToolsInstance.executeMetaTool.mockResolvedValueOnce({
data: {
- GMAIL_SEND_EMAIL: { message_id: 'msg_1' },
- SLACK_POST_MESSAGE: { ts: '123456' },
+ results: [
+ { response: { successful: true, data: { message_id: 'msg_1' } }, tool_slug: 'GMAIL_SEND_EMAIL', index: 0 },
+ { response: { successful: true, data: { ts: '123456' } }, tool_slug: 'SLACK_POST_MESSAGE', index: 1 },
+ ],
+ total_count: 2,
+ success_count: 2,
+ error_count: 0,
},
error: null,
successful: true,
@@ -778,16 +868,17 @@ describe('ToolRouterSession execution routing', () => {
sync_response_to_workbench: false,
});
- // Local tool result keyed by its slug
- expect(result.data).toHaveProperty('LOCAL_GET_USER_CONTEXT');
- expect(result.data.LOCAL_GET_USER_CONTEXT).toEqual({ local_result: true });
+ const { results } = result.data;
+ expect(results).toHaveLength(3);
- // Each remote tool gets its own keyed result, not the entire batch blob
- expect(result.data).toHaveProperty('GMAIL_SEND_EMAIL');
- expect(result.data.GMAIL_SEND_EMAIL).toEqual({ message_id: 'msg_1' });
+ // Each tool has its own entry
+ const local = results.find((r: any) => r.tool_slug === 'LOCAL_GET_USER_CONTEXT');
+ const gmail = results.find((r: any) => r.tool_slug === 'GMAIL_SEND_EMAIL');
+ const slack = results.find((r: any) => r.tool_slug === 'SLACK_POST_MESSAGE');
- expect(result.data).toHaveProperty('SLACK_POST_MESSAGE');
- expect(result.data.SLACK_POST_MESSAGE).toEqual({ ts: '123456' });
+ expect(local.response.data).toEqual({ local_result: true });
+ expect(gmail.response.data).toEqual({ message_id: 'msg_1' });
+ expect(slack.response.data).toEqual({ ts: '123456' });
});
});