Skip to content

Commit 221c64e

Browse files
fix: 正确处理工具调用结果的 JSON 解析
Co-authored-by: aider (vertex_ai/gemini-2.5-pro) <aider@aider.chat>
1 parent 93641d6 commit 221c64e

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

packages/mcp-server/src/gemini-client.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -77,19 +77,26 @@ export class GeminiApiClient {
7777

7878
if (msg.role === 'tool') {
7979
const functionName = this.parseFunctionNameFromId(msg.tool_call_id || '');
80+
let responsePayload: object;
81+
82+
try {
83+
// 尝试将工具返回的内容解析为 JSON 对象
84+
responsePayload = JSON.parse(msg.content as string);
85+
} catch (e) {
86+
// 如果解析失败,说明工具返回的可能是一个简单的字符串
87+
// 在这种情况下,我们遵循 Gemini API 的惯例,将其包装在 { "output": "..." } 中
88+
responsePayload = { output: msg.content };
89+
}
90+
8091
return {
8192
role: 'user', // Gemini 使用 'user' role 来承载 functionResponse
8293
parts: [
8394
{
8495
functionResponse: {
8596
id: msg.tool_call_id,
8697
name: functionName,
87-
response: {
88-
// Gemini 期望 response 是一个对象,我们把工具的输出放在这里
89-
// 假设工具输出是一个 JSON 字符串,我们解析它
90-
// 如果不是,就直接作为字符串
91-
output: msg.content,
92-
},
98+
// 直接将解析后的对象或包装后的对象作为 response 的值
99+
response: responsePayload,
93100
},
94101
},
95102
],

0 commit comments

Comments
 (0)