Skip to content

Commit bbcc13f

Browse files
committed
Re-inject errors into the LLM
1 parent 9401982 commit bbcc13f

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

packages/mcp-client/src/McpClient.ts

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -181,8 +181,6 @@ export class McpClient {
181181
for (const toolCall of Object.values(finalToolCalls)) {
182182
const toolName = toolCall.function.name ?? "unknown";
183183
/// TODO(Fix upstream type so this is always a string)^
184-
const toolArgs = toolCall.function.arguments === "" ? {} : JSON.parse(toolCall.function.arguments);
185-
186184
const toolMessage: ChatCompletionInputMessageTool = {
187185
role: "tool",
188186
tool_call_id: toolCall.id,
@@ -193,11 +191,26 @@ export class McpClient {
193191
messages.push(toolMessage);
194192
return yield toolMessage;
195193
}
194+
let toolArgs: Record<string, unknown> = {};
195+
try {
196+
toolArgs = toolCall.function.arguments === "" ? {} : JSON.parse(toolCall.function.arguments);
197+
} catch (error) {
198+
if (error instanceof SyntaxError) {
199+
toolMessage.content = `Invalid JSON generated by the model: ${error.message}`;
200+
} else {
201+
throw error;
202+
}
203+
}
204+
196205
/// Get the appropriate session for this tool
197206
const client = this.clients.get(toolName);
198207
if (client) {
199-
const result = await client.callTool({ name: toolName, arguments: toolArgs, signal: opts.abortSignal });
200-
toolMessage.content = ResultFormatter.format(result);
208+
try {
209+
const result = await client.callTool({ name: toolName, arguments: toolArgs, signal: opts.abortSignal });
210+
toolMessage.content = ResultFormatter.format(result);
211+
} catch (error) {
212+
toolMessage.content = `Error: MCP tool call failed with error message: ${error}`;
213+
}
201214
} else {
202215
toolMessage.content = `Error: No session found for tool: ${toolName}`;
203216
}

0 commit comments

Comments
 (0)