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, 19:30 UTC
Fix: Remove unnecessary API calls during tool execution and Handle execution errors better (#2071)
Musthaq Ahamad committed
Oct 17, 2025 at 18:01 UTC
1c13c5212f597c76f1d5b7e4dfb12e8291a8f623
4 files changed
+97
-192
ts/packages/core/src/errors/ToolErrors.ts
+43
-17
@@ -1,4 +1,6 @@
1
+import { APIError } from '@composio/client';
2
import { ComposioError, ComposioErrorOptions } from './ComposioError';
3
+import { ComposioConnectedAccountNotFoundError } from './ConnectedAccountsErrors';
4
5
export const ToolErrorCodes = {
6
TOOLSET_NOT_DEFINED: 'TOOLSET_NOT_DEFINED',
@@ -75,30 +77,17 @@ export class ComposioCustomToolsNotInitializedError extends ComposioError {
77
}
78
79
export class ComposioToolExecutionError extends ComposioError {
78
- public readonly error: Error;
79
- constructor(
80
- message: string = 'Tool execution error',
81
- options: ComposioErrorOptions & { originalError?: Error } = {}
82
- ) {
83
- const { originalError, ...restOptions } = options;
84
-
80
+ constructor(message: string = 'Tool execution error', options: ComposioErrorOptions = {}) {
81
super(message, {
86
- ...restOptions,
82
+ ...options,
83
code: options.code || ToolErrorCodes.TOOL_EXECUTION_ERROR,
88
- cause: options.cause || originalError,
84
+ cause: options.cause,
85
possibleFixes: options.possibleFixes || [
86
'Ensure the tool is correctly configured and the input is valid',
87
+ 'Ensure the userId is correct and has an active connected account for the user in case of non NoAuth toolkits',
88
],
89
});
90
94
- this.error =
95
- originalError ||
96
- (options.cause instanceof Error
97
- ? options.cause
98
- : options.cause
99
- ? new Error(String(options.cause))
100
- : new Error('Unknown error'));
101
-
91
this.name = 'ComposioToolExecutionError';
92
}
93
}
@@ -134,3 +123,40 @@ export class ComposioGlobalExecuteToolFnNotSetError extends ComposioError {
123
this.name = 'ComposioGlobalExecuteToolFnNotSetError';
124
}
125
}
126
+
127
+export interface ComposioAPIServerErrorBody {
128
+ error: {
129
+ message: string;
130
+ code: number;
131
+ status: number;
132
+ request_id: string;
133
+ suggested_fix: string;
134
+ };
135
+}
136
+
137
+// Map of error codes to their corresponding error constructors
138
+const ERROR_CODE_HANDLERS = new Map<number, (message: string) => ComposioError>([
139
+ [1803, msg => new ComposioConnectedAccountNotFoundError(msg)],
140
+ // Add more error code handlers here as needed
141
+]);
142
+
143
+export const handleToolExecutionError = (tool: string, actualError: Error): ComposioError => {
144
+ // Handle specific API error codes
145
+ if (actualError instanceof APIError && actualError.error) {
146
+ const errorBody = actualError.error as ComposioAPIServerErrorBody;
147
+ const errorCode = errorBody?.error?.code;
148
+ const errorMessage = errorBody?.error?.message;
149
+
150
+ if (errorCode && ERROR_CODE_HANDLERS.has(errorCode)) {
151
+ return ERROR_CODE_HANDLERS.get(errorCode)!(errorMessage || 'An error occurred');
152
+ }
153
+ }
154
+
155
+ // Default error for all other cases
156
+ return new ComposioToolExecutionError(`Error executing the tool ${tool}`, {
157
+ cause: actualError,
158
+ possibleFixes: [
159
+ 'Ensure the tool slug is correct and the input arguments for the tool is valid',
160
+ ],
161
+ });
162
+};
ts/packages/core/src/models/CustomTools.ts
-4
@@ -167,10 +167,6 @@ export class CustomTools {
167
* ```
168
*/
169
async getCustomToolBySlug(slug: string): Promise<Tool | undefined> {
170
- if (!slug) {
171
- throw new Error('Tool slug is required');
172
- }
173
-
170
try {
171
const tool = this.customToolsRegistry.get(slug.toLowerCase());
172
return tool?.schema;
ts/packages/core/src/models/Tools.ts
+54
-161
@@ -40,16 +40,15 @@ import { ExecuteToolFn } from '../types/provider.types';
40
import {
41
ComposioCustomToolsNotInitializedError,
42
ComposioInvalidModifierError,
43
- ComposioToolExecutionError,
43
ComposioToolNotFoundError,
44
ComposioProviderNotDefinedError,
45
} from '../errors/ToolErrors';
46
import { ValidationError } from '../errors/ValidationErrors';
47
import { telemetry } from '../telemetry/Telemetry';
48
import { FileToolModifier } from '../utils/modifiers/FileToolModifier';
50
-import { AuthSchemeTypes } from '../types/authConfigs.types';
49
import { ComposioConfig } from '../composio';
50
import { getToolkitVersion } from '../utils/toolkitVersion';
51
+import { handleToolExecutionError } from '../errors/ToolErrors';
52
/**
53
* This class is used to manage tools in the Composio SDK.
54
* It provides methods to list, get, and execute tools.
@@ -132,51 +131,6 @@ export class Tools<
131
});
132
}
133
135
- /**
136
- * Get the connected account id for a given tool
137
- * @param {string} userId - The user id
138
- * @param {string} toolSlug - The tool slug
139
- * @returns {Promise<string | null>} The connected account id or null if the toolkit is a no auth app
140
- */
141
- private async getConnectedAccountIdForTool(
142
- userId: string,
143
- toolSlug: string
144
- ): Promise<string | null> {
145
- const tool = await this.getRawComposioToolBySlug(toolSlug);
146
- if (!tool.toolkit) {
147
- throw new Error(`Unable to find toolkit for tool ${toolSlug}`);
148
- }
149
-
150
- const toolkit = await this.client.toolkits.retrieve(tool.toolkit.slug);
151
- if (!toolkit) {
152
- throw new Error(`Unable to find toolkit for tool ${toolSlug}`);
153
- }
154
-
155
- // check if the toolkit is a no auth app
156
- const isNoAuthApp = toolkit.auth_config_details?.some(
157
- authConfigDetails => authConfigDetails.mode === AuthSchemeTypes.NO_AUTH
158
- );
159
- // if the toolkit is not a no auth app, fetch connected accounts
160
- if (!isNoAuthApp) {
161
- const connectedAccounts = await this.client.connectedAccounts.list({
162
- user_ids: [userId],
163
- toolkit_slugs: [tool.toolkit.slug],
164
- });
165
- // if no connected accounts, throw an error
166
- if (connectedAccounts.items.length === 0) {
167
- throw new Error('No connected accounts found');
168
- }
169
- // by default, use the first connected account
170
- // @TODO: Add support for multiple connected accounts
171
- logger.warn(
172
- `Using the first connected account for tool ${toolSlug}. To change this behaviour please explicitly pass a connectedAccountId for the tool`
173
- );
174
- return connectedAccounts.items[0].id;
175
- }
176
- // if the toolkit is a no auth app, return null
177
- return null;
178
- }
179
-
134
/**
135
* Applies the default schema modifiers to the tools
136
* @param tools - The tools to apply the default schema modifiers to
@@ -654,100 +608,33 @@ export class Tools<
608
609
/**
610
* @internal
657
- * Handles the execution of a custom tool
611
+ * Executes a composio tool via API without modifiers
612
* @param tool - The tool to execute
613
* @param body - The body of the tool execution
660
- * @param modifiers - The modifiers to be applied to the tool execution
614
* @returns The response from the tool execution
615
*/
663
- private async handleCustomToolExecution(
616
+ private async executeComposioTool(
617
tool: Tool,
665
- body: ToolExecuteParams,
666
- modifiers?: ExecuteToolModifiers
618
+ body: ToolExecuteParams
619
): Promise<ToolExecuteResponse> {
668
- if (modifiers?.beforeExecute) {
669
- if (typeof modifiers.beforeExecute === 'function') {
670
- body = await modifiers.beforeExecute({
671
- toolSlug: tool.slug,
672
- toolkitSlug: tool.toolkit?.slug ?? 'unknown',
673
- params: body,
674
- });
675
- } else {
676
- throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
677
- }
678
- }
679
-
680
- let result = await this.customTools.executeCustomTool(tool.slug, body);
681
-
682
- if (modifiers?.afterExecute) {
683
- if (typeof modifiers.afterExecute === 'function') {
684
- result = await modifiers.afterExecute({
685
- toolSlug: tool.slug,
686
- toolkitSlug: tool.toolkit?.slug ?? 'unknown',
687
- result,
688
- });
689
- } else {
690
- throw new ComposioInvalidModifierError('Invalid afterExecute modifier. Not a function.');
691
- }
692
- }
693
-
694
- return result;
695
- }
696
-
697
- /**
698
- * @internal
699
- * Handles the execution of a composio tool
700
- * @param tool - The tool to execute
701
- * @param body - The body of the tool execution
702
- * @param modifiers - The modifiers to be applied to the tool execution
703
- * @returns The response from the tool execution
704
- */
705
- private async handleComposioToolExecution(
706
- tool: Tool,
707
- body: ToolExecuteParams,
708
- modifiers?: ExecuteToolModifiers
709
- ): Promise<ToolExecuteResponse> {
710
- // apply before execute modifiers
711
- body = await this.applyBeforeExecuteModifiers(
712
- tool,
713
- {
714
- toolSlug: tool.slug,
715
- toolkitSlug: tool.toolkit?.slug ?? 'unknown',
716
- params: body,
717
- },
718
- modifiers?.beforeExecute
719
- );
720
-
721
- // fetch connected accounts if exists
722
- let connectedAccountId = body.connectedAccountId;
723
- if (!connectedAccountId && body.userId) {
724
- connectedAccountId =
725
- (await this.getConnectedAccountIdForTool(body.userId, tool.slug)) || undefined;
620
+ try {
621
+ const result = await this.client.tools.execute(tool.slug, {
622
+ allow_tracing: body.allowTracing,
623
+ connected_account_id: body.connectedAccountId,
624
+ custom_auth_params: body.customAuthParams,
625
+ custom_connection_data: body.customConnectionData,
626
+ arguments: body.arguments,
627
+ user_id: body.userId,
628
+ version:
629
+ body.version ?? getToolkitVersion(tool.toolkit?.slug ?? 'unknown', this.toolkitVersions),
630
+ text: body.text,
631
+ });
632
+ // transform the response to the ToolExecuteResponse format
633
+ return this.transformToolExecuteResponse(result);
634
+ } catch (error) {
635
+ const toolError = handleToolExecutionError(tool.slug, error as Error);
636
+ throw toolError;
637
}
727
-
728
- let result = await this.client.tools.execute(tool.slug, {
729
- allow_tracing: body.allowTracing,
730
- connected_account_id: body.connectedAccountId,
731
- custom_auth_params: body.customAuthParams,
732
- custom_connection_data: body.customConnectionData,
733
- arguments: body.arguments,
734
- user_id: body.userId,
735
- version:
736
- body.version ?? getToolkitVersion(tool.toolkit?.slug ?? 'unknown', this.toolkitVersions),
737
- text: body.text,
738
- });
739
- // apply transformations to the response
740
- result = this.transformToolExecuteResponse(result);
741
- result = await this.applyAfterExecuteModifiers(
742
- tool,
743
- {
744
- toolSlug: tool.slug,
745
- toolkitSlug: tool.toolkit?.slug ?? 'unknown',
746
- result,
747
- },
748
- modifiers?.afterExecute
749
- );
750
- return result;
638
}
639
640
/**
@@ -805,33 +692,39 @@ export class Tools<
692
throw new ValidationError('Invalid tool execute parameters', { cause: executeParams.error });
693
}
694
808
- try {
809
- const customTool = await this.customTools.getCustomToolBySlug(slug);
810
- if (customTool) {
811
- // handle custom tool execution
812
- return this.handleCustomToolExecution(customTool, executeParams.data, modifiers);
813
- } else {
814
- // handle composio tool execution
815
- const composioTool = await this.getRawComposioToolBySlug(slug);
816
- if (!composioTool) {
817
- throw new ComposioToolNotFoundError(
818
- `Tool with slug ${slug} version:${executeParams.data.version} not found`
819
- );
820
- }
821
- return this.handleComposioToolExecution(composioTool, executeParams.data, modifiers);
822
- }
823
- } catch (error) {
824
- throw new ComposioToolExecutionError(
825
- `Error executing tool ${slug} version:${executeParams.data.version}`,
826
- {
827
- originalError: error as Error,
828
- meta: {
829
- toolSlug: slug,
830
- body,
831
- },
832
- }
833
- );
834
- }
695
+ // Determine if it's a custom tool or composio tool
696
+ const customTool = await this.customTools.getCustomToolBySlug(slug);
697
+ const tool = customTool ?? (await this.getRawComposioToolBySlug(slug));
698
+ const toolkitSlug = tool.toolkit?.slug ?? 'unknown';
699
+
700
+ // Apply before execute modifiers
701
+ const params = await this.applyBeforeExecuteModifiers(
702
+ tool,
703
+ {
704
+ toolSlug: slug,
705
+ toolkitSlug,
706
+ params: executeParams.data,
707
+ },
708
+ modifiers?.beforeExecute
709
+ );
710
+
711
+ // Execute the tool (custom or composio)
712
+ let result = customTool
713
+ ? await this.customTools.executeCustomTool(customTool.slug, params)
714
+ : await this.executeComposioTool(tool, params);
715
+
716
+ // Apply after execute modifiers
717
+ result = await this.applyAfterExecuteModifiers(
718
+ tool,
719
+ {
720
+ toolSlug: slug,
721
+ toolkitSlug,
722
+ result,
723
+ },
724
+ modifiers?.afterExecute
725
+ );
726
+
727
+ return result;
728
}
729
730
/**
ts/packages/core/test/utils/toolExecuteUtils.ts
-10
@@ -48,22 +48,12 @@ export const mockToolExecution = async (
48
const getRawComposioToolBySlugSpy = vi.spyOn(tools, 'getRawComposioToolBySlug');
49
getRawComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);
50
51
- // Mock connected account
52
- const getConnectedAccountIdForToolSpy = vi.spyOn(
53
- tools as unknown as {
54
- getConnectedAccountIdForTool: (typeof tools)['getConnectedAccountIdForTool'];
55
- },
56
- 'getConnectedAccountIdForTool'
57
- );
58
- getConnectedAccountIdForToolSpy.mockResolvedValueOnce(connectedAccountId);
59
-
51
// Mock tool execution
52
mockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);
53
54
return {
55
getCustomToolBySlugSpy,
56
getRawComposioToolBySlugSpy,
66
- getConnectedAccountIdForToolSpy,
57
};
58
};
59