import { fileURLToPath } from 'node:url'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { createDefaultDashboardPluginHostFactory } from '../../domains/dashboard/default-plugin-host.js'; import { discoverDashboardProjectRoot } from '../../domains/dashboard/project-root.js'; import { startDashboardServer } from '../../domains/dashboard/server.js'; import { spawnInstalledCometCommand } from '../../platform/process/comet-command.js'; import { getCurrentVersion } from '../../platform/version/version.js'; const server = new McpServer({ name: 'comet-dashboard', version: getCurrentVersion() }); let dashboard: Promise> & { projectPath: string }> | undefined; async function resolveProjectPath(): Promise { const fallback = process.env.CLAUDE_PROJECT_DIR ?? process.cwd(); if (server.server.getClientCapabilities()?.roots) { // Claude lists the session launch directory before any additional directories. const { roots } = await server.server.listRoots(undefined, { timeout: 5_000 }); if (roots[0]) return discoverDashboardProjectRoot(fileURLToPath(roots[0].uri)); } return discoverDashboardProjectRoot(fallback); } server.registerTool( 'open_dashboard', { title: 'Open Comet Dashboard', description: 'Start or reuse Comet Dashboard for this local Claude Code project.', inputSchema: {}, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, }, async () => { dashboard ??= resolveProjectPath() .then(async (projectPath) => ({ ...(await startDashboardServer({ projectPath, webRoot: fileURLToPath(new URL('./web/', import.meta.url)), port: 0, pluginHost: createDefaultDashboardPluginHostFactory(), spawnUpdateCommand: spawnInstalledCometCommand, })), projectPath, })) .catch((error: unknown) => { dashboard = undefined; throw error; }); const { url, projectPath } = await dashboard; return { content: [{ type: 'text', text: url }], structuredContent: { url, projectPath }, }; }, ); server.server.onclose = () => { void dashboard?.then((handle) => handle.close()).catch(() => undefined); }; function stop() { void server.close(); } process.once('SIGINT', stop); process.once('SIGTERM', stop); process.stdin.once('end', stop); await server.connect(new StdioServerTransport());