-
Notifications
You must be signed in to change notification settings - Fork 2.6k
fix: improve MCP tool error handling with retry logic and better messages #6191
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -54,29 +54,54 @@ async function validateParams( | |||||
| return { isValid: false } | ||||||
| } | ||||||
|
|
||||||
| // Validate server name format | ||||||
| const serverName = params.server_name.trim() | ||||||
| if (!serverName) { | ||||||
| cline.consecutiveMistakeCount++ | ||||||
| cline.recordToolError("use_mcp_tool") | ||||||
| await cline.say("error", "Server name cannot be empty or contain only whitespace") | ||||||
| pushToolResult(formatResponse.toolError("Invalid server name: cannot be empty")) | ||||||
| return { isValid: false } | ||||||
| } | ||||||
|
|
||||||
| // Validate tool name format | ||||||
| const toolName = params.tool_name.trim() | ||||||
| if (!toolName) { | ||||||
| cline.consecutiveMistakeCount++ | ||||||
| cline.recordToolError("use_mcp_tool") | ||||||
| await cline.say("error", "Tool name cannot be empty or contain only whitespace") | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Similarly, use i18n for the tool name error message rather than a literal string.
Suggested change
This comment was generated because it violated a code review rule: irule_C0ez7Rji6ANcGkkX. |
||||||
| pushToolResult(formatResponse.toolError("Invalid tool name: cannot be empty")) | ||||||
| return { isValid: false } | ||||||
| } | ||||||
|
|
||||||
| let parsedArguments: Record<string, unknown> | undefined | ||||||
|
|
||||||
| if (params.arguments) { | ||||||
| try { | ||||||
| parsedArguments = JSON.parse(params.arguments) | ||||||
|
|
||||||
| // Validate that arguments is an object (not array or primitive) | ||||||
| if ((parsedArguments !== null && typeof parsedArguments !== "object") || Array.isArray(parsedArguments)) { | ||||||
| throw new Error("Arguments must be a JSON object, not an array or primitive value") | ||||||
| } | ||||||
| } catch (error) { | ||||||
| cline.consecutiveMistakeCount++ | ||||||
| cline.recordToolError("use_mcp_tool") | ||||||
| await cline.say("error", t("mcp:errors.invalidJsonArgument", { toolName: params.tool_name })) | ||||||
|
|
||||||
| const errorMessage = error instanceof Error ? error.message : "Invalid JSON" | ||||||
| await cline.say("error", `Invalid JSON arguments for tool '${toolName}': ${errorMessage}`) | ||||||
|
|
||||||
| pushToolResult( | ||||||
| formatResponse.toolError( | ||||||
| formatResponse.invalidMcpToolArgumentError(params.server_name, params.tool_name), | ||||||
| ), | ||||||
| formatResponse.toolError(`Invalid JSON arguments for ${serverName}.${toolName}: ${errorMessage}`), | ||||||
| ) | ||||||
| return { isValid: false } | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| return { | ||||||
| isValid: true, | ||||||
| serverName: params.server_name, | ||||||
| toolName: params.tool_name, | ||||||
| serverName, | ||||||
| toolName, | ||||||
| parsedArguments, | ||||||
| } | ||||||
| } | ||||||
|
|
@@ -127,41 +152,74 @@ async function executeToolAndProcessResult( | |||||
| toolName, | ||||||
| }) | ||||||
|
|
||||||
| const toolResult = await cline.providerRef.deref()?.getMcpHub()?.callTool(serverName, toolName, parsedArguments) | ||||||
| let retryCount = 0 | ||||||
| const maxRetries = 3 | ||||||
| let lastError: Error | null = null | ||||||
|
|
||||||
| let toolResultPretty = "(No response)" | ||||||
| while (retryCount <= maxRetries) { | ||||||
| try { | ||||||
| const mcpHub = cline.providerRef.deref()?.getMcpHub() | ||||||
| if (!mcpHub) { | ||||||
| throw new Error("MCP Hub is not available. Please ensure MCP servers are properly configured.") | ||||||
| } | ||||||
|
|
||||||
| if (toolResult) { | ||||||
| const outputText = processToolContent(toolResult) | ||||||
| const toolResult = await mcpHub.callTool(serverName, toolName, parsedArguments) | ||||||
|
|
||||||
| if (outputText) { | ||||||
| await sendExecutionStatus(cline, { | ||||||
| executionId, | ||||||
| status: "output", | ||||||
| response: outputText, | ||||||
| }) | ||||||
| if (toolResult) { | ||||||
| const outputText = processToolContent(toolResult) | ||||||
|
|
||||||
| toolResultPretty = (toolResult.isError ? "Error:\n" : "") + outputText | ||||||
| } | ||||||
| if (outputText) { | ||||||
| await sendExecutionStatus(cline, { | ||||||
| executionId, | ||||||
| status: "output", | ||||||
| response: outputText, | ||||||
| }) | ||||||
|
|
||||||
| // Send completion status | ||||||
| await sendExecutionStatus(cline, { | ||||||
| executionId, | ||||||
| status: toolResult.isError ? "error" : "completed", | ||||||
| response: toolResultPretty, | ||||||
| error: toolResult.isError ? "Error executing MCP tool" : undefined, | ||||||
| }) | ||||||
| } else { | ||||||
| // Send error status if no result | ||||||
| await sendExecutionStatus(cline, { | ||||||
| executionId, | ||||||
| status: "error", | ||||||
| error: "No response from MCP server", | ||||||
| }) | ||||||
| const toolResultPretty = (toolResult.isError ? "Error:\n" : "") + outputText | ||||||
|
|
||||||
| // Send completion status | ||||||
| await sendExecutionStatus(cline, { | ||||||
| executionId, | ||||||
| status: toolResult.isError ? "error" : "completed", | ||||||
| response: toolResultPretty, | ||||||
| error: toolResult.isError ? outputText : undefined, | ||||||
| }) | ||||||
|
|
||||||
| await cline.say("mcp_server_response", toolResultPretty) | ||||||
| pushToolResult(formatResponse.toolResult(toolResultPretty)) | ||||||
| return | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| // If we get here, toolResult was null/undefined | ||||||
| throw new Error(`No response received from MCP server '${serverName}' for tool '${toolName}'`) | ||||||
| } catch (error) { | ||||||
| lastError = error instanceof Error ? error : new Error(String(error)) | ||||||
| retryCount++ | ||||||
|
|
||||||
| if (retryCount <= maxRetries) { | ||||||
| const delay = Math.min(1000 * Math.pow(2, retryCount - 1), 5000) // Exponential backoff with max 5s | ||||||
| await cline.say( | ||||||
| "error", | ||||||
| `MCP tool execution failed (attempt ${retryCount}/${maxRetries}). Retrying in ${delay / 1000}s...`, | ||||||
| ) | ||||||
| await new Promise((resolve) => setTimeout(resolve, delay)) | ||||||
| } | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| await cline.say("mcp_server_response", toolResultPretty) | ||||||
| pushToolResult(formatResponse.toolResult(toolResultPretty)) | ||||||
| // All retries failed | ||||||
| const errorMessage = lastError?.message || "Unknown error occurred" | ||||||
| const userFriendlyError = `Failed to execute MCP tool '${toolName}' on server '${serverName}' after ${maxRetries} attempts. ${errorMessage}` | ||||||
|
|
||||||
| await sendExecutionStatus(cline, { | ||||||
| executionId, | ||||||
| status: "error", | ||||||
| error: userFriendlyError, | ||||||
| }) | ||||||
|
|
||||||
| await cline.say("mcp_server_response", `Error: ${userFriendlyError}`) | ||||||
| pushToolResult(formatResponse.toolError(userFriendlyError)) | ||||||
| } | ||||||
|
|
||||||
| export async function useMcpToolTool( | ||||||
|
|
||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider using the translation function (t) for user‐facing error messages instead of hardcoding strings (e.g. 'Server name cannot be empty or contain only whitespace'). This will ensure consistency with i18n practices.
This comment was generated because it violated a code review rule: irule_C0ez7Rji6ANcGkkX.