import { Command } from 'commander'; import chalk from 'chalk'; import { spawn } from 'child_process'; import path from 'path'; import fs from 'fs'; import { fileURLToPath } from 'url'; import { getApiKey, getApiUrl } from '../utils/config.js'; // ESM compatibility for __dirname const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); export function createMcpCommand() { const mcp = new Command('mcp'); mcp .description('Run the Rigstate MCP server for AI editors') .action(async () => { // Determine the path to the MCP server const possiblePaths = [ // From packages/cli -> packages/mcp (sibling package) path.resolve(__dirname, '../../mcp/dist/index.js'), // If installed globally or via npm path.resolve(__dirname, '../../../mcp/dist/index.js'), // Development path from packages/cli/dist path.resolve(__dirname, '../../../packages/mcp/dist/index.js'), ]; let serverPath = ''; for (const p of possiblePaths) { if (fs.existsSync(p)) { serverPath = p; break; } } if (!serverPath) { console.error(chalk.red('❌ Error: Rigstate MCP Server binary not found.')); console.error(chalk.yellow('Please ensure that the mcp package is built:')); console.error(chalk.white(' cd packages/mcp && npm run build')); console.error(''); console.error(chalk.dim('Or run directly with:')); console.error(chalk.white(' npx @rigstate/mcp')); process.exit(1); } console.log(chalk.dim(`Starting MCP server from: ${serverPath}`)); // SMART INJECTION: Inject global config into MCP environment const env = { ...process.env }; try { const apiKey = getApiKey(); if (apiKey) { env.RIGSTATE_API_KEY = apiKey; // Also inject the URL for consistency env.RIGSTATE_APP_URL = getApiUrl(); env.RIGSTATE_API_URL = getApiUrl(); } } catch (e) { // If not logged in, we carry on and let the MCP server show the final error } // Map VIBE_API_KEY if needed if (env.VIBE_API_KEY && !env.RIGSTATE_API_KEY) { env.RIGSTATE_API_KEY = env.VIBE_API_KEY; } // Spawn the MCP server as a child process const worker = spawn('node', [serverPath], { env, stdio: ['inherit', 'inherit', 'inherit'] }); worker.on('error', (err) => { console.error(chalk.red(`❌ Failed to start MCP server: ${err.message}`)); process.exit(1); }); worker.on('exit', (code) => { if (code !== 0 && code !== null) { process.exit(code); } }); }); return mcp; }