telemetry.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import { Buffer } from "node:buffer";
  2. import { createHmac, randomUUID } from "node:crypto";
  3. import type { ZCodeMcpTelemetryEvent } from "@zcode/shared";
  4. import {
  5. createMcpResourceTelemetry,
  6. type McpResourceTelemetryOptions,
  7. } from "./resource-telemetry.js";
  8. const BUILTIN_MCP_ID_PREFIX = "builtin:";
  9. const BUILTIN_NODE_REPL_SERVER_NAME = "node_repl";
  10. const MCP_ID_SAFE_CHARACTER_PATTERN = /^[A-Za-z0-9._~-]$/;
  11. const PLUGIN_MCP_NAMESPACE_PREFIX = "plugin:";
  12. export type McpTelemetryEvent = ZCodeMcpTelemetryEvent;
  13. export type McpTelemetrySource = Extract<
  14. ZCodeMcpTelemetryEvent,
  15. { kind: "process_start" }
  16. >["mcpSource"];
  17. export type McpTelemetryIsolation = Extract<
  18. ZCodeMcpTelemetryEvent,
  19. { kind: "process_start" }
  20. >["mcpIsolation"];
  21. export interface McpProcessTelemetryIdentity {
  22. mcpId: string;
  23. mcpInstanceId: string;
  24. }
  25. /**
  26. * 资源管理器用的 MCP 子进程视图:只回 pid 与归属,不含任何采样值。
  27. * 这里保留明文 serverName / pluginName——只在本机 host ↔ CLI 之间流转,
  28. * 不出本机,无需脱敏;Host 用它把 ps 进程树上的 pid 归到具体插件。
  29. */
  30. export interface McpTrackedProcess {
  31. pid: number;
  32. serverName: string;
  33. mcpSource: McpTelemetrySource;
  34. /** `plugin:<name>:<key>` 命名空间里的插件名;builtin host MCP(node_repl)由调用方按官方插件表补齐 */
  35. pluginName?: string;
  36. }
  37. export interface McpTelemetryTracker {
  38. acquireOwner(input: { connectionId: string; ownerId: string; sessionId?: string }): void;
  39. recordSessionStartup(input: {
  40. configuredCount: number;
  41. connectedCount: number;
  42. failedCount: number;
  43. processCount: number;
  44. sessionId: string;
  45. }): void;
  46. recordProcessCrashed(input: {
  47. connectionId: string;
  48. exitCode: number | null;
  49. signal: string | null;
  50. }): void;
  51. recordProcessClosed(input: { connectionId: string }): void;
  52. recordProcessStarted(input: {
  53. connectionId: string;
  54. pid: number;
  55. }): McpProcessTelemetryIdentity | undefined;
  56. releaseOwner(input: { connectionId: string; ownerId: string }): void;
  57. registerConnection(input: {
  58. connectionId: string;
  59. isolation: McpTelemetryIsolation;
  60. serverName: string;
  61. source?: McpTelemetrySource;
  62. }): void;
  63. unregisterConnection(input: { connectionId: string }): void;
  64. /** 当前仍有存活进程记录的 MCP 连接(纯内存,无 I/O) */
  65. listProcesses(): McpTrackedProcess[];
  66. sampleNow(): Promise<void>;
  67. start(): void;
  68. stop(): void;
  69. }
  70. export interface CreateMcpTelemetryTrackerOptions {
  71. arch?: ZCodeMcpTelemetryEvent["arch"];
  72. idSalt: string;
  73. now?: () => number;
  74. onEvent(event: McpTelemetryEvent): void;
  75. platform?: ZCodeMcpTelemetryEvent["platform"];
  76. randomId?: () => string;
  77. onResourceSamples?: McpResourceTelemetryOptions["onResourceSamples"];
  78. processProbe?: McpResourceTelemetryOptions["processProbe"];
  79. logicalCpuCount?: number;
  80. totalMemoryGb?: number;
  81. timer?: McpResourceTelemetryOptions["timer"];
  82. }
  83. interface TrackedConnection {
  84. connectionId: string;
  85. isolation: McpTelemetryIsolation;
  86. mcpId: string;
  87. mcpSource: McpTelemetrySource;
  88. serverName: string;
  89. owners: Map<string, string | undefined>;
  90. process?: {
  91. instanceId: string;
  92. pid: number;
  93. startedAt: number;
  94. };
  95. unownedAt?: number;
  96. }
  97. export function createMcpTelemetryTracker(
  98. options: CreateMcpTelemetryTrackerOptions,
  99. ): McpTelemetryTracker {
  100. const arch = options.arch ?? (process.arch as ZCodeMcpTelemetryEvent["arch"]);
  101. const now = options.now ?? Date.now;
  102. const platform = options.platform ?? (process.platform as ZCodeMcpTelemetryEvent["platform"]);
  103. const randomId = options.randomId ?? randomUUID;
  104. const connections = new Map<string, TrackedConnection>();
  105. const emit = (event: McpTelemetryEvent): void => {
  106. try {
  107. options.onEvent(event);
  108. } catch {
  109. // 遥测为旁路,下游通知或 IPC 关闭不得改变 MCP 连接、回收或 crash 处理。
  110. }
  111. };
  112. const resourceTelemetry = createMcpResourceTelemetry({
  113. ...options,
  114. arch,
  115. platform,
  116. now,
  117. getProcesses: () =>
  118. [...connections.values()].flatMap((connection) => {
  119. const trackedProcess = connection.process;
  120. if (!trackedProcess) return [];
  121. return [
  122. {
  123. ...trackedProcess,
  124. mcpId: connection.mcpId,
  125. isCurrent: () =>
  126. connections.get(connection.connectionId) === connection &&
  127. connection.process === trackedProcess,
  128. observed(samples, sampledAt, memoryScope) {
  129. if (!samples) {
  130. if (connection.owners.size === 0) {
  131. connection.process = undefined;
  132. connections.delete(connection.connectionId);
  133. }
  134. return;
  135. }
  136. const sessionIds = new Set(
  137. [...connection.owners.values()].filter((id) => id !== undefined),
  138. );
  139. const unownedMs =
  140. connection.owners.size === 0 && connection.unownedAt !== undefined
  141. ? Math.max(0, sampledAt - connection.unownedAt)
  142. : 0;
  143. // 保留 tracker 内部孤儿观测口径;bootstrap 不再把旧 memory 事实发上协议。
  144. emit({
  145. arch,
  146. kind: "memory",
  147. mcpId: connection.mcpId,
  148. mcpInstanceId: trackedProcess.instanceId,
  149. mcpIsolation: connection.isolation,
  150. mcpSource: connection.mcpSource,
  151. platform,
  152. occurredAt: sampledAt,
  153. memoryKb: samples.reduce((total, sample) => total + sample.rssKb, 0),
  154. memoryScope,
  155. orphanSuspected: connection.owners.size === 0 && unownedMs > 60_000,
  156. ownerSessionCount: sessionIds.size,
  157. unownedSeconds: unownedMs / 1_000,
  158. });
  159. },
  160. },
  161. ];
  162. }),
  163. });
  164. return {
  165. acquireOwner(input) {
  166. const connection = connections.get(input.connectionId);
  167. if (!connection) return;
  168. connection.owners.set(input.ownerId, input.sessionId);
  169. connection.unownedAt = undefined;
  170. },
  171. recordProcessCrashed(input) {
  172. const connection = connections.get(input.connectionId);
  173. const trackedProcess = connection?.process;
  174. if (!connection || !trackedProcess) return;
  175. connection.process = undefined;
  176. const occurredAt = now();
  177. const sessionIds = new Set(
  178. [...connection.owners.values()].filter(
  179. (sessionId): sessionId is string => sessionId !== undefined,
  180. ),
  181. );
  182. emit({
  183. affectedSessionCount: sessionIds.size,
  184. arch,
  185. exitCode: input.exitCode,
  186. kind: "process_crash",
  187. mcpId: connection.mcpId,
  188. mcpInstanceId: trackedProcess.instanceId,
  189. mcpIsolation: connection.isolation,
  190. mcpSource: connection.mcpSource,
  191. occurredAt,
  192. platform,
  193. signal: input.signal,
  194. uptimeMs: Math.max(0, occurredAt - trackedProcess.startedAt),
  195. });
  196. },
  197. recordProcessClosed(input) {
  198. const connection = connections.get(input.connectionId);
  199. if (!connection) return;
  200. connection.process = undefined;
  201. if (connection.owners.size === 0) connections.delete(input.connectionId);
  202. },
  203. recordProcessStarted(input) {
  204. const connection = connections.get(input.connectionId);
  205. if (!connection || !Number.isInteger(input.pid) || input.pid <= 0) return undefined;
  206. const mcpInstanceId = randomId();
  207. const occurredAt = now();
  208. connection.process = {
  209. instanceId: mcpInstanceId,
  210. pid: input.pid,
  211. startedAt: occurredAt,
  212. };
  213. if (connection.owners.size === 0) connection.unownedAt ??= occurredAt;
  214. emit({
  215. arch,
  216. kind: "process_start",
  217. mcpId: connection.mcpId,
  218. mcpInstanceId,
  219. mcpIsolation: connection.isolation,
  220. mcpSource: connection.mcpSource,
  221. occurredAt,
  222. platform,
  223. });
  224. return { mcpId: connection.mcpId, mcpInstanceId };
  225. },
  226. recordSessionStartup(input) {
  227. emit({
  228. arch,
  229. configuredCount: input.configuredCount,
  230. connectedCount: input.connectedCount,
  231. failedCount: input.failedCount,
  232. kind: "session_startup",
  233. occurredAt: now(),
  234. platform,
  235. processCount: input.processCount,
  236. sessionId: input.sessionId,
  237. });
  238. },
  239. releaseOwner(input) {
  240. const connection = connections.get(input.connectionId);
  241. if (!connection || !connection.owners.delete(input.ownerId)) return;
  242. if (connection.owners.size !== 0) return;
  243. connection.unownedAt = now();
  244. // process crash 后最后一个 owner 释放时,pool entry 仍会在 idle grace 内存活。
  245. // 此处提前删除 registration 会让同一 workspace entry 被复用后的新进程永久失去遥测。
  246. // registration 的终态由 pool closeEntry 显式 unregister,owner 释放只记录无主时间。
  247. },
  248. registerConnection(input) {
  249. const mcpSource = input.source ?? resolveMcpSource(input.serverName);
  250. connections.set(input.connectionId, {
  251. connectionId: input.connectionId,
  252. isolation: input.isolation,
  253. mcpId: resolveMcpId(input.serverName, mcpSource, options.idSalt),
  254. mcpSource,
  255. serverName: input.serverName,
  256. owners: new Map(),
  257. });
  258. },
  259. unregisterConnection(input) {
  260. const connection = connections.get(input.connectionId);
  261. if (!connection) return;
  262. // pool entry 已进入终态,残留 lease 不能继续被视为 owner;若进程树回收失败则保留
  263. // process 供后续采样标记 orphan,确认进程关闭或 OS 不再可见后再删除 registration。
  264. connection.owners.clear();
  265. connection.unownedAt ??= now();
  266. if (!connection.process) connections.delete(input.connectionId);
  267. },
  268. listProcesses() {
  269. const processes: McpTrackedProcess[] = [];
  270. for (const connection of connections.values()) {
  271. if (!connection.process) continue;
  272. const pluginName = resolvePluginName(connection.serverName);
  273. processes.push({
  274. pid: connection.process.pid,
  275. serverName: connection.serverName,
  276. mcpSource: connection.mcpSource,
  277. ...(pluginName ? { pluginName } : {}),
  278. });
  279. }
  280. return processes;
  281. },
  282. sampleNow: resourceTelemetry.sampleNow,
  283. start: resourceTelemetry.start,
  284. stop: resourceTelemetry.stop,
  285. };
  286. }
  287. /** `plugin:<name>:<key>` → `<name>`;非插件命名空间返回 undefined */
  288. export function resolvePluginName(serverName: string): string | undefined {
  289. if (!serverName.startsWith(PLUGIN_MCP_NAMESPACE_PREFIX)) return undefined;
  290. const name = serverName.slice(PLUGIN_MCP_NAMESPACE_PREFIX.length).split(":")[0]?.trim();
  291. return name ? name : undefined;
  292. }
  293. function resolveMcpSource(serverName: string): McpTelemetrySource {
  294. if (serverName === BUILTIN_NODE_REPL_SERVER_NAME) return "builtin";
  295. return serverName.startsWith(PLUGIN_MCP_NAMESPACE_PREFIX) ? "plugin" : "custom";
  296. }
  297. function resolveMcpId(serverName: string, source: McpTelemetrySource, idSalt: string): string {
  298. if (source === "builtin") {
  299. const publicName = serverName.startsWith(PLUGIN_MCP_NAMESPACE_PREFIX)
  300. ? serverName.slice(PLUGIN_MCP_NAMESPACE_PREFIX.length)
  301. : serverName;
  302. return `${BUILTIN_MCP_ID_PREFIX}${publicName.split(":").map(encodeMcpIdSegment).join(":")}`;
  303. }
  304. const digest = createHmac("sha256", idSalt).update(serverName).digest("hex").slice(0, 12);
  305. return `${source}:${digest}`;
  306. }
  307. function encodeMcpIdSegment(value: string): string {
  308. // 原因:encodeURIComponent 遇到孤立 surrogate 会抛 URIError,遥测编码不能反向阻断 MCP 启动。
  309. // Buffer 的 UTF-8 编码会把畸形序列替换为 U+FFFD,再逐字节转义成协议允许的稳定 `%HH`。
  310. let encoded = "";
  311. for (const byte of Buffer.from(value, "utf8")) {
  312. const character = String.fromCharCode(byte);
  313. encoded += MCP_ID_SAFE_CHARACTER_PATTERN.test(character)
  314. ? character
  315. : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
  316. }
  317. return encoded;
  318. }