Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Fix: Remove unnecessary API calls during tool execution and Handle execution errors better (#2071)
Musthaq Ahamad1c13c5212f59
diff --git a/ts/packages/core/src/errors/ToolErrors.ts b/ts/packages/core/src/errors/ToolErrors.tsindex 4aa8ac4f6..8700bf48b 100644--- a/ts/packages/core/src/errors/ToolErrors.ts+++ b/ts/packages/core/src/errors/ToolErrors.ts@@ -1,4 +1,6 @@+import { APIError } from '@composio/client';import { ComposioError, ComposioErrorOptions } from './ComposioError';+import { ComposioConnectedAccountNotFoundError } from './ConnectedAccountsErrors';export const ToolErrorCodes = {TOOLSET_NOT_DEFINED: 'TOOLSET_NOT_DEFINED',@@ -75,30 +77,17 @@ export class ComposioCustomToolsNotInitializedError extends ComposioError {}export class ComposioToolExecutionError extends ComposioError {- public readonly error: Error;- constructor(- message: string = 'Tool execution error',- options: ComposioErrorOptions & { originalError?: Error } = {}- ) {- const { originalError, ...restOptions } = options;-+ constructor(message: string = 'Tool execution error', options: ComposioErrorOptions = {}) {super(message, {- ...restOptions,+ ...options,code: options.code || ToolErrorCodes.TOOL_EXECUTION_ERROR,- cause: options.cause || originalError,+ cause: options.cause,possibleFixes: options.possibleFixes || ['Ensure the tool is correctly configured and the input is valid',+ 'Ensure the userId is correct and has an active connected account for the user in case of non NoAuth toolkits',],});- this.error =- originalError ||- (options.cause instanceof Error- ? options.cause- : options.cause- ? new Error(String(options.cause))- : new Error('Unknown error'));-this.name = 'ComposioToolExecutionError';}}@@ -134,3 +123,40 @@ export class ComposioGlobalExecuteToolFnNotSetError extends ComposioError {this.name = 'ComposioGlobalExecuteToolFnNotSetError';}}++export interface ComposioAPIServerErrorBody {+ error: {+ message: string;+ code: number;+ status: number;+ request_id: string;+ suggested_fix: string;+ };+}++// Map of error codes to their corresponding error constructors+const ERROR_CODE_HANDLERS = new Map<number, (message: string) => ComposioError>([+ [1803, msg => new ComposioConnectedAccountNotFoundError(msg)],+ // Add more error code handlers here as needed+]);++export const handleToolExecutionError = (tool: string, actualError: Error): ComposioError => {+ // Handle specific API error codes+ if (actualError instanceof APIError && actualError.error) {+ const errorBody = actualError.error as ComposioAPIServerErrorBody;+ const errorCode = errorBody?.error?.code;+ const errorMessage = errorBody?.error?.message;++ if (errorCode && ERROR_CODE_HANDLERS.has(errorCode)) {+ return ERROR_CODE_HANDLERS.get(errorCode)!(errorMessage || 'An error occurred');+ }+ }++ // Default error for all other cases+ return new ComposioToolExecutionError(`Error executing the tool ${tool}`, {+ cause: actualError,+ possibleFixes: [+ 'Ensure the tool slug is correct and the input arguments for the tool is valid',+ ],+ });+};diff --git a/ts/packages/core/src/models/CustomTools.ts b/ts/packages/core/src/models/CustomTools.tsindex 81573d053..4fff46dbc 100644--- a/ts/packages/core/src/models/CustomTools.ts+++ b/ts/packages/core/src/models/CustomTools.ts@@ -167,10 +167,6 @@ export class CustomTools {* ```*/async getCustomToolBySlug(slug: string): Promise<Tool | undefined> {- if (!slug) {- throw new Error('Tool slug is required');- }-try {const tool = this.customToolsRegistry.get(slug.toLowerCase());return tool?.schema;diff --git a/ts/packages/core/src/models/Tools.ts b/ts/packages/core/src/models/Tools.tsindex 30c17e29b..3648a2a50 100644--- a/ts/packages/core/src/models/Tools.ts+++ b/ts/packages/core/src/models/Tools.ts@@ -40,16 +40,15 @@ import { ExecuteToolFn } from '../types/provider.types';import {ComposioCustomToolsNotInitializedError,ComposioInvalidModifierError,- ComposioToolExecutionError,ComposioToolNotFoundError,ComposioProviderNotDefinedError,} from '../errors/ToolErrors';import { ValidationError } from '../errors/ValidationErrors';import { telemetry } from '../telemetry/Telemetry';import { FileToolModifier } from '../utils/modifiers/FileToolModifier';-import { AuthSchemeTypes } from '../types/authConfigs.types';import { ComposioConfig } from '../composio';import { getToolkitVersion } from '../utils/toolkitVersion';+import { handleToolExecutionError } from '../errors/ToolErrors';/*** This class is used to manage tools in the Composio SDK.* It provides methods to list, get, and execute tools.@@ -132,51 +131,6 @@ export class Tools<});}- /**- * Get the connected account id for a given tool- * @param {string} userId - The user id- * @param {string} toolSlug - The tool slug- * @returns {Promise<string | null>} The connected account id or null if the toolkit is a no auth app- */- private async getConnectedAccountIdForTool(- userId: string,- toolSlug: string- ): Promise<string | null> {- const tool = await this.getRawComposioToolBySlug(toolSlug);- if (!tool.toolkit) {- throw new Error(`Unable to find toolkit for tool ${toolSlug}`);- }-- const toolkit = await this.client.toolkits.retrieve(tool.toolkit.slug);- if (!toolkit) {- throw new Error(`Unable to find toolkit for tool ${toolSlug}`);- }-- // check if the toolkit is a no auth app- const isNoAuthApp = toolkit.auth_config_details?.some(- authConfigDetails => authConfigDetails.mode === AuthSchemeTypes.NO_AUTH- );- // if the toolkit is not a no auth app, fetch connected accounts- if (!isNoAuthApp) {- const connectedAccounts = await this.client.connectedAccounts.list({- user_ids: [userId],- toolkit_slugs: [tool.toolkit.slug],- });- // if no connected accounts, throw an error- if (connectedAccounts.items.length === 0) {- throw new Error('No connected accounts found');- }- // by default, use the first connected account- // @TODO: Add support for multiple connected accounts- logger.warn(- `Using the first connected account for tool ${toolSlug}. To change this behaviour please explicitly pass a connectedAccountId for the tool`- );- return connectedAccounts.items[0].id;- }- // if the toolkit is a no auth app, return null- return null;- }-/*** Applies the default schema modifiers to the tools* @param tools - The tools to apply the default schema modifiers to@@ -654,100 +608,33 @@ export class Tools</*** @internal- * Handles the execution of a custom tool+ * Executes a composio tool via API without modifiers* @param tool - The tool to execute* @param body - The body of the tool execution- * @param modifiers - The modifiers to be applied to the tool execution* @returns The response from the tool execution*/- private async handleCustomToolExecution(+ private async executeComposioTool(tool: Tool,- body: ToolExecuteParams,- modifiers?: ExecuteToolModifiers+ body: ToolExecuteParams): Promise<ToolExecuteResponse> {- if (modifiers?.beforeExecute) {- if (typeof modifiers.beforeExecute === 'function') {- body = await modifiers.beforeExecute({- toolSlug: tool.slug,- toolkitSlug: tool.toolkit?.slug ?? 'unknown',- params: body,- });- } else {- throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');- }- }-- let result = await this.customTools.executeCustomTool(tool.slug, body);-- if (modifiers?.afterExecute) {- if (typeof modifiers.afterExecute === 'function') {- result = await modifiers.afterExecute({- toolSlug: tool.slug,- toolkitSlug: tool.toolkit?.slug ?? 'unknown',- result,- });- } else {- throw new ComposioInvalidModifierError('Invalid afterExecute modifier. Not a function.');- }- }-- return result;- }-- /**- * @internal- * Handles the execution of a composio tool- * @param tool - The tool to execute- * @param body - The body of the tool execution- * @param modifiers - The modifiers to be applied to the tool execution- * @returns The response from the tool execution- */- private async handleComposioToolExecution(- tool: Tool,- body: ToolExecuteParams,- modifiers?: ExecuteToolModifiers- ): Promise<ToolExecuteResponse> {- // apply before execute modifiers- body = await this.applyBeforeExecuteModifiers(- tool,- {- toolSlug: tool.slug,- toolkitSlug: tool.toolkit?.slug ?? 'unknown',- params: body,- },- modifiers?.beforeExecute- );-- // fetch connected accounts if exists- let connectedAccountId = body.connectedAccountId;- if (!connectedAccountId && body.userId) {- connectedAccountId =- (await this.getConnectedAccountIdForTool(body.userId, tool.slug)) || undefined;+ try {+ const result = await this.client.tools.execute(tool.slug, {+ allow_tracing: body.allowTracing,+ connected_account_id: body.connectedAccountId,+ custom_auth_params: body.customAuthParams,+ custom_connection_data: body.customConnectionData,+ arguments: body.arguments,+ user_id: body.userId,+ version:+ body.version ?? getToolkitVersion(tool.toolkit?.slug ?? 'unknown', this.toolkitVersions),+ text: body.text,+ });+ // transform the response to the ToolExecuteResponse format+ return this.transformToolExecuteResponse(result);+ } catch (error) {+ const toolError = handleToolExecutionError(tool.slug, error as Error);+ throw toolError;}-- let result = await this.client.tools.execute(tool.slug, {- allow_tracing: body.allowTracing,- connected_account_id: body.connectedAccountId,- custom_auth_params: body.customAuthParams,- custom_connection_data: body.customConnectionData,- arguments: body.arguments,- user_id: body.userId,- version:- body.version ?? getToolkitVersion(tool.toolkit?.slug ?? 'unknown', this.toolkitVersions),- text: body.text,- });- // apply transformations to the response- result = this.transformToolExecuteResponse(result);- result = await this.applyAfterExecuteModifiers(- tool,- {- toolSlug: tool.slug,- toolkitSlug: tool.toolkit?.slug ?? 'unknown',- result,- },- modifiers?.afterExecute- );- return result;}/**@@ -805,33 +692,39 @@ export class Tools<throw new ValidationError('Invalid tool execute parameters', { cause: executeParams.error });}- try {- const customTool = await this.customTools.getCustomToolBySlug(slug);- if (customTool) {- // handle custom tool execution- return this.handleCustomToolExecution(customTool, executeParams.data, modifiers);- } else {- // handle composio tool execution- const composioTool = await this.getRawComposioToolBySlug(slug);- if (!composioTool) {- throw new ComposioToolNotFoundError(- `Tool with slug ${slug} version:${executeParams.data.version} not found`- );- }- return this.handleComposioToolExecution(composioTool, executeParams.data, modifiers);- }- } catch (error) {- throw new ComposioToolExecutionError(- `Error executing tool ${slug} version:${executeParams.data.version}`,- {- originalError: error as Error,- meta: {- toolSlug: slug,- body,- },- }- );- }+ // Determine if it's a custom tool or composio tool+ const customTool = await this.customTools.getCustomToolBySlug(slug);+ const tool = customTool ?? (await this.getRawComposioToolBySlug(slug));+ const toolkitSlug = tool.toolkit?.slug ?? 'unknown';++ // Apply before execute modifiers+ const params = await this.applyBeforeExecuteModifiers(+ tool,+ {+ toolSlug: slug,+ toolkitSlug,+ params: executeParams.data,+ },+ modifiers?.beforeExecute+ );++ // Execute the tool (custom or composio)+ let result = customTool+ ? await this.customTools.executeCustomTool(customTool.slug, params)+ : await this.executeComposioTool(tool, params);++ // Apply after execute modifiers+ result = await this.applyAfterExecuteModifiers(+ tool,+ {+ toolSlug: slug,+ toolkitSlug,+ result,+ },+ modifiers?.afterExecute+ );++ return result;}/**diff --git a/ts/packages/core/test/utils/toolExecuteUtils.ts b/ts/packages/core/test/utils/toolExecuteUtils.tsindex 601bfa40c..e468e2eac 100644--- a/ts/packages/core/test/utils/toolExecuteUtils.ts+++ b/ts/packages/core/test/utils/toolExecuteUtils.ts@@ -48,22 +48,12 @@ export const mockToolExecution = async (const getRawComposioToolBySlugSpy = vi.spyOn(tools, 'getRawComposioToolBySlug');getRawComposioToolBySlugSpy.mockResolvedValueOnce(toolMocks.transformedTool as unknown as Tool);- // Mock connected account- const getConnectedAccountIdForToolSpy = vi.spyOn(- tools as unknown as {- getConnectedAccountIdForTool: (typeof tools)['getConnectedAccountIdForTool'];- },- 'getConnectedAccountIdForTool'- );- getConnectedAccountIdForToolSpy.mockResolvedValueOnce(connectedAccountId);-// Mock tool executionmockClient.tools.execute.mockResolvedValueOnce(toolMocks.rawToolExecuteResponse);return {getCustomToolBySlugSpy,getRawComposioToolBySlugSpy,- getConnectedAccountIdForToolSpy,};};