index.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. #!/usr/bin/env node
  2. /**
  3. * wedo MCP —— 原型库多人协同操作入口(七工具)
  4. *
  5. * proto_init 新项目一键引导:目录骨架+_meta.js+门户+git初始化
  6. * proto_sync 感知远程更新(hub事件/git提交),可选 pull --rebase
  7. * proto_list 原型库目录树+收录清单元数据+git状态
  8. * proto_read 读原型(默认摘要150行,full=true全量)
  9. * proto_write 原子写入(tmp+rename,杜绝半截文件)
  10. * proto_publish 精确提交推送(commit自动规范[域/页]动作:摘要;push前远端检查;成功后广播hub)
  11. * proto_verify headless视口矩阵断言(publish质量门禁)
  12. *
  13. * 配置(env): 见 README.md;核心 PROTO_REPO(原型库绝对路径,必填)
  14. */
  15. import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
  16. import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
  17. import { z } from "zod";
  18. import { readFile, writeFile, readdir, stat, rename, mkdir } from "node:fs/promises";
  19. import { existsSync } from "node:fs";
  20. import { join, dirname, relative } from "node:path";
  21. import { git, gitTry, safePath, REPO, BRANCH } from "./lib/git.js";
  22. import { normalizeMsg } from "./lib/msg.js";
  23. import { hubNotify, startPolling, newsBanner } from "./lib/hub.js";
  24. import { verifyPage } from "./lib/verify.js";
  25. import { readMeta, metaLines } from "./lib/meta.js";
  26. import { initProject } from "./lib/init.js";
  27. const server = new McpServer({ name: "wedo", version: "2.0.0" });
  28. /* ── proto_init ── */
  29. server.tool("proto_init", "新项目原型库一键引导:目录骨架+_meta.js+门户index.html+git初始化(不覆盖已有库)", {
  30. repo_path: z.string().describe("原型库绝对路径(不存在则创建)"),
  31. project_name: z.string().describe("项目/系统名称"),
  32. repo_url: z.string().optional().describe("git远程仓库地址(可选,提供则自动配置remote)"),
  33. domains: z.array(z.string()).optional().describe("业务域目录名清单(默认 系统工作台/业务管理/数据中心/系统设置)"),
  34. live_url: z.string().optional().describe("线上系统访问地址(可选,登记进_meta.js)"),
  35. }, async (p) => {
  36. try { return { content: [{ type: "text", text: await initProject(p) }] }; }
  37. catch (e) { return { content: [{ type: "text", text: `❌ ${e.message}` }] }; }
  38. });
  39. /* ── proto_sync ── */
  40. server.tool("proto_sync", `感知原型库远程更新(hub事件优先,降级git提交比对)+本地脏文件;pull=true 时 pull --rebase 同步(本地脏则拒绝)`, { pull: z.boolean().optional() }, async ({ pull }) => {
  41. const fetchRes = gitTry(["fetch", "origin", "--quiet"]);
  42. if (!fetchRes.ok) return { content: [{ type: "text", text: `❌ fetch 失败(检查网络/凭据):\n${fetchRes.err}` }] };
  43. const news = gitTry(["log", "--pretty=format:%h %an %ad %s", "--date=format:%m-%d %H:%M", `HEAD..origin/${BRANCH}`]).out.trim();
  44. const dirty = gitTry(["status", "--porcelain"]).out.trim();
  45. let lines = [`仓库: ${REPO}`];
  46. lines.push(news ? `🔔 远程有 ${news.split("\n").length} 个新提交:\n${news}` : "✅ 远程无新提交(本地已是最新)");
  47. lines.push(dirty ? `⚠️ 本地未提交改动(将阻碍 rebase):\n${dirty}` : "✅ 本地工作区干净");
  48. if (pull) {
  49. if (news && dirty) lines.push("⏭️ 已跳过 pull:本地有未提交改动,请先处理(提交或暂存)再同步");
  50. else if (news) {
  51. const r = gitTry(["pull", "--rebase", "origin", BRANCH]);
  52. lines.push(r.ok ? "✅ 已同步(pull --rebase 完成,本地页面已更新,浏览器记得刷新)" : `❌ pull 失败:\n${r.err}`);
  53. } else lines.push("⏭️ 无需 pull");
  54. } else if (news) lines.push("💡 需要更新到本地时: proto_sync {pull:true}(本地干净才会执行)");
  55. return { content: [{ type: "text", text: lines.join("\n\n") }] };
  56. });
  57. /* ── proto_list ── */
  58. server.tool("proto_list", "列出原型库目录树(按业务域分组)、收录清单元数据(_meta.js)与 git 状态", {}, async () => {
  59. async function walk(dir, depth) {
  60. const out = [];
  61. for (const name of (await readdir(dir)).sort()) {
  62. if (name === ".git" || name.startsWith(".")) continue;
  63. const p = join(dir, name), s = await stat(p);
  64. if (s.isDirectory()) out.push(`${" ".repeat(depth)}📁 ${name}/`, ...(await walk(p, depth + 1)));
  65. else out.push(`${" ".repeat(depth)}📄 ${name} (${(s.size / 1024).toFixed(1)}KB)`);
  66. }
  67. return out;
  68. }
  69. const tree = (await walk(REPO, 0)).join("\n");
  70. let metaTxt;
  71. try { metaTxt = metaLines(await readMeta()); }
  72. catch { metaTxt = "\n\n(⚠️ _meta.js 缺失或解析失败,门户收录清单将不完整;可用 proto_init 模板补建)"; }
  73. const head = gitTry(["log", "-1", "--pretty=format:%h %an %ad %s", "--date=format:%m-%d %H:%M"]).out;
  74. const dirty = gitTry(["status", "--porcelain"]).out.trim();
  75. return { content: [{ type: "text", text: `原型库目录树:\n${tree}${metaTxt}\n\n当前 HEAD: ${head || "(空仓库)"}${dirty ? `\n⚠️ 未提交改动:\n${dirty}` : "\n✅ 工作区干净"}${newsBanner()}` }] };
  76. });
  77. /* ── proto_read ── */
  78. server.tool("proto_read", "读取原型文件;默认摘要模式(前150行+统计),full=true 返回全部内容", { path: z.string().describe("库内相对路径,如 财务管理/包额.html"), full: z.boolean().optional() }, async ({ path: p, full }) => {
  79. let abs; try { abs = safePath(p); } catch (e) { return { content: [{ type: "text", text: `❌ ${e.message}` }] }; }
  80. if (!existsSync(abs)) return { content: [{ type: "text", text: `❌ 文件不存在: ${p}(用 proto_list 查看目录)` }] };
  81. const content = await readFile(abs, "utf8");
  82. const lines = content.split("\n");
  83. if (full || lines.length <= 150) return { content: [{ type: "text", text: `📄 ${p} (共${lines.length}行,全量):\n\n${content}` }] };
  84. return { content: [{ type: "text", text: `📄 ${p} (共${lines.length}行,摘要前150行;需全文加 full:true):\n\n${lines.slice(0, 150).join("\n")}\n\n…(余 ${lines.length - 150} 行省略)` }] };
  85. });
  86. /* ── proto_write ── */
  87. server.tool("proto_write", "原子写入原型文件(临时文件+rename,杜绝半截文件);自动创建父目录;限 .html/.md/_meta.js/门户", { path: z.string(), content: z.string() }, async ({ path: p, content }) => {
  88. let abs; try { abs = safePath(p); } catch (e) { return { content: [{ type: "text", text: `❌ ${e.message}` }] }; }
  89. await mkdir(dirname(abs), { recursive: true });
  90. const tmp = abs + ".tmp_" + Date.now();
  91. await writeFile(tmp, content, "utf8");
  92. await rename(tmp, abs);
  93. return { content: [{ type: "text", text: `✅ 已原子写入 ${p} (${content.split("\n").length}行)。改动未提交,确认后用 proto_publish 推送。` }] };
  94. });
  95. /* ── proto_publish ── */
  96. server.tool("proto_publish",
  97. "精确提交并推送原型改动(显式文件清单,禁 add -A);commit 自动规范为 [业务域/页面] 动作: 摘要;push 前检查远端(落后拒绝);成功后广播 wedo-hub",
  98. { files: z.array(z.string()).describe("要提交的文件相对路径清单"), message: z.string().describe("改动摘要(自动包装为规范格式,已合规则原样)") },
  99. async ({ files, message }) => {
  100. if (!files || !files.length) return { content: [{ type: "text", text: "❌ files 不能为空(精确提交,拒绝全量提交)" }] };
  101. const absList = [];
  102. for (const f of files) {
  103. let abs; try { abs = safePath(f); } catch (e) { return { content: [{ type: "text", text: `❌ ${e.message}` }] }; }
  104. if (!existsSync(abs)) return { content: [{ type: "text", text: `❌ 文件不存在: ${f}` }] };
  105. absList.push(abs);
  106. }
  107. gitTry(["fetch", "origin", "--quiet"]);
  108. const ahead = gitTry(["log", "--oneline", `origin/${BRANCH}..HEAD`]).out.trim();
  109. const behind = gitTry(["log", "--oneline", `HEAD..origin/${BRANCH}`]).out.trim();
  110. if (behind && !ahead) return { content: [{ type: "text", text: `❌ 远程有新提交,请先 proto_sync {pull:true} 同步再提交:\n${behind}` }] };
  111. for (const abs of absList) git(["add", relative(REPO, abs)]);
  112. const staged = git(["status", "--porcelain"]).split("\n").filter(l => /^[AM]/.test(l));
  113. if (!staged.length) return { content: [{ type: "text", text: "❌ 没有可提交的改动(文件内容与上次提交相同?)" }] };
  114. const normMsg = normalizeMsg(message, staged);
  115. git(["commit", "-m", normMsg]);
  116. const push = gitTry(["push", "origin", BRANCH]);
  117. if (!push.ok) {
  118. gitTry(["reset", "--soft", "HEAD~1"]);
  119. return { content: [{ type: "text", text: `❌ push 失败(已回退本地提交,改动仍在暂存区):\n${push.err}` }] };
  120. }
  121. const head = git(["log", "-1", "--pretty=format:%h"]).trim();
  122. hubNotify(head, normMsg, staged.map(l => l.slice(3).trim()));
  123. return { content: [{ type: "text", text: `✅ 已提交并推送 ${head}: ${normMsg}\n提交文件:\n${staged.join("\n")}\n\n💡 建议:重要页面改动 publish 前先 proto_verify 跑视口矩阵断言。${newsBanner()}` }] };
  124. });
  125. /* ── proto_verify ── */
  126. server.tool("proto_verify",
  127. "对原型页面跑 headless 视口矩阵断言(默认 1280/1536/1920):横向零溢出(默认态+标注态)、页面有内容;publish 前的质量门禁",
  128. { path: z.string().describe("库内相对路径"), viewports: z.array(z.number()).optional().describe("自定义视口宽度列表") },
  129. async ({ path: p, viewports }) => {
  130. let abs; try { abs = safePath(p); } catch (e) { return { content: [{ type: "text", text: `❌ ${e.message}` }] }; }
  131. if (!existsSync(abs)) return { content: [{ type: "text", text: `❌ 文件不存在: ${p}` }] };
  132. try {
  133. const report = await verifyPage(abs, viewports && viewports.length ? viewports : [1280, 1536, 1920]);
  134. return { content: [{ type: "text", text: report }] };
  135. } catch (e) { return { content: [{ type: "text", text: `❌ ${e.message}` }] }; }
  136. });
  137. /* ── 启动 ── */
  138. startPolling(5 * 60_000);
  139. const transport = new StdioServerTransport();
  140. await server.connect(transport);
  141. console.error(`[wedo] ready v2.0.0 repo=${REPO} branch=${BRANCH} hub=${process.env.WEDO_HUB_URL ? "on" : "off"}(降级git)`);