-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart-mcp.js
More file actions
132 lines (116 loc) · 3.52 KB
/
start-mcp.js
File metadata and controls
132 lines (116 loc) · 3.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// start-mcp.js
const { spawn } = require("child_process");
const mysql = require("mysql2/promise");
const net = require("net");
const path = require("path");
const fs = require("fs");
const dotenv = require("dotenv");
// Cargar configuración desde el archivo mcp-config.env
const configPath = path.join(__dirname, "mcp-config.env");
const envConfig = dotenv.parse(fs.readFileSync(configPath));
// Función para obtener un valor del archivo de configuración o usar un valor por defecto
function getConfig(key, defaultValue = "") {
return envConfig[key] || process.env[key] || defaultValue;
}
/**
* Espera a que un puerto TCP esté escuchando
*/
async function waitForPort(port, host = "127.0.0.1", timeout = 10000) {
const start = Date.now();
while (Date.now() - start < timeout) {
try {
await new Promise((resolve, reject) => {
const s = net
.createConnection(port, host)
.once("connect", () => {
s.end();
resolve();
})
.once("error", reject);
});
return;
} catch (_) {
// si falla, esperamos medio segundo y reintentamos
await new Promise((r) => setTimeout(r, 500));
}
}
throw new Error(`Timeout esperando a ${host}:${port}`);
}
async function introspectDatabase() {
console.error("🔍 Conectando para inspección…");
const conn = await mysql.createConnection({
host: getConfig("MYSQL_HOST", "127.0.0.1"),
port: parseInt(getConfig("MYSQL_PORT", "3306")),
user: getConfig("MYSQL_USER"),
password: getConfig("MYSQL_PASS"),
database: getConfig("MYSQL_DB"),
});
await conn.end();
console.error("✅ Inspección completada.");
}
async function main() {
// 1) Arrancamos el túnel SSH
const sshHost = getConfig("SSH_HOST");
const sshUser = getConfig("SSH_USER");
const sshPortMapping = getConfig("SSH_PORT_MAPPING", "3306:127.0.0.1:3306");
const ssh = spawn(
"ssh",
[
"-N",
"-L",
sshPortMapping,
`${sshUser}@${sshHost}`,
],
{ stdio: "inherit", shell: false }
);
ssh.on("error", (err) => {
console.error("❌ Error iniciando túnel SSH:", err);
process.exit(1);
});
ssh.on("close", (code) => {
console.error(`🔌 Túnel SSH cerrado (code ${code})`);
process.exit(code);
});
// 2) Esperamos a que 127.0.0.1:3306 esté listo
console.error("⏳ Esperando a que el túnel abra el puerto 3306…");
await waitForPort(parseInt(getConfig("MYSQL_PORT", "3306")), getConfig("MYSQL_HOST", "127.0.0.1"), 15000);
// 3) Hacemos la introspección
await introspectDatabase();
// 4) Arrancamos el MCP-Server
console.error("🔒 Iniciando MCP-Server…");
const serverScript = path.join(
__dirname,
"node_modules",
"@benborla29",
"mcp-server-mysql",
"dist",
"index.js"
);
// Configurar el entorno para el servidor MCP
const serverEnv = {
...process.env,
};
// Añadir todas las variables del archivo de configuración al entorno
Object.keys(envConfig).forEach(key => {
serverEnv[key] = envConfig[key];
});
const server = spawn("node", [serverScript], {
stdio: "inherit",
cwd: __dirname,
env: serverEnv,
});
server.on("error", (err) => {
console.error("❌ Error arrancando MCP-Server:", err);
ssh.kill();
process.exit(1);
});
server.on("exit", (code) => {
console.error(
`⚠️ MCP-Server finalizó con código ${code} — presiona Ctrl+C para cerrar el túnel.`
);
});
}
main().catch((err) => {
console.error("❌ ERROR_FATAL:", err);
process.exit(1);
});