index.js•2.98 kB
#!/usr/bin/env node
const { spawn, exec } = require('child_process');
const path = require('path');
const fs = require('fs');
const os = require('os');
const CACHE_FILE = path.join(os.tmpdir(), '.dieter-rams-mcp-deps-ok');
function checkRequirements() {
// Skip check if cached and recent (< 1 hour)
if (fs.existsSync(CACHE_FILE)) {
const stats = fs.statSync(CACHE_FILE);
const ageMs = Date.now() - stats.mtime.getTime();
if (ageMs < 3600000) { // 1 hour
return Promise.resolve();
}
}
return new Promise((resolve, reject) => {
exec('python3 --version', (error, stdout) => {
if (error) {
reject(new Error('Python 3 is required but not found. Please install Python 3.7+'));
return;
}
const requirementsPath = path.join(__dirname, 'requirements.txt');
if (!fs.existsSync(requirementsPath)) {
reject(new Error('requirements.txt not found'));
return;
}
exec('python3 -c "import fastmcp"', (error) => {
if (error) {
reject(new Error('Python dependencies not installed. Run: pip install -r requirements.txt'));
return;
}
// Cache successful check
try {
fs.writeFileSync(CACHE_FILE, Date.now().toString());
} catch (e) {
// Ignore cache write errors
}
resolve();
});
});
});
}
async function startMCPServer() {
try {
await checkRequirements();
} catch (error) {
console.error(`Setup Error: ${error.message}`);
process.exit(1);
}
const serverPath = path.join(__dirname, 'server.py');
if (!fs.existsSync(serverPath)) {
console.error('server.py not found');
process.exit(1);
}
const pythonProcess = spawn('python3', [serverPath], {
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env, PYTHONUNBUFFERED: '1' } // Faster output
});
pythonProcess.stdout.pipe(process.stdout);
process.stdin.pipe(pythonProcess.stdin);
pythonProcess.stderr.pipe(process.stderr);
let isShuttingDown = false;
pythonProcess.on('error', (error) => {
if (!isShuttingDown) {
console.error(`Failed to start Python MCP server: ${error.message}`);
process.exit(1);
}
});
pythonProcess.on('close', (code) => {
if (!isShuttingDown && code !== 0) {
console.error(`Python MCP server exited with code ${code}`);
process.exit(code);
}
});
function gracefulShutdown(signal) {
if (isShuttingDown) return;
isShuttingDown = true;
pythonProcess.kill(signal);
// Force kill after 5 seconds
setTimeout(() => {
if (!pythonProcess.killed) {
pythonProcess.kill('SIGKILL');
}
process.exit(0);
}, 5000);
}
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
}
if (require.main === module) {
startMCPServer();
}
module.exports = { startMCPServer };