plugin-mcp-skill.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. // 插件 MCP skill 生命周期 e2e helper。
  2. // 仅在 conversation-session/manual-review/pending/conversation-session-plugin-mcp-skill-*.test.ts
  3. // 这几个 spec 里被使用;wdio 启动前在 seedE2EStartupState 阶段会把对应的
  4. // plugin 安装记录落到 <E2E_HOME>/.zcode/cli/plugins/,并 patch cli config。
  5. import { readFile } from "node:fs/promises";
  6. import { dirname, join, resolve } from "node:path";
  7. import { fileURLToPath } from "node:url";
  8. // 修复原因:Windows 上 URL.pathname 是 `/C:/...`,resolve 后变成 `C:\C:\...`,
  9. // 与 wdio 写入工作区配置的真实插件路径不一致;必须用 fileURLToPath 转本机路径。
  10. const FIXTURES_ROOT = resolve(
  11. dirname(fileURLToPath(import.meta.url)),
  12. "..",
  13. "fixtures",
  14. "plugin-mcp-skill",
  15. );
  16. const PLUGIN_ROOT = join(FIXTURES_ROOT, "e2e-plugin-mcp-ping");
  17. export const PLUGIN_MCP_FIXTURE_DIR = FIXTURES_ROOT;
  18. export const PLUGIN_MCP_PLUGIN_ROOT = PLUGIN_ROOT;
  19. export const PLUGIN_MCP_PLUGIN_ID = "e2e-plugin-mcp-ping@e2e-fixture";
  20. // Bugfix: agent adapter 注入 MCP 工具时把 namespaced server 名(`plugin:<name>:<server>`)
  21. // 重写成符合模型 API 工具名约束的 `mcp__plugin_<name>_<server>__<tool>`,实际发给模型的就是这个名。
  22. // 见 `apps/zcode-cli/packages/adapters/src/mcp/descriptor.ts` 与
  23. // `apps/zcode-cli/packages/adapters/src/mcp/index.ts:normalizeMcpToolDescriptor`。
  24. export const PLUGIN_MCP_TOOL_NAME = "mcp__plugin_e2e-plugin-mcp-ping_ping__ping";
  25. export const PLUGIN_MCP_MARKER_PREFIX = "E2E_PLUGIN_MCP_PING";
  26. const TITLE_REQUEST_MARKER = "Generate a concise title";
  27. /**
  28. * 读取 upstream replay 捕获的请求记录,遍历 tools 数组,断言指定工具名是否注册。
  29. * 强证据:只有当 plugin MCP server 真正被 listTools 时,agent 才会把
  30. * `mcp__plugin_e2e-plugin-mcp-ping_ping__ping` 加进 `body.tools[]` 一并发送给模型。
  31. */
  32. export function captureArtifactAdvertisesToolName(requestJson: unknown, toolName: string): boolean {
  33. if (!requestJson || typeof requestJson !== "object") return false;
  34. const tools = (requestJson as { tools?: unknown }).tools;
  35. if (!Array.isArray(tools)) return false;
  36. return tools.some(
  37. (tool) =>
  38. tool !== null && typeof tool === "object" && (tool as { name?: unknown }).name === toolName,
  39. );
  40. }
  41. /**
  42. * 找到包含 marker 的最后一条 capture 请求,导出 requestJson 给调用方继续断言。
  43. * 比 `countUpstreamRequests` 更进一步:返回 record,方便读 tools 数组。
  44. */
  45. export async function findUpstreamRequestContaining(
  46. marker: string,
  47. timeoutMs = 30000,
  48. options?: { advertisedToolName?: string },
  49. ): Promise<{ method: string; path: string; requestJson: unknown } | null> {
  50. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  51. if (!capturePath) return null;
  52. const deadline = Date.now() + timeoutMs;
  53. let latest: { method: string; path: string; requestJson: unknown } | null = null;
  54. while (Date.now() < deadline) {
  55. const artifact = await readCaptureArtifact(capturePath);
  56. if (artifact) {
  57. for (const record of artifact.records) {
  58. if (
  59. containsText(record.requestJson, marker) &&
  60. !containsText(record.requestJson, TITLE_REQUEST_MARKER) &&
  61. (!options?.advertisedToolName ||
  62. captureArtifactAdvertisesToolName(record.requestJson, options.advertisedToolName))
  63. ) {
  64. latest = {
  65. method: record.method,
  66. path: record.path,
  67. requestJson: record.requestJson,
  68. };
  69. }
  70. }
  71. }
  72. // 修复原因:同一首发 prompt 会并发触发主请求与标题请求,两者都含 marker,
  73. // 但只有主请求携带 MCP tools 与插件运行时内容。标题请求(system 为 Generate a concise title)
  74. // 一律排除,必须等到主请求落盘,否则可能先取到标题请求导致后续断言读不到插件内容。
  75. if (latest) return latest;
  76. await sleep(250);
  77. }
  78. return latest;
  79. }
  80. async function readCaptureArtifact(capturePath: string): Promise<{
  81. records: Array<{ method: string; path: string; requestJson: unknown }>;
  82. } | null> {
  83. try {
  84. const raw = await readFile(capturePath, "utf-8");
  85. const parsed = JSON.parse(raw) as {
  86. records?: Array<{ method: string; path: string; requestJson?: unknown }>;
  87. };
  88. if (!parsed || !Array.isArray(parsed.records)) return null;
  89. return {
  90. records: parsed.records.map((record) => ({
  91. method: record.method,
  92. path: record.path,
  93. requestJson: record.requestJson ?? null,
  94. })),
  95. };
  96. } catch (error) {
  97. if (
  98. typeof error === "object" &&
  99. error !== null &&
  100. "code" in error &&
  101. (error as { code?: string }).code === "ENOENT"
  102. ) {
  103. return null;
  104. }
  105. throw error;
  106. }
  107. }
  108. function containsText(value: unknown, expected: string): boolean {
  109. if (typeof value === "string") return value.includes(expected);
  110. if (Array.isArray(value)) return value.some((item) => containsText(item, expected));
  111. if (!value || typeof value !== "object") return false;
  112. return Object.values(value).some((child) => containsText(child, expected));
  113. }
  114. function sleep(ms: number): Promise<void> {
  115. return new Promise((resolveSleep) => setTimeout(resolveSleep, ms));
  116. }