zcodeAgentService.mcpTelemetry.test.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import type { ZCodeMcpTelemetryEvent, ZCodeMcpResourceSample } from "@zcode/shared";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { createZCodeAgentService } from "../src/zcode-agent/zcodeAgentService.js";
  7. const MCP_TELEMETRY_FAKE_AGENT = `
  8. let buffer = "";
  9. function send(value) { process.stdout.write(JSON.stringify(value) + "\\n"); }
  10. process.stdin.on("data", (chunk) => {
  11. buffer += chunk.toString("utf8");
  12. let newline;
  13. while ((newline = buffer.indexOf("\\n")) >= 0) {
  14. const line = buffer.slice(0, newline);
  15. buffer = buffer.slice(newline + 1);
  16. if (!line.trim()) continue;
  17. const message = JSON.parse(line);
  18. if (message.method !== "session/list" || message.id === undefined) continue;
  19. send({ id: message.id, result: { sessions: [] } });
  20. const uiResult = { sessionId: "background", toolCallId: "open", serverName: "plugin:editor:editor", ui: { pluginId: "editor@example", resourceUri: "ui://editor" } };
  21. send({ method: "v4/plugin-ui/tool-result", params: { ...uiResult, extra: true } });
  22. send({ method: "v4/plugin-ui/tool-result", params: { ...uiResult, ui: { ...uiResult.ui, isError: true } } });
  23. send({ method: "v4/plugin-ui/tool-result", params: uiResult });
  24. const event = {
  25. kind: "memory",
  26. arch: "x64",
  27. platform: "linux",
  28. occurredAt: 1000,
  29. mcpId: "custom:123456789abc",
  30. mcpInstanceId: "mcp-instance-1",
  31. mcpIsolation: "session",
  32. mcpSource: "custom",
  33. memoryKb: 65536,
  34. memoryScope: "process_tree",
  35. ownerSessionCount: 0,
  36. unownedSeconds: 61,
  37. orphanSuspected: true,
  38. };
  39. send({ method: "process/mcpTelemetry", params: { ...event, mcpServerName: "private" } });
  40. send({ method: "process/mcpTelemetry", params: event });
  41. const samples = [{ mcpId: "builtin:node_repl", instanceToken: "cli-instance-01", sampledAt: 300000,
  42. intervalMs: 300000, processCount: 2, rssKbTotal: 120000, rssKbMaxProcess: 80000,
  43. cpuTimeMsDelta: 30000, uptimeMinutes: 5, platform: "linux", arch: "x64", logicalCpuCount: 8, totalMemoryGb: 32 }];
  44. send({ method: "process/mcpResourceSamples", params: [{ ...samples[0], pid: 123 }] });
  45. send({ method: "process/mcpResourceSamples", params: samples });
  46. }
  47. });
  48. `;
  49. describe("ZCodeAgentService MCP telemetry", () => {
  50. const tempDirs: string[] = [];
  51. afterEach(() => {
  52. for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
  53. });
  54. it("strictly validates MCP telemetry before publishing the process-level event", async () => {
  55. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-mcp-telemetry-"));
  56. tempDirs.push(workspacePath);
  57. const scriptPath = join(workspacePath, "mcp-telemetry-agent.cjs");
  58. writeFileSync(scriptPath, MCP_TELEMETRY_FAKE_AGENT);
  59. const service = createZCodeAgentService({
  60. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  61. });
  62. const uiResults: unknown[] = [];
  63. const uiSubscription = service.onDynamicPluginUiToolResult()((value) => uiResults.push(value));
  64. const events: ZCodeMcpTelemetryEvent[] = [];
  65. const subscription = service.onDynamicMcpTelemetry()((event) => events.push(event));
  66. try {
  67. await service.listSessions({ workspacePath });
  68. await new Promise((resolve) => setTimeout(resolve, 20));
  69. await expect.poll(() => uiResults.length).toBe(1);
  70. expect(uiResults).toEqual([
  71. {
  72. workspacePath,
  73. sessionId: "background",
  74. toolCallId: "open",
  75. serverName: "plugin:editor:editor",
  76. ui: { pluginId: "editor@example", resourceUri: "ui://editor" },
  77. },
  78. ]);
  79. expect(events).toEqual([
  80. {
  81. arch: "x64",
  82. kind: "memory",
  83. mcpId: "custom:123456789abc",
  84. mcpInstanceId: "mcp-instance-1",
  85. mcpIsolation: "session",
  86. mcpSource: "custom",
  87. memoryKb: 65_536,
  88. memoryScope: "process_tree",
  89. occurredAt: 1_000,
  90. orphanSuspected: true,
  91. ownerSessionCount: 0,
  92. platform: "linux",
  93. unownedSeconds: 61,
  94. },
  95. ]);
  96. } finally {
  97. subscription.dispose();
  98. uiSubscription.dispose();
  99. await service.disposeAllAndWait();
  100. }
  101. });
  102. it("通过真实 stdio 解析资源数组,丢弃含 PID 的通知", async () => {
  103. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-mcp-resources-"));
  104. tempDirs.push(workspacePath);
  105. const scriptPath = join(workspacePath, "agent.cjs");
  106. writeFileSync(scriptPath, MCP_TELEMETRY_FAKE_AGENT);
  107. const service = createZCodeAgentService({
  108. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  109. });
  110. const batches: ZCodeMcpResourceSample[][] = [];
  111. const subscription = service.onDynamicMcpResourceSamples()((samples) => batches.push(samples));
  112. try {
  113. await service.listSessions({ workspacePath });
  114. await expect.poll(() => batches.length).toBe(1);
  115. expect(batches[0]).toEqual([
  116. expect.objectContaining({
  117. mcpId: "builtin:node_repl",
  118. rssKbTotal: 120000,
  119. cpuTimeMsDelta: 30000,
  120. }),
  121. ]);
  122. } finally {
  123. subscription.dispose();
  124. await service.disposeAllAndWait();
  125. }
  126. });
  127. });