import { execFile, spawn } from 'node:child_process'; import { readFile } from 'node:fs/promises'; import { createInterface } from 'node:readline'; import { promisify } from 'node:util'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import type { DashboardSnapshot } from '../../domains/dashboard/types.js'; import { resolveNodeCliCommand } from '../../platform/process/node-cli-command.js'; import { compareSemverVersions, parseSemver } from '../../platform/version/version.js'; export function createZCodeMcpServer({ projectRoot, version, panelUrl, env = process.env, }: { projectRoot: string; version: string; panelUrl: URL; env?: NodeJS.ProcessEnv; }) { const execute = promisify(execFile); const uri = 'ui://comet/status.html'; const mimeType = 'text/html;profile=mcp-app'; const server = new McpServer({ name: 'Comet', version }); const installCommand = `npm install -g @rpamis/comet@${version}`; const doctorCommand = 'comet doctor . --scope project --json'; const initCommand = 'comet init . --platform zcode --scope project'; function cometCommand(args: string[]) { const cliEnv = { ...env, COMET_NO_HINTS: '1' }; const invocation = resolveNodeCliCommand('comet', args, { cwd: projectRoot, env: cliEnv }); return { ...invocation, options: { cwd: projectRoot, env: invocation.env ?? cliEnv, windowsHide: true }, }; } async function runComet(args: string[]) { const { command, args: parameters, options } = cometCommand(args); return execute(command, parameters, { ...options, timeout: 30_000, maxBuffer: 16 * 1024 * 1024, }); } async function detectCli() { const installed = await runComet(['--version']).then( ({ stdout }) => stdout.trim(), () => null, ); const installedVersion = installed && parseSemver(installed); const requiredVersion = parseSemver(version)!; const compatible = installedVersion && compareSemverVersions(installedVersion, requiredVersion) >= 0; return { compatible, installed }; } async function requireCli() { const { installed, compatible } = await detectCli(); if (!compatible) { throw new Error( `Comet ${version}+ is required (found ${installed ?? 'none'}). In a terminal, run ${installCommand}, then restart ZCode.`, ); } } function response(content: Record, text: string) { return { content: [{ type: 'text' as const, text }], structuredContent: content }; } server.registerResource('Comet Workflows', uri, { mimeType }, async () => ({ contents: [{ uri, mimeType, text: await readFile(panelUrl, 'utf8') }], })); server.registerTool( 'check_comet', { title: '核对 Comet 安装', description: '检查当前项目的 Comet CLI 版本及 ZCode 项目 Hook 配置。', inputSchema: {}, annotations: { readOnlyHint: true, openWorldHint: false }, }, async () => { const { installed, compatible } = await detectCli(); if (!compatible) { return response( { cli: installed ? 'incompatible' : 'unavailable', installed, required: version, installCommand, }, `此 ZCode 会话需要 Comet CLI ${version} 或更高版本。请运行 ${installCommand},然后重启 ZCode。`, ); } const stdout = await runComet(['doctor', projectRoot, '--scope', 'project', '--json']).then( (result) => result.stdout, (error: { stdout?: string }) => error.stdout ?? '', ); let results: { check: string; status: string; message: string }[] = []; try { const report = JSON.parse(stdout); if (Array.isArray(report.results)) results = report.results; } catch { return response( { cli: 'ready', installed, hook: 'unknown', doctorCommand }, `无法读取项目 Hook 诊断。请运行 ${doctorCommand} 查看原因。`, ); } const hook = results.find(({ check }) => check === 'hooks: ZCode (project)'); if (!hook) { return response( { cli: 'ready', installed, hook: 'unreported', doctorCommand, initCommand }, `当前项目未报告 ZCode 项目 Hook。请核对 ${doctorCommand}。首次配置请选择支持 ZCode 项目 Hook 的 CLI,运行 ${initCommand}。在 ZCode 设置中审核、信任并启用项目 Router。`, ); } const runtimeWarning = results.find( ({ check, status }) => check === 'hook runtime: ZCode (project)' && status !== 'pass', ); return response( { cli: 'ready', installed, hook: hook.status === 'pass' && !runtimeWarning ? 'configured' : 'attention', doctorCommand, }, [ hook.message, runtimeWarning?.message, '在 ZCode 设置中核对项目 Router 的审核、信任和启用状态。', ] .filter(Boolean) .join(' '), ); }, ); server.registerTool( 'comet_status', { title: '读取当前项目的 Comet 状态', inputSchema: {}, annotations: { readOnlyHint: true, openWorldHint: false }, _meta: { ui: { visibility: ['app'] } }, }, async () => { await requireCli(); const { stdout } = await runComet(['dashboard', projectRoot, '--json']); const snapshot = JSON.parse(stdout) as DashboardSnapshot; const native = (snapshot.native?.changes ?? []) .filter((change) => change.workspace.current) .map((change) => ({ id: change.locator, name: change.name, phase: change.phase, status: change.status, workflow: 'Native', artifacts: change.artifacts.filter(({ exists }) => exists).map(({ label }) => label), })); const classic = [...snapshot.changes.active, ...snapshot.changes.archived] .filter((change) => change.workspace.current) .map((change) => ({ id: change.locator, name: change.displayName, phase: change.phase, status: change.status, workflow: 'Classic', artifacts: change.artifacts.grouped .filter(({ exists }) => exists) .map(({ label }) => label), })); return response( { project: snapshot.project, branch: snapshot.git.branch, changes: [...native, ...classic], incomplete: Boolean( snapshot.nativeError || snapshot.classicError || snapshot.native?.changesTruncated, ), }, 'Comet 项目状态已读取。', ); }, ); let dashboard: ReturnType | undefined; let dashboardUrl: Promise | undefined; async function openDashboard() { await requireCli(); if (dashboardUrl) return dashboardUrl; const { command, args, options } = cometCommand([ 'dashboard', projectRoot, '--port', '0', '--no-open', ]); const child = spawn(command, args, { ...options, stdio: ['ignore', 'pipe', 'pipe'] }); dashboard = child; dashboardUrl = new Promise((resolve, reject) => { const lines = createInterface({ input: child.stdout }); child.stderr.resume(); const timer = setTimeout(() => { reject(new Error('Comet Dashboard did not start within 30 seconds.')); child.kill(); }, 30_000); lines.on('line', (line) => { const url = /^Comet Dashboard running at (http:\/\/(?:localhost|127\.0\.0\.1):\d+)\/?$/u.exec( line, )?.[1]; if (url) { clearTimeout(timer); resolve(url); } }); child.once('error', (error) => reject(error)); child.once('close', (code) => { clearTimeout(timer); if (dashboard === child) { dashboard = undefined; dashboardUrl = undefined; } reject(new Error(`Comet Dashboard exited (${code ?? 'no exit code'}).`)); }); }); return dashboardUrl; } server.registerTool( 'open_comet_dashboard', { title: '打开完整 Comet Dashboard', inputSchema: {}, annotations: { readOnlyHint: true, openWorldHint: false }, _meta: { ui: { visibility: ['app'] } }, }, async () => response({ url: await openDashboard() }, 'Comet Dashboard 已就绪。'), ); function stopDashboard() { dashboard?.kill(); } server.server.onclose = stopDashboard; return { server, stopDashboard }; }