mcp-structured-content-projection.test.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // @vitest-environment node
  2. /**
  3. * MCP 结果投影:优先模型可见 content,空内容回退 structuredContent。
  4. *
  5. * 背景(2026-08-19 产品反馈):CUA 等成功结果携带 structuredContent: undefined
  6. * 的空键时,通用 bridge 仍追加 "Structured content:\n"(stringify(undefined)
  7. * 为空串),模型每次都看到一段无信息量的尾巴。
  8. *
  9. * producer 将模型需要的错误恢复详情写入 content,应用读取 structuredContent。
  10. */
  11. import { describe, expect, it } from "vitest";
  12. import { formatMcpToolResult, registerMcpTools } from "../src/mcp/index.js";
  13. import { createMcpAppProvidedToolEntry } from "../src/mcp/app-tools.js";
  14. import { createToolRegistry } from "../src/tool/registry.js";
  15. import type { McpPort } from "@zcode/shared";
  16. describe("formatMcpToolResult structuredContent projection", () => {
  17. // 最小 mock port(与 mcp-tool-bridge.test.ts 的 createMockMcpPort 同形);
  18. // 本用例组只消费 registerMcpTools 的 descriptor→entry 注册,port 不被调用。
  19. const createMockMcpPort = (): McpPort =>
  20. ({
  21. connectConfiguredServers: async () => ({ statuses: {}, tools: [] }),
  22. connectServer: async () => ({
  23. status: "connected",
  24. transport: "stdio",
  25. toolCount: 1,
  26. updatedAt: "now",
  27. }),
  28. disconnectServer: async () => undefined,
  29. status: async () => ({}),
  30. listTools: async () => [],
  31. callTool: async () => ({ content: [] }),
  32. close: async () => {},
  33. }) as McpPort;
  34. function structuredToolEntry(toolName = "structured", serverName = "modern") {
  35. const registry = createToolRegistry();
  36. registerMcpTools(registry, createMockMcpPort(), [
  37. {
  38. serverName,
  39. toolName,
  40. inputSchema: { type: "object" },
  41. },
  42. ]);
  43. return registry.get(`mcp__${serverName}__${toolName}`);
  44. }
  45. it("undefined 值不投影(CUA 成功结果空尾巴修复)", () => {
  46. const entry = structuredToolEntry();
  47. expect(
  48. entry?.formatModelContent?.({
  49. content: [{ type: "text", text: '{"pid":18067}' }],
  50. structuredContent: undefined,
  51. }),
  52. ).toBe('{"pid":18067}');
  53. });
  54. it("null / 空对象 / 空数组值同样不投影", () => {
  55. const entry = structuredToolEntry();
  56. for (const empty of [null, {}, []]) {
  57. expect(
  58. entry?.formatModelContent?.({
  59. content: [{ type: "text", text: "ok" }],
  60. structuredContent: empty,
  61. }),
  62. ).toBe("ok");
  63. }
  64. });
  65. it("错误结果同样优先 content", () => {
  66. expect(
  67. structuredToolEntry()?.formatModelContent?.({
  68. content: [{ type: "text", text: "blocked" }],
  69. isError: true,
  70. structuredContent: { action_sent: true, request_delivery_state: "possibly_sent" },
  71. }),
  72. ).toBe("MCP tool returned an error:\nblocked");
  73. });
  74. it.each([null, {}, [], false, 0, "result", [1, 2]])(
  75. "空 content 回退 JSON 值 %j",
  76. (structuredContent) => {
  77. expect(
  78. structuredToolEntry()?.formatModelContent?.({
  79. content: [{ type: "text", text: "" }],
  80. structuredContent,
  81. }),
  82. ).toBe(`Structured content:\n${JSON.stringify(structuredContent, null, 2)}`);
  83. },
  84. );
  85. describe.each(["tavily_search", "tavily_extract", "lookup_record"])("%s", (toolName) => {
  86. it.each(["tavily", "custom_search", "plugin_tavily_search"])(
  87. "同一份 JSON 只投影一次,支持 server 名 %s",
  88. (serverName) => {
  89. const structuredContent = {
  90. results: [{ url: "https://example.com", content: "唯一结果" }],
  91. response_time: 0.2,
  92. };
  93. const text = JSON.stringify(
  94. {
  95. response_time: 0.2,
  96. results: [{ content: "唯一结果", url: "https://example.com" }],
  97. },
  98. null,
  99. 2,
  100. );
  101. const output = { content: [{ type: "text", text }], structuredContent };
  102. const original = structuredClone(output);
  103. expect(structuredToolEntry(toolName, serverName)?.formatModelContent?.(output)).toBe(text);
  104. expect(output).toEqual(original);
  105. },
  106. );
  107. it.each([
  108. ["非 JSON", { results: ["完整结果"] }],
  109. ['{"results":["部分结果"]}', { results: ["完整结果"] }],
  110. ['{"results":["完整结果"]}', { results: ["完整结果"], failed_results: ["失败"] }],
  111. ["[2,1]", [1, 2]],
  112. ['"1"', 1],
  113. ])("优先 content,无需解析或比较 JSON %s", (text, structuredContent) => {
  114. const result = structuredToolEntry(toolName)?.formatModelContent?.({
  115. content: [{ type: "text", text }],
  116. structuredContent,
  117. });
  118. expect(result).toBe(text);
  119. });
  120. it.each([[[1, "two"]], ["result"], [false], [0]])("支持 JSON 值 %j", (structuredContent) => {
  121. const text = JSON.stringify(structuredContent);
  122. expect(
  123. structuredToolEntry(toolName)?.formatModelContent?.({
  124. content: [{ type: "text", text }],
  125. structuredContent,
  126. }),
  127. ).toBe(text);
  128. });
  129. it("保留额外说明、图片和资源", () => {
  130. const structuredContent = { results: ["唯一结果"] };
  131. const text = JSON.stringify(structuredContent);
  132. const result = structuredToolEntry(toolName)?.formatModelContent?.({
  133. content: [
  134. { type: "text", text: "结果说明" },
  135. { type: "image", data: "aGVsbG8=", mimeType: "image/png" },
  136. { type: "text", text },
  137. { type: "resource", resource: { uri: "https://example.com", text: "资源" } },
  138. ],
  139. structuredContent,
  140. });
  141. expect(result).toEqual([
  142. { type: "text", text: "结果说明" },
  143. expect.objectContaining({ type: "image" }),
  144. { type: "text", text },
  145. { type: "text", text: expect.stringContaining("资源") },
  146. ]);
  147. });
  148. it("保留错误标志与只有 structuredContent 的结果", () => {
  149. const structuredContent = { error: "quota" };
  150. const text = JSON.stringify(structuredContent);
  151. const entry = structuredToolEntry(toolName);
  152. expect(
  153. entry?.formatModelContent?.({
  154. content: [{ type: "text", text }],
  155. structuredContent,
  156. isError: true,
  157. }),
  158. ).toBe(`MCP tool returned an error:\n${text}`);
  159. expect(entry?.formatModelContent?.({ content: [], structuredContent })).toBe(
  160. `Structured content:\n${JSON.stringify(structuredContent, null, 2)}`,
  161. );
  162. expect(entry?.formatModelContent?.({ content: [{ type: "text", text }] })).toBe(text);
  163. });
  164. });
  165. it("公共投影优先模型可见 content", () => {
  166. const structuredContent = { records: [{ id: 1 }] };
  167. const text = JSON.stringify(structuredContent);
  168. expect(formatMcpToolResult({ content: [{ type: "text", text }], structuredContent })).toBe(
  169. text,
  170. );
  171. });
  172. it("MCP Apps app-provided 工具复用公共选择规则", () => {
  173. const structuredContent = { records: [{ id: 1 }] };
  174. const text = JSON.stringify(structuredContent);
  175. const entry = createMcpAppProvidedToolEntry(
  176. {
  177. modelName: "app__records__lookup",
  178. serverName: "records",
  179. pluginId: "records",
  180. scopeId: "scope",
  181. generation: 1,
  182. toolName: "lookup",
  183. inputSchema: { type: "object" },
  184. },
  185. async () => ({ content: [] }),
  186. );
  187. expect(
  188. entry.formatModelContent?.({ content: [{ type: "text", text }], structuredContent }),
  189. ).toBe(text);
  190. });
  191. });