backend-mcp
Version:
Generador automático de backends con Node.js, Express, Prisma y módulos configurables. Servidor MCP compatible con npx para agentes IA. Soporta PostgreSQL, MySQL, MongoDB y SQLite.
318 lines (270 loc) • 9.31 kB
JavaScript
const fs = require('fs');
const path = require('path');
const os = require('os');
// Colores para la consola
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m'
};
function log(message, color = 'reset') {
console.log(`${colors[color]}${message}${colors.reset}`);
}
function showHelp() {
log('\n🤖 Configurador Automático de Backend MCP para Agentes', 'cyan');
log('=' .repeat(60), 'cyan');
log('\nUso: node setup-agent.js [opciones]\n', 'bright');
log('Opciones:', 'yellow');
log(' --agent <tipo> Tipo de agente (claude, cursor, generic)', 'white');
log(' --db <url> URL de la base de datos (opcional)', 'white');
log(' --help Mostrar esta ayuda', 'white');
log('\nEjemplos:', 'yellow');
log(' # Configuración básica (recomendado)', 'green');
log(' node setup-agent.js --agent claude', 'green');
log(' node setup-agent.js --agent cursor', 'green');
log(' node setup-agent.js --agent generic', 'green');
log('', 'white');
log(' # Con base de datos específica (opcional)', 'green');
log(' node setup-agent.js --agent claude --db "postgresql://user:pass@localhost:5432/db"', 'green');
log(' node setup-agent.js --agent cursor --db "file:./database.db"', 'green');
log(' node setup-agent.js --agent generic --db "mysql://user:pass@localhost:3306/db"', 'green');
log('\nAgentes soportados:', 'yellow');
log(' claude - Claude Desktop', 'white');
log(' cursor - Cursor IDE', 'white');
log(' generic - Configuración genérica MCP', 'white');
log('\n💡 Nota:', 'yellow');
log(' Si no especificas --db, el servidor se iniciará sin base de datos.', 'white');
log(' Puedes configurar la base de datos después usando la herramienta configure_database.', 'white');
}
function getClaudeConfigPath() {
const platform = os.platform();
switch (platform) {
case 'win32':
return path.join(os.homedir(), 'AppData', 'Roaming', 'Claude', 'claude_desktop_config.json');
case 'darwin':
return path.join(os.homedir(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
case 'linux':
return path.join(os.homedir(), '.config', 'claude', 'claude_desktop_config.json');
default:
return null;
}
}
function createClaudeConfig(databaseUrl) {
const configPath = getClaudeConfigPath();
if (!configPath) {
log('❌ Plataforma no soportada para Claude Desktop', 'red');
return false;
}
const args = ['backend-mcp'];
if (databaseUrl) {
args.push(databaseUrl);
}
const config = {
mcpServers: {
'backend-mcp': {
command: 'npx',
args: args,
env: {}
}
}
};
try {
// Crear directorio si no existe
const configDir = path.dirname(configPath);
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
// Leer configuración existente si existe
let existingConfig = {};
if (fs.existsSync(configPath)) {
const existingContent = fs.readFileSync(configPath, 'utf8');
try {
existingConfig = JSON.parse(existingContent);
} catch (e) {
log('⚠️ Configuración existente inválida, creando nueva', 'yellow');
}
}
// Fusionar configuraciones
if (!existingConfig.mcpServers) {
existingConfig.mcpServers = {};
}
existingConfig.mcpServers['backend-mcp'] = config.mcpServers['backend-mcp'];
// Escribir configuración
fs.writeFileSync(configPath, JSON.stringify(existingConfig, null, 2));
log('✅ Configuración de Claude Desktop creada exitosamente', 'green');
log(`📁 Ubicación: ${configPath}`, 'cyan');
log('🔄 Reinicia Claude Desktop para aplicar los cambios', 'yellow');
return true;
} catch (error) {
log(`❌ Error al crear configuración de Claude: ${error.message}`, 'red');
return false;
}
}
function createCursorConfig(databaseUrl) {
const args = ['backend-mcp'];
if (databaseUrl) {
args.push(databaseUrl);
}
const config = {
'mcp.servers': {
'backend-mcp': {
command: 'npx',
args: args,
cwd: './'
}
}
};
const configPath = './cursor-mcp-config.json';
try {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
log('✅ Configuración de Cursor IDE creada exitosamente', 'green');
log(`📁 Archivo: ${configPath}`, 'cyan');
log('📋 Copia esta configuración a tu settings.json de Cursor:', 'yellow');
log(' 1. Abre Cursor IDE', 'white');
log(' 2. Ve a File > Preferences > Settings', 'white');
log(' 3. Busca "settings.json" y ábrelo', 'white');
log(' 4. Agrega la configuración del archivo generado', 'white');
return true;
} catch (error) {
log(`❌ Error al crear configuración de Cursor: ${error.message}`, 'red');
return false;
}
}
function createGenericConfig(databaseUrl) {
const args = ['backend-mcp'];
if (databaseUrl) {
args.push(databaseUrl);
}
const config = {
servers: {
'backend-mcp': {
command: 'npx',
args: args,
env: {},
timeout: 30000
}
}
};
const configPath = './generic-mcp-config.json';
try {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
log('✅ Configuración genérica MCP creada exitosamente', 'green');
log(`📁 Archivo: ${configPath}`, 'cyan');
log('📋 Usa esta configuración en tu cliente MCP compatible', 'yellow');
return true;
} catch (error) {
log(`❌ Error al crear configuración genérica: ${error.message}`, 'red');
return false;
}
}
function validateDatabaseUrl(url) {
const patterns = {
postgresql: /^postgresql:\/\/[^:]+:[^@]+@[^:]+:\d+\/\w+$/,
mysql: /^mysql:\/\/[^:]+:[^@]+@[^:]+:\d+\/\w+$/,
mongodb: /^mongodb:\/\/[^:]+:[^@]+@[^:]+:\d+\/\w+$/,
sqlite: /^file:.*\.db$/
};
for (const [type, pattern] of Object.entries(patterns)) {
if (pattern.test(url)) {
return type;
}
}
return null;
}
function main() {
const args = process.argv.slice(2);
if (args.includes('--help') || args.length === 0) {
showHelp();
return;
}
let agent = null;
let databaseUrl = null;
// Parsear argumentos
for (let i = 0; i < args.length; i++) {
if (args[i] === '--agent' && i + 1 < args.length) {
agent = args[i + 1];
i++;
} else if (args[i] === '--db' && i + 1 < args.length) {
databaseUrl = args[i + 1];
i++;
}
}
if (!agent) {
log('❌ Debes especificar un tipo de agente con --agent', 'red');
log('💡 Usa --help para ver las opciones disponibles', 'yellow');
return;
}
let dbType = null;
// Validar URL de base de datos si se proporciona
if (databaseUrl) {
dbType = validateDatabaseUrl(databaseUrl);
if (!dbType) {
log('❌ URL de base de datos inválida', 'red');
log('💡 Formatos soportados:', 'yellow');
log(' postgresql://user:pass@host:5432/db', 'white');
log(' mysql://user:pass@host:3306/db', 'white');
log(' mongodb://user:pass@host:27017/db', 'white');
log(' file:./database.db', 'white');
return;
}
}
log('\n🚀 Configurando Backend MCP...', 'cyan');
if (dbType) {
log(`🗄️ Base de datos: ${dbType}`, 'blue');
} else {
log('🗄️ Base de datos: No configurada (se configurará dinámicamente)', 'blue');
}
log(`🤖 Agente: ${agent}`, 'blue');
log('');
let success = false;
switch (agent.toLowerCase()) {
case 'claude':
success = createClaudeConfig(databaseUrl);
break;
case 'cursor':
success = createCursorConfig(databaseUrl);
break;
case 'generic':
success = createGenericConfig(databaseUrl);
break;
default:
log(`❌ Agente no soportado: ${agent}`, 'red');
log('💡 Agentes disponibles: claude, cursor, generic', 'yellow');
return;
}
if (success) {
log('\n🎉 ¡Configuración completada exitosamente!', 'green');
log('\n📋 Próximos pasos:', 'yellow');
if (databaseUrl) {
log(' 1. Asegúrate de que tu base de datos esté ejecutándose', 'white');
log(' 2. Reinicia tu agente para aplicar la configuración', 'white');
log(' 3. Prueba con comandos como "Crea una tabla de usuarios"', 'white');
} else {
log(' 1. Reinicia tu agente para aplicar la configuración', 'white');
log(' 2. Usa la herramienta "configure_database" para configurar tu base de datos', 'white');
log(' 3. Prueba con comandos como "Crea una tabla de usuarios"', 'white');
}
log('\n🔧 Para probar localmente:', 'yellow');
if (databaseUrl) {
log(` npx backend-mcp "${databaseUrl}"`, 'green');
} else {
log(' npx backend-mcp', 'green');
log(' # Luego usa configure_database para configurar la base de datos', 'cyan');
}
}
}
if (require.main === module) {
main();
}
module.exports = {
createClaudeConfig,
createCursorConfig,
createGenericConfig,
validateDatabaseUrl
};