MCP工具的字符串类型响应也被json序列化 #8043
-
📦 部署环境Docker 📦 部署模式服务端模式(lobe-chat-database 镜像) 📌 软件版本v1.90.2 💻 系统环境Other Linux 🌐 浏览器Chrome 🐛 问题描述当mcp工具以字符串类型做出响应时,lobe-chat依然会将响应值进行json转译。 📷 复现步骤
🚦 期望结果📝 补充信息OpenAI MCP调用示例(Function calling - OpenAI API): messages.push(completion.choices[0].message); // append model's function call message
messages.push({ // append result message
role: "tool",
tool_call_id: toolCall.id,
content: result.toString()
});
const completion2 = await openai.chat.completions.create({
model: "gpt-4.1",
messages,
tools,
store: true,
});
console.log(completion2.choices[0].message.content); Anthropic调用示例(Tool use with Claude - Anthropic) curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
...
"messages": [
{
"role": "user",
"content": "What is the weather like in San Francisco?"
},
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "<thinking>I need to use get_weather, and the user wants SF, which is likely San Francisco, CA.</thinking>"
},
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "get_weather",
"input": {
"location": "San Francisco, CA",
"unit": "celsius"
}
}
]
},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "15 degrees"
}
]
}
]
}' |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Thank you for raising an issue. We will investigate into the matter and get back to you as soon as possible. |
Beta Was this translation helpful? Give feedback.
-
Hi @wolf-joe! I'm Dosu and I’m helping the lobe-chat team. 你的问题是 MCP 工具返回字符串类型时,lobe-chat 依然对响应值进行了 JSON 序列化,导致接口返回内容变成了多重引号包裹的字符串,前端展示也不直观。 经过分析,根本原因在于 lobe-chat 服务端的 router 层(如 而 MCPService 的 如何实现你期望的效果: 只需修改 router 层的返回逻辑,判断 // 伪代码
if (typeof data === 'string') {
return data;
}
return JSON.stringify(data); 这样接口就能直接返回字符串类型响应,前端展示也会更直观,无需再做额外的反序列化处理。 目前没有配置项可以直接关闭这个行为,只能通过代码层面调整 router 的返回逻辑实现你的需求。 To reply, just mention my name @dosu. How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other |
Beta Was this translation helpful? Give feedback.
-
这个结构是 trpc 的接口规范, 另外从模型角度来说是否做一次 JSON stringify 都是能正常理解的,这个不存在问题。反而是如果针对字符串不做 JSON stringify ,有较大概率在返回信息的时候出现无法正常解析的问题。 另外你可以自己测一下官方的 mcp sdk ,我这里已经做得比较细致了,都去掉了第一次的 [ {type: "text" ,text:""}] 这个外层包裹的对象。 |
Beta Was this translation helpful? Give feedback.
[{"result":{"data":{"json":"\"100*200 = 20000.0\\n300*400 = 120000.0\""}}}]
这个结构是 trpc 的接口规范,
"\"100*200 = 20000.0\\n300*400 = 120000.0\""
这一串才是实际返回的值。另外从模型角度来说是否做一次 JSON stringify 都是能正常理解的,这个不存在问题。反而是如果针对字符串不做 JSON stringify ,有较大概率在返回信息的时候出现无法正常解析的问题。
另外你可以自己测一下官方的 mcp sdk ,我这里已经做得比较细致了,都去掉了第一次的 [ {type: "text" ,text:""}] 这个外层包裹的对象。