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(tool-router): harden multi-execute edge cases

Dhawal Upadhyay24918adc0118
diff --git a/python/composio/core/models/custom_tool.py b/python/composio/core/models/custom_tool.py
index 905474486..626a423e0 100644
--- a/python/composio/core/models/custom_tool.py
+++ b/python/composio/core/models/custom_tool.py
@@ -391,12 +391,6 @@ class ExperimentalToolkit:
output_params=output_params,
# No extends_toolkit for toolkit tools
)
- if custom_tool.extends_toolkit:
- raise ValidationError(
- f'experimental.Toolkit.tool: tool "{custom_tool.slug}" has '
- f"extends_toolkit set. Tools in a custom toolkit must not "
- f"use extends_toolkit — they inherit the toolkit identity."
- )
_validate_slug_length(
custom_tool.slug, self.slug, f'experimental.Toolkit("{self.slug}").tool'
)
diff --git a/python/composio/core/models/tool_router_session.py b/python/composio/core/models/tool_router_session.py
index 75ccec442..48fefca9c 100644
--- a/python/composio/core/models/tool_router_session.py
+++ b/python/composio/core/models/tool_router_session.py
@@ -169,6 +169,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
Applies before_execute/after_execute modifiers around the overall
COMPOSIO_MULTI_EXECUTE_TOOL call, consistent with the standard path.
"""
+ backend_execute = tools_model._wrap_execute_tool_for_tool_router(
+ session_id=self.session_id,
+ modifiers=modifiers,
+ )
def routing_execute(slug: str, arguments: t.Dict) -> t.Dict:
if slug == COMPOSIO_MULTI_EXECUTE_TOOL:
@@ -204,10 +208,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
return result
# Non-multi-execute meta tools always go to backend
- return tools_model._wrap_execute_tool_for_tool_router(
- session_id=self.session_id,
- modifiers=modifiers,
- )(slug, arguments)
+ return backend_execute(slug, arguments)
return routing_execute
@@ -323,26 +324,35 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
local_entries.append(local_entry)
# Merge: remotes first, locals appended (matches TS behavior —
- # remote results may be stored in workbench with index references)
- remote_data = (remote_result or {}).get("data", {})
+ # remote results may have workbench index references)
+ remote_data_raw = (remote_result or {}).get("data")
+ remote_data = remote_data_raw if isinstance(remote_data_raw, dict) else {}
remote_results_list = (
- remote_data.get("results", []) if isinstance(remote_data, dict) else []
+ remote_data.get("results", []) if isinstance(remote_data.get("results"), list) else []
)
all_results = [
{**entry, "index": i}
for i, entry in enumerate([*remote_results_list, *local_entries])
]
- has_any_error = any(r.get("error") for _, r in local_results) or bool(
- remote_result and remote_result.get("error")
+ remote_error = (
+ str(remote_result.get("error"))
+ if remote_result and remote_result.get("error") is not None
+ else None
)
+ has_any_error = any(r.get("error") for _, r in local_results) or bool(remote_error)
failed = sum(1 for r in all_results if r.get("error"))
+ error_message = None
+ if has_any_error:
+ error_message = (
+ remote_error
+ if remote_error is not None and failed == 0
+ else f"{failed} out of {len(all_results)} tools failed"
+ )
return {
"data": {**remote_data, "results": all_results},
- "error": f"{failed} out of {len(all_results)} tools failed"
- if has_any_error
- else None,
+ "error": error_message,
"successful": not has_any_error,
}
diff --git a/python/tests/test_custom_tools.py b/python/tests/test_custom_tools.py
index 8687a3852..959b2ac10 100644
--- a/python/tests/test_custom_tools.py
+++ b/python/tests/test_custom_tools.py
@@ -700,3 +700,44 @@ class TestMultiExecuteRouting:
)
assert result["successful"] is False
assert "1 out of 2" in result["error"]
+
+ def test_remote_null_data_does_not_crash(self, grep_tool):
+ s = self._make_session(grep_tool)
+ tm = MagicMock()
+ remote = {"data": None, "error": None, "successful": True}
+ tm._wrap_execute_tool_for_tool_router.return_value = lambda slug, args: remote
+ result = s._route_multi_execute(
+ {
+ "tools": [
+ {"tool_slug": "GREP", "arguments": {"pattern": "x"}},
+ {"tool_slug": "REMOTE", "arguments": {}},
+ ]
+ },
+ tm,
+ )
+ assert result["successful"] is True
+ assert result["data"]["results"][0]["tool_slug"] == "GREP"
+
+ def test_remote_batch_error_without_item_errors_uses_batch_message(self, grep_tool):
+ s = self._make_session(grep_tool)
+ tm = MagicMock()
+ remote = {
+ "data": None,
+ "error": "Remote batch failed before per-tool results were produced",
+ "successful": False,
+ }
+ tm._wrap_execute_tool_for_tool_router.return_value = lambda slug, args: remote
+ result = s._route_multi_execute(
+ {
+ "tools": [
+ {"tool_slug": "GREP", "arguments": {"pattern": "x"}},
+ {"tool_slug": "REMOTE", "arguments": {}},
+ ]
+ },
+ tm,
+ )
+ assert result["successful"] is False
+ assert (
+ result["error"]
+ == "Remote batch failed before per-tool results were produced"
+ )
diff --git a/ts/packages/core/src/models/ToolRouterSession.ts b/ts/packages/core/src/models/ToolRouterSession.ts
index e2b9846b8..108c5be50 100644
--- a/ts/packages/core/src/models/ToolRouterSession.ts
+++ b/ts/packages/core/src/models/ToolRouterSession.ts
@@ -115,7 +115,7 @@ export class ToolRouterSession<
if (!this.config?.provider) {
throw new Error(
'A provider is required when using custom tools with session.tools(). ' +
- 'Pass a provider in the Composio constructor.'
+ 'Pass a provider in the Composio constructor.'
);
}
return this.config.provider.wrapTools(tools, routingExecuteFn) as ReturnType<
@@ -313,7 +313,9 @@ export class ToolRouterSession<
* @param params - Proxy request parameters (toolkit, endpoint, method, body, headers/query params)
* @returns The proxied API response with status, data, headers
*/
- async proxyExecute(params: SessionProxyExecuteParams): Promise<ToolRouterSessionProxyExecuteResponse> {
+ async proxyExecute(
+ params: SessionProxyExecuteParams
+ ): Promise<ToolRouterSessionProxyExecuteResponse> {
const validated = SessionProxyExecuteParamsSchema.safeParse(params);
if (!validated.success) {
throw new ValidationError('Invalid proxy execute parameters', { cause: validated.error });
@@ -329,14 +331,16 @@ export class ToolRouterSession<
status: response.status,
data: response.data,
headers: response.headers,
- ...(response.binary_data ? {
- binaryData: {
- contentType: response.binary_data.content_type,
- size: response.binary_data.size,
- url: response.binary_data.url,
- expiresAt: response.binary_data.expires_at,
- },
- } : {}),
+ ...(response.binary_data
+ ? {
+ binaryData: {
+ contentType: response.binary_data.content_type,
+ size: response.binary_data.size,
+ url: response.binary_data.url,
+ expiresAt: response.binary_data.expires_at,
+ },
+ }
+ : {}),
};
}
@@ -432,8 +436,16 @@ export class ToolRouterSession<
}
// Merge results into the backend's results[] format.
- const remoteData = (remoteResult?.data ?? {}) as Record<string, unknown>;
- const remoteResults = (Array.isArray(remoteData.results) ? remoteData.results : []) as unknown[];
+ const remoteData = (
+ remoteResult?.data &&
+ typeof remoteResult.data === 'object' &&
+ !Array.isArray(remoteResult.data)
+ ? remoteResult.data
+ : {}
+ ) as Record<string, unknown>;
+ const remoteResults = (
+ Array.isArray(remoteData.results) ? remoteData.results : []
+ ) as unknown[];
// Build local result entries matching backend format
const localEntries = localResults.map(({ index, result }) => ({
@@ -451,19 +463,24 @@ export class ToolRouterSession<
...(remoteResults as Array<Record<string, unknown>>),
...localEntries,
];
- const allResults = merged.map((entry, i): Record<string, unknown> => ({
- ...entry,
- index: i,
- }));
- const hasAnyError = localResults.some(r => r.result.error) || !!remoteResult?.error;
+ const allResults = merged.map(
+ (entry, i): Record<string, unknown> => ({
+ ...entry,
+ index: i,
+ })
+ );
+ const remoteError = typeof remoteResult?.error === 'string' ? remoteResult.error : null;
+ const hasAnyError = localResults.some(r => r.result.error) || !!remoteError;
+ const failedCount = allResults.filter(r => r.error).length;
return {
data: { ...remoteData, results: allResults },
error: hasAnyError
- ? `${allResults.filter(r => r.error).length} out of ${allResults.length} tools failed`
+ ? remoteError && failedCount === 0
+ ? remoteError
+ : `${failedCount} out of ${allResults.length} tools failed`
: null,
successful: !hasAnyError,
};
}
-
}
diff --git a/ts/packages/core/test/models/customToolRouting.test.ts b/ts/packages/core/test/models/customToolRouting.test.ts
index c35248f64..264fab316 100644
--- a/ts/packages/core/test/models/customToolRouting.test.ts
+++ b/ts/packages/core/test/models/customToolRouting.test.ts
@@ -671,6 +671,28 @@ describe('ToolRouterSession execution routing', () => {
expect(result.successful).toBe(true);
});
+ it('should handle remote null data without crashing', async () => {
+ const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
+
+ toolsInstance.executeMetaTool.mockResolvedValueOnce({
+ data: null,
+ error: null,
+ successful: true,
+ });
+
+ const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
+ tools: [
+ { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'x' } },
+ { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: '[email protected]' } },
+ ],
+ sync_response_to_workbench: false,
+ });
+
+ expect(result.successful).toBe(true);
+ expect(result.data.results).toHaveLength(1);
+ expect(findResult(result.data.results, 'LOCAL_GET_USER_CONTEXT')).toBeDefined();
+ });
+
it('should surface errors from both local and remote tools', async () => {
const throwingHandle = createCustomTool('MIXED_THROWER', {
name: 'Throws in batch',
@@ -725,6 +747,27 @@ describe('ToolRouterSession execution routing', () => {
expect(result.error).toContain('2 out of 4');
});
+ it('should preserve batch-level remote errors when no per-tool remote results exist', async () => {
+ const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
+
+ toolsInstance.executeMetaTool.mockResolvedValueOnce({
+ data: null,
+ error: 'Remote batch failed before per-tool results were produced',
+ successful: false,
+ });
+
+ const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
+ tools: [
+ { tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'x' } },
+ { tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: '[email protected]' } },
+ ],
+ sync_response_to_workbench: false,
+ });
+
+ expect(result.successful).toBe(false);
+ expect(result.error).toBe('Remote batch failed before per-tool results were produced');
+ });
+
it('should forward to backend when tools array is empty', async () => {
const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);