ETOS-LLM-Studio icon indicating copy to clipboard operation
ETOS-LLM-Studio copied to clipboard

优化 MCP 工具调用结果的显示方式

Open Eric-Terminal opened this issue 10 months ago • 1 comments

背景

当前 ChatBubble.swift 中的 toolResultsDisclosureView 直接显示工具调用的原始返回结果。当 MCP 服务器返回大段 JSON 时,展开后会直接糊脸,用户体验不佳。

MCP 返回格式规律

根据 MCP 协议规范,所有工具调用结果都遵循统一结构:

{
  "content": [
    {
      "type": "text",
      "text": "实际内容"
    }
  ]
}

可以放心依赖 content[0].text 这个路径。

建议方案

方案 A:智能摘要

折叠状态只显示简短摘要:

private func summarizeToolResult(_ result: String) -> String {
    if let data = result.data(using: .utf8),
       let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        return "返回 \(json.count) 个字段"
    }
    let maxLength = 100
    if result.count > maxLength {
        return String(result.prefix(maxLength)) + "..."
    }
    return result
}

方案 B:格式化 JSON 显示

展开后用等宽字体显示格式化的 JSON:

@ViewBuilder
private func renderToolResult(_ result: String) -> some View {
    if let data = result.data(using: .utf8),
       let json = try? JSONSerialization.jsonObject(with: data),
       let prettyData = try? JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted, .sortedKeys]),
       let prettyString = String(data: prettyData, encoding: .utf8) {
        Text(prettyString)
            .font(.system(.caption2, design: .monospaced))
            .foregroundColor(.secondary)
    } else {
        Text(result)
            .font(.caption2)
            .foregroundColor(.secondary)
    }
}

方案 C:结合两者

  • 折叠状态:显示摘要
  • 展开状态:显示格式化 JSON(可选语法高亮)

此 Issue 由 Claude Opus 4.5 在 Apple Watch 上通过 ELS + MCP 工具自动提交 🤖⌚

Eric-Terminal avatar Feb 02 '26 06:02 Eric-Terminal

两个月了终于要落实了

Eric-Terminal avatar Apr 10 '26 13:04 Eric-Terminal