tool-catalog-cache.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import { createHash } from "node:crypto";
  2. import { isAbsolute, resolve } from "node:path";
  3. import { mcpConfigKey, resolveMcpToolVisibility } from "@zcode/contracts";
  4. import type {
  5. McpServerToolSnapshot,
  6. McpCatalogToolDescriptor,
  7. McpStdioServerConfig,
  8. McpToolCatalogLookupResult,
  9. McpToolCatalogPort,
  10. McpToolCatalogPublication,
  11. McpToolCatalogScope,
  12. McpToolDescriptor,
  13. } from "@zcode/contracts";
  14. const DEFAULT_CAPACITY = 32;
  15. const DEFAULT_MAX_ENTRY_BYTES = 2 * 1024 * 1024;
  16. const DEFAULT_MAX_TOTAL_BYTES = 16 * 1024 * 1024;
  17. const DEFAULT_TTL_MS = 30 * 60 * 1_000;
  18. interface CatalogEntry {
  19. bytes: number;
  20. publishedAt: number;
  21. tools: McpCatalogToolDescriptor[];
  22. }
  23. export interface InMemoryMcpToolCatalogOptions {
  24. capacity?: number;
  25. maxEntryBytes?: number;
  26. maxTotalBytes?: number;
  27. now?: () => number;
  28. platform?: NodeJS.Platform | string;
  29. ttlMs?: number;
  30. env?: Record<string, string | undefined>;
  31. }
  32. export function createInMemoryMcpToolCatalog(
  33. options: InMemoryMcpToolCatalogOptions = {},
  34. ): McpToolCatalogPort {
  35. const capacity = options.capacity ?? DEFAULT_CAPACITY;
  36. const maxEntryBytes = options.maxEntryBytes ?? DEFAULT_MAX_ENTRY_BYTES;
  37. const maxTotalBytes = options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES;
  38. const now = options.now ?? Date.now;
  39. const platform = options.platform ?? process.platform;
  40. const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
  41. const entries = new Map<string, CatalogEntry>();
  42. let totalBytes = 0;
  43. const remove = (key: string): void => {
  44. const existing = entries.get(key);
  45. if (!existing) return;
  46. totalBytes -= existing.bytes;
  47. entries.delete(key);
  48. };
  49. const lookup = (servers: readonly PreparedServer[]): McpToolCatalogLookupResult => {
  50. const byServer: Record<string, McpCatalogToolDescriptor[]> = {};
  51. let complete = true;
  52. for (const server of servers) {
  53. const key = server.cacheKey;
  54. const entry = key ? entries.get(key) : undefined;
  55. if (!key || !entry) {
  56. complete = false;
  57. continue;
  58. }
  59. if (now() - entry.publishedAt > ttlMs) {
  60. remove(key);
  61. complete = false;
  62. continue;
  63. }
  64. // Map 的 insertion order 就是 LRU 顺序;读取只更新 recency,不延长 publishedAt TTL。
  65. entries.delete(key);
  66. entries.set(key, entry);
  67. byServer[server.name] = cloneTools(entry.tools);
  68. }
  69. return { byServer, status: complete ? "complete" : "incomplete" };
  70. };
  71. const publish = (
  72. servers: readonly PreparedServer[],
  73. invalidated: ReadonlySet<string>,
  74. snapshot: Readonly<Record<string, McpServerToolSnapshot>>,
  75. published: Map<string, string>,
  76. ): void => {
  77. for (const server of servers) {
  78. const key = server.cacheKey;
  79. if (!key || invalidated.has(key)) continue;
  80. const row = snapshot[server.name];
  81. if (!row) continue;
  82. const status = row.status;
  83. if (
  84. status.status === "connecting" ||
  85. (status.status === "connected" && row.toolsVersion === undefined)
  86. )
  87. continue;
  88. const version = JSON.stringify([status.status, row.toolsVersion]);
  89. if (published.get(server.name) === version) continue;
  90. published.set(server.name, version);
  91. if (status && ["failed", "disabled", "disconnected", "untrusted"].includes(status.status)) {
  92. remove(key);
  93. continue;
  94. }
  95. if (status?.status !== "connected") continue;
  96. const tools = sanitizeTools(row.tools ?? []);
  97. const bytes = Buffer.byteLength(JSON.stringify(tools), "utf8");
  98. if (bytes > maxEntryBytes || bytes > maxTotalBytes) {
  99. remove(key);
  100. continue;
  101. }
  102. remove(key);
  103. entries.set(key, { bytes, publishedAt: now(), tools });
  104. totalBytes += bytes;
  105. while (entries.size > capacity || totalBytes > maxTotalBytes) {
  106. const oldest = entries.keys().next().value;
  107. if (typeof oldest !== "string") break;
  108. remove(oldest);
  109. }
  110. }
  111. };
  112. return {
  113. prepare(scope: McpToolCatalogScope): McpToolCatalogPublication {
  114. const servers = prepareServers(scope, platform, options.env ?? process.env);
  115. const result = lookup(servers);
  116. // 读取者不参与生产者任期;只有所有者撤销该 publication 才拒绝后续写入。
  117. const invalidated = new Set<string>();
  118. const published = new Map<string, string>();
  119. return {
  120. lookup: result,
  121. publish: (snapshot) => {
  122. for (const [name, { status }] of Object.entries(snapshot)) {
  123. if (["failed", "disabled", "disconnected", "untrusted"].includes(status.status))
  124. delete result.byServer[name];
  125. }
  126. publish(servers, invalidated, snapshot, published);
  127. },
  128. invalidate: (names) => {
  129. for (const server of servers) {
  130. const key = server.cacheKey;
  131. if (!key || (names && !names.includes(server.name))) continue;
  132. remove(key);
  133. invalidated.add(key);
  134. delete result.byServer[server.name];
  135. }
  136. },
  137. };
  138. },
  139. };
  140. }
  141. interface PreparedServer {
  142. cacheKey?: string;
  143. name: string;
  144. }
  145. function prepareServers(
  146. scope: McpToolCatalogScope,
  147. platform: NodeJS.Platform | string,
  148. executionEnv: Record<string, string | undefined>,
  149. ): PreparedServer[] {
  150. return Object.entries(scope.servers)
  151. .filter(([, config]) => config.enabled !== false)
  152. .sort(([left], [right]) => left.localeCompare(right))
  153. .map(([name, config]) => ({
  154. cacheKey:
  155. config.type === "stdio"
  156. ? createStdioCacheKey(name, config, scope, platform, executionEnv)
  157. : undefined,
  158. name,
  159. }));
  160. }
  161. function createStdioCacheKey(
  162. serverName: string,
  163. config: McpStdioServerConfig,
  164. scope: McpToolCatalogScope,
  165. platform: NodeJS.Platform | string,
  166. executionEnv: Record<string, string | undefined>,
  167. ): string {
  168. const workingDirectory = scope.workingDirectory?.trim() || process.cwd();
  169. const serverCwd = config.cwd ? resolve(workingDirectory, config.cwd) : workingDirectory;
  170. const workspaceKey = scope.workspaceIdentity?.trim() || workingDirectory;
  171. const command = normalizeCommand(config.command, serverCwd);
  172. const env = normalizeEnv(
  173. Object.fromEntries(
  174. Object.entries({ ...executionEnv, ...config.env }).filter(
  175. (entry): entry is [string, string] => entry[1] !== undefined,
  176. ),
  177. ),
  178. platform,
  179. );
  180. return createHash("sha256")
  181. .update(
  182. mcpConfigKey({
  183. config,
  184. args: config.args ?? [],
  185. clientCapabilities: "zcode-mcp-v1",
  186. command,
  187. cwd: serverCwd,
  188. env,
  189. isolation: config.isolation ?? "session",
  190. protocolVersion: config.protocolVersion ?? "auto",
  191. serverName,
  192. timeoutMs: config.timeoutMs,
  193. workspaceKey,
  194. }),
  195. )
  196. .digest("hex");
  197. }
  198. function normalizeCommand(command: string, cwd: string): string {
  199. return isAbsolute(command) || command.includes("/") || command.includes("\\")
  200. ? resolve(cwd, command)
  201. : command;
  202. }
  203. function normalizeEnv(
  204. env: McpStdioServerConfig["env"],
  205. platform: NodeJS.Platform | string,
  206. ): Array<[string, string]> {
  207. return Object.entries(env ?? {})
  208. .map(
  209. ([key, value]) => [platform === "win32" ? key.toUpperCase() : key, value] as [string, string],
  210. )
  211. .sort(([left], [right]) => left.localeCompare(right));
  212. }
  213. function sanitizeTools(descriptors: readonly McpToolDescriptor[]): McpCatalogToolDescriptor[] {
  214. return descriptors.map((descriptor) => ({
  215. serverName: descriptor.serverName,
  216. toolName: descriptor.toolName,
  217. ...(descriptor.name ? { name: descriptor.name } : {}),
  218. ...(descriptor.description ? { description: descriptor.description } : {}),
  219. inputSchema: cloneJson(descriptor.inputSchema),
  220. ...(descriptor.outputSchema ? { outputSchema: cloneJson(descriptor.outputSchema) } : {}),
  221. // 显式 false 也要保留,命中缓存时不能退回 server 级 alwaysLoad 默认值。
  222. ...(typeof descriptor.alwaysLoad === "boolean" ? { alwaysLoad: descriptor.alwaysLoad } : {}),
  223. ...(descriptor.searchHint ? { searchHint: descriptor.searchHint } : {}),
  224. // 缓存不保留 ui;只声明 ui.visibility 的工具要按同一规则落到 visibility,避免变成默认 model+app。
  225. ...(descriptor.visibility || descriptor.ui?.visibility
  226. ? { visibility: [...resolveMcpToolVisibility(descriptor)] }
  227. : {}),
  228. }));
  229. }
  230. function cloneTools(tools: readonly McpCatalogToolDescriptor[]): McpCatalogToolDescriptor[] {
  231. return tools.map((tool) => ({
  232. ...tool,
  233. inputSchema: cloneJson(tool.inputSchema),
  234. ...(tool.outputSchema ? { outputSchema: cloneJson(tool.outputSchema) } : {}),
  235. ...(tool.visibility ? { visibility: [...tool.visibility] } : {}),
  236. }));
  237. }
  238. function cloneJson<T>(value: T): T {
  239. return JSON.parse(JSON.stringify(value)) as T;
  240. }