| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150 |
- #!/usr/bin/env node
- /**
- * wedo MCP —— 原型库多人协同操作入口(七工具)
- *
- * proto_init 新项目一键引导:目录骨架+_meta.js+门户+git初始化
- * proto_sync 感知远程更新(hub事件/git提交),可选 pull --rebase
- * proto_list 原型库目录树+收录清单元数据+git状态
- * proto_read 读原型(默认摘要150行,full=true全量)
- * proto_write 原子写入(tmp+rename,杜绝半截文件)
- * proto_publish 精确提交推送(commit自动规范[域/页]动作:摘要;push前远端检查;成功后广播hub)
- * proto_verify headless视口矩阵断言(publish质量门禁)
- *
- * 配置(env): 见 README.md;核心 PROTO_REPO(原型库绝对路径,必填)
- */
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
- import { z } from "zod";
- import { readFile, writeFile, readdir, stat, rename, mkdir } from "node:fs/promises";
- import { existsSync } from "node:fs";
- import { join, dirname, relative } from "node:path";
- import { git, gitTry, safePath, REPO, BRANCH } from "./lib/git.js";
- import { normalizeMsg } from "./lib/msg.js";
- import { hubNotify, startPolling, newsBanner } from "./lib/hub.js";
- import { verifyPage } from "./lib/verify.js";
- import { readMeta, metaLines } from "./lib/meta.js";
- import { initProject } from "./lib/init.js";
- const server = new McpServer({ name: "wedo", version: "2.0.0" });
- /* ── proto_init ── */
- server.tool("proto_init", "新项目原型库一键引导:目录骨架+_meta.js+门户index.html+git初始化(不覆盖已有库)", {
- repo_path: z.string().describe("原型库绝对路径(不存在则创建)"),
- project_name: z.string().describe("项目/系统名称"),
- repo_url: z.string().optional().describe("git远程仓库地址(可选,提供则自动配置remote)"),
- domains: z.array(z.string()).optional().describe("业务域目录名清单(默认 系统工作台/业务管理/数据中心/系统设置)"),
- live_url: z.string().optional().describe("线上系统访问地址(可选,登记进_meta.js)"),
- }, async (p) => {
- try { return { content: [{ type: "text", text: await initProject(p) }] }; }
- catch (e) { return { content: [{ type: "text", text: `❌ ${e.message}` }] }; }
- });
- /* ── proto_sync ── */
- server.tool("proto_sync", `感知原型库远程更新(hub事件优先,降级git提交比对)+本地脏文件;pull=true 时 pull --rebase 同步(本地脏则拒绝)`, { pull: z.boolean().optional() }, async ({ pull }) => {
- const fetchRes = gitTry(["fetch", "origin", "--quiet"]);
- if (!fetchRes.ok) return { content: [{ type: "text", text: `❌ fetch 失败(检查网络/凭据):\n${fetchRes.err}` }] };
- const news = gitTry(["log", "--pretty=format:%h %an %ad %s", "--date=format:%m-%d %H:%M", `HEAD..origin/${BRANCH}`]).out.trim();
- const dirty = gitTry(["status", "--porcelain"]).out.trim();
- let lines = [`仓库: ${REPO}`];
- lines.push(news ? `🔔 远程有 ${news.split("\n").length} 个新提交:\n${news}` : "✅ 远程无新提交(本地已是最新)");
- lines.push(dirty ? `⚠️ 本地未提交改动(将阻碍 rebase):\n${dirty}` : "✅ 本地工作区干净");
- if (pull) {
- if (news && dirty) lines.push("⏭️ 已跳过 pull:本地有未提交改动,请先处理(提交或暂存)再同步");
- else if (news) {
- const r = gitTry(["pull", "--rebase", "origin", BRANCH]);
- lines.push(r.ok ? "✅ 已同步(pull --rebase 完成,本地页面已更新,浏览器记得刷新)" : `❌ pull 失败:\n${r.err}`);
- } else lines.push("⏭️ 无需 pull");
- } else if (news) lines.push("💡 需要更新到本地时: proto_sync {pull:true}(本地干净才会执行)");
- return { content: [{ type: "text", text: lines.join("\n\n") }] };
- });
- /* ── proto_list ── */
- server.tool("proto_list", "列出原型库目录树(按业务域分组)、收录清单元数据(_meta.js)与 git 状态", {}, async () => {
- async function walk(dir, depth) {
- const out = [];
- for (const name of (await readdir(dir)).sort()) {
- if (name === ".git" || name.startsWith(".")) continue;
- const p = join(dir, name), s = await stat(p);
- if (s.isDirectory()) out.push(`${" ".repeat(depth)}📁 ${name}/`, ...(await walk(p, depth + 1)));
- else out.push(`${" ".repeat(depth)}📄 ${name} (${(s.size / 1024).toFixed(1)}KB)`);
- }
- return out;
- }
- const tree = (await walk(REPO, 0)).join("\n");
- let metaTxt;
- try { metaTxt = metaLines(await readMeta()); }
- catch { metaTxt = "\n\n(⚠️ _meta.js 缺失或解析失败,门户收录清单将不完整;可用 proto_init 模板补建)"; }
- const head = gitTry(["log", "-1", "--pretty=format:%h %an %ad %s", "--date=format:%m-%d %H:%M"]).out;
- const dirty = gitTry(["status", "--porcelain"]).out.trim();
- return { content: [{ type: "text", text: `原型库目录树:\n${tree}${metaTxt}\n\n当前 HEAD: ${head || "(空仓库)"}${dirty ? `\n⚠️ 未提交改动:\n${dirty}` : "\n✅ 工作区干净"}${newsBanner()}` }] };
- });
- /* ── proto_read ── */
- server.tool("proto_read", "读取原型文件;默认摘要模式(前150行+统计),full=true 返回全部内容", { path: z.string().describe("库内相对路径,如 财务管理/包额.html"), full: z.boolean().optional() }, async ({ path: p, full }) => {
- let abs; try { abs = safePath(p); } catch (e) { return { content: [{ type: "text", text: `❌ ${e.message}` }] }; }
- if (!existsSync(abs)) return { content: [{ type: "text", text: `❌ 文件不存在: ${p}(用 proto_list 查看目录)` }] };
- const content = await readFile(abs, "utf8");
- const lines = content.split("\n");
- if (full || lines.length <= 150) return { content: [{ type: "text", text: `📄 ${p} (共${lines.length}行,全量):\n\n${content}` }] };
- return { content: [{ type: "text", text: `📄 ${p} (共${lines.length}行,摘要前150行;需全文加 full:true):\n\n${lines.slice(0, 150).join("\n")}\n\n…(余 ${lines.length - 150} 行省略)` }] };
- });
- /* ── proto_write ── */
- server.tool("proto_write", "原子写入原型文件(临时文件+rename,杜绝半截文件);自动创建父目录;限 .html/.md/_meta.js/门户", { path: z.string(), content: z.string() }, async ({ path: p, content }) => {
- let abs; try { abs = safePath(p); } catch (e) { return { content: [{ type: "text", text: `❌ ${e.message}` }] }; }
- await mkdir(dirname(abs), { recursive: true });
- const tmp = abs + ".tmp_" + Date.now();
- await writeFile(tmp, content, "utf8");
- await rename(tmp, abs);
- return { content: [{ type: "text", text: `✅ 已原子写入 ${p} (${content.split("\n").length}行)。改动未提交,确认后用 proto_publish 推送。` }] };
- });
- /* ── proto_publish ── */
- server.tool("proto_publish",
- "精确提交并推送原型改动(显式文件清单,禁 add -A);commit 自动规范为 [业务域/页面] 动作: 摘要;push 前检查远端(落后拒绝);成功后广播 wedo-hub",
- { files: z.array(z.string()).describe("要提交的文件相对路径清单"), message: z.string().describe("改动摘要(自动包装为规范格式,已合规则原样)") },
- async ({ files, message }) => {
- if (!files || !files.length) return { content: [{ type: "text", text: "❌ files 不能为空(精确提交,拒绝全量提交)" }] };
- const absList = [];
- for (const f of files) {
- let abs; try { abs = safePath(f); } catch (e) { return { content: [{ type: "text", text: `❌ ${e.message}` }] }; }
- if (!existsSync(abs)) return { content: [{ type: "text", text: `❌ 文件不存在: ${f}` }] };
- absList.push(abs);
- }
- gitTry(["fetch", "origin", "--quiet"]);
- const ahead = gitTry(["log", "--oneline", `origin/${BRANCH}..HEAD`]).out.trim();
- const behind = gitTry(["log", "--oneline", `HEAD..origin/${BRANCH}`]).out.trim();
- if (behind && !ahead) return { content: [{ type: "text", text: `❌ 远程有新提交,请先 proto_sync {pull:true} 同步再提交:\n${behind}` }] };
- for (const abs of absList) git(["add", relative(REPO, abs)]);
- const staged = git(["status", "--porcelain"]).split("\n").filter(l => /^[AM]/.test(l));
- if (!staged.length) return { content: [{ type: "text", text: "❌ 没有可提交的改动(文件内容与上次提交相同?)" }] };
- const normMsg = normalizeMsg(message, staged);
- git(["commit", "-m", normMsg]);
- const push = gitTry(["push", "origin", BRANCH]);
- if (!push.ok) {
- gitTry(["reset", "--soft", "HEAD~1"]);
- return { content: [{ type: "text", text: `❌ push 失败(已回退本地提交,改动仍在暂存区):\n${push.err}` }] };
- }
- const head = git(["log", "-1", "--pretty=format:%h"]).trim();
- hubNotify(head, normMsg, staged.map(l => l.slice(3).trim()));
- return { content: [{ type: "text", text: `✅ 已提交并推送 ${head}: ${normMsg}\n提交文件:\n${staged.join("\n")}\n\n💡 建议:重要页面改动 publish 前先 proto_verify 跑视口矩阵断言。${newsBanner()}` }] };
- });
- /* ── proto_verify ── */
- server.tool("proto_verify",
- "对原型页面跑 headless 视口矩阵断言(默认 1280/1536/1920):横向零溢出(默认态+标注态)、页面有内容;publish 前的质量门禁",
- { path: z.string().describe("库内相对路径"), viewports: z.array(z.number()).optional().describe("自定义视口宽度列表") },
- async ({ path: p, viewports }) => {
- let abs; try { abs = safePath(p); } catch (e) { return { content: [{ type: "text", text: `❌ ${e.message}` }] }; }
- if (!existsSync(abs)) return { content: [{ type: "text", text: `❌ 文件不存在: ${p}` }] };
- try {
- const report = await verifyPage(abs, viewports && viewports.length ? viewports : [1280, 1536, 1920]);
- return { content: [{ type: "text", text: report }] };
- } catch (e) { return { content: [{ type: "text", text: `❌ ${e.message}` }] }; }
- });
- /* ── 启动 ── */
- startPolling(5 * 60_000);
- const transport = new StdioServerTransport();
- await server.connect(transport);
- console.error(`[wedo] ready v2.0.0 repo=${REPO} branch=${BRANCH} hub=${process.env.WEDO_HUB_URL ? "on" : "off"}(降级git)`);
|