diff --git a/packages/mcp-client/src/McpClient.ts b/packages/mcp-client/src/McpClient.ts index 8b105a0eaa..29ea633db5 100644 --- a/packages/mcp-client/src/McpClient.ts +++ b/packages/mcp-client/src/McpClient.ts @@ -181,8 +181,6 @@ export class McpClient { for (const toolCall of Object.values(finalToolCalls)) { const toolName = toolCall.function.name ?? "unknown"; /// TODO(Fix upstream type so this is always a string)^ - const toolArgs = toolCall.function.arguments === "" ? {} : JSON.parse(toolCall.function.arguments); - const toolMessage: ChatCompletionInputMessageTool = { role: "tool", tool_call_id: toolCall.id, @@ -193,11 +191,29 @@ export class McpClient { messages.push(toolMessage); return yield toolMessage; } + let toolArgs: Record = {}; + try { + toolArgs = toolCall.function.arguments === "" ? {} : JSON.parse(toolCall.function.arguments); + } catch (error) { + if (error instanceof SyntaxError) { + toolMessage.content = `Invalid JSON generated by the model: ${error.message}`; + messages.push(toolMessage); + yield toolMessage; + continue; + } else { + throw error; + } + } + /// Get the appropriate session for this tool const client = this.clients.get(toolName); if (client) { - const result = await client.callTool({ name: toolName, arguments: toolArgs, signal: opts.abortSignal }); - toolMessage.content = ResultFormatter.format(result); + try { + const result = await client.callTool({ name: toolName, arguments: toolArgs, signal: opts.abortSignal }); + toolMessage.content = ResultFormatter.format(result); + } catch (error) { + toolMessage.content = `Error: MCP tool call failed with error message: ${error}`; + } } else { toolMessage.content = `Error: No session found for tool: ${toolName}`; }