@mgsoftwarebv/mg-dashboard-mcp 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -0
- package/dist/index.js +784 -0
- package/dist/index.js.map +1 -0
- package/package.json +46 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,784 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
3
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
4
|
+
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
5
|
+
import { createClient } from '@supabase/supabase-js';
|
|
6
|
+
import { createHash, randomBytes, createCipheriv, createDecipheriv } from 'crypto';
|
|
7
|
+
import { Client } from 'ssh2';
|
|
8
|
+
|
|
9
|
+
var args = process.argv.slice(2);
|
|
10
|
+
function getArg(name) {
|
|
11
|
+
return args.find((a) => a.startsWith(`--${name}=`))?.split("=").slice(1).join("=");
|
|
12
|
+
}
|
|
13
|
+
var apiKey = getArg("api-key") || process.env.MG_DASHBOARD_API_KEY;
|
|
14
|
+
var supabaseUrl = getArg("supabase-url") || process.env.SUPABASE_URL;
|
|
15
|
+
var supabaseKey = getArg("supabase-key") || process.env.SUPABASE_SERVICE_ROLE_KEY;
|
|
16
|
+
var encryptionKey = getArg("encryption-key") || process.env.ENCRYPTION_KEY;
|
|
17
|
+
if (!apiKey) {
|
|
18
|
+
console.error("API key is required. Use --api-key=dk_xxx or set MG_DASHBOARD_API_KEY");
|
|
19
|
+
process.exit(1);
|
|
20
|
+
}
|
|
21
|
+
if (!supabaseUrl || !supabaseKey) {
|
|
22
|
+
console.error("Supabase credentials required. Use --supabase-url and --supabase-key or set SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY");
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
var supabase = createClient(supabaseUrl, supabaseKey);
|
|
26
|
+
var authContext = null;
|
|
27
|
+
async function validateApiKey(key) {
|
|
28
|
+
if (!key.startsWith("dk_") || key.length !== 67) {
|
|
29
|
+
console.error("Invalid API key format (expected dk_ + 64 hex chars)");
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
const keyHash = createHash("sha256").update(key).digest("hex");
|
|
33
|
+
const { data, error } = await supabase.from("dashboard_mcp_api_key").select("id, created_by, allowed_server_ids, is_active, expires_at").eq("api_key_hash", keyHash).eq("is_active", true).single();
|
|
34
|
+
if (error || !data) {
|
|
35
|
+
console.error("API key not found or inactive");
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
if (data.expires_at && new Date(data.expires_at) < /* @__PURE__ */ new Date()) {
|
|
39
|
+
console.error("API key has expired");
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
await supabase.from("dashboard_mcp_api_key").update({ last_used_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", data.id);
|
|
43
|
+
console.error(`Authenticated as user ${data.created_by}`);
|
|
44
|
+
return {
|
|
45
|
+
userId: data.created_by,
|
|
46
|
+
allowedServerIds: data.allowed_server_ids
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function assertServerAccess(serverId) {
|
|
50
|
+
if (!authContext) throw new Error("Not authenticated");
|
|
51
|
+
if (authContext.allowedServerIds === null) return;
|
|
52
|
+
if (!authContext.allowedServerIds.includes(serverId)) {
|
|
53
|
+
throw new Error(`Access denied: you do not have permission for server ${serverId}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
var ENC_ALGORITHM = "aes-256-gcm";
|
|
57
|
+
var ENC_IV_LENGTH = 16;
|
|
58
|
+
var ENC_TAG_LENGTH = 16;
|
|
59
|
+
function getEncryptionKey() {
|
|
60
|
+
if (!encryptionKey) throw new Error("ENCRYPTION_KEY is required for env operations");
|
|
61
|
+
const buf = Buffer.from(encryptionKey, "hex");
|
|
62
|
+
if (buf.length !== 32) throw new Error("ENCRYPTION_KEY must be a 64-character hex string");
|
|
63
|
+
return buf;
|
|
64
|
+
}
|
|
65
|
+
function encrypt(text) {
|
|
66
|
+
const key = getEncryptionKey();
|
|
67
|
+
const iv = randomBytes(ENC_IV_LENGTH);
|
|
68
|
+
const cipher = createCipheriv(ENC_ALGORITHM, new Uint8Array(key), new Uint8Array(iv));
|
|
69
|
+
let encrypted = cipher.update(text, "utf8", "hex");
|
|
70
|
+
encrypted += cipher.final("hex");
|
|
71
|
+
const authTag = cipher.getAuthTag();
|
|
72
|
+
return Buffer.concat([
|
|
73
|
+
new Uint8Array(iv),
|
|
74
|
+
new Uint8Array(authTag),
|
|
75
|
+
new Uint8Array(Buffer.from(encrypted, "hex"))
|
|
76
|
+
]).toString("base64");
|
|
77
|
+
}
|
|
78
|
+
function decrypt(payload) {
|
|
79
|
+
const key = getEncryptionKey();
|
|
80
|
+
const buf = Buffer.from(payload, "base64");
|
|
81
|
+
const iv = buf.subarray(0, ENC_IV_LENGTH);
|
|
82
|
+
const authTag = buf.subarray(ENC_IV_LENGTH, ENC_IV_LENGTH + ENC_TAG_LENGTH);
|
|
83
|
+
const encrypted = buf.subarray(ENC_IV_LENGTH + ENC_TAG_LENGTH);
|
|
84
|
+
const decipher = createDecipheriv(ENC_ALGORITHM, new Uint8Array(key), new Uint8Array(iv));
|
|
85
|
+
decipher.setAuthTag(new Uint8Array(authTag));
|
|
86
|
+
let decrypted = decipher.update(encrypted.toString("hex"), "hex", "utf8");
|
|
87
|
+
decrypted += decipher.final("utf8");
|
|
88
|
+
return decrypted;
|
|
89
|
+
}
|
|
90
|
+
async function getServerConnection(serverId) {
|
|
91
|
+
assertServerAccess(serverId);
|
|
92
|
+
const { data, error } = await supabase.from("ssh_server").select("hostname, port, username, password_encrypted, ssh_key_encrypted, ssh_key_passphrase_encrypted").eq("id", serverId).single();
|
|
93
|
+
if (error || !data) throw new Error(`Server not found: ${serverId}`);
|
|
94
|
+
if (!encryptionKey) throw new Error("ENCRYPTION_KEY required to decrypt server credentials");
|
|
95
|
+
return {
|
|
96
|
+
hostname: data.hostname,
|
|
97
|
+
port: data.port || 22,
|
|
98
|
+
username: data.username,
|
|
99
|
+
password: data.password_encrypted ? decrypt(data.password_encrypted) : void 0,
|
|
100
|
+
privateKey: data.ssh_key_encrypted ? decrypt(data.ssh_key_encrypted) : void 0,
|
|
101
|
+
passphrase: data.ssh_key_passphrase_encrypted ? decrypt(data.ssh_key_passphrase_encrypted) : void 0
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
async function sshExec(opts, command) {
|
|
105
|
+
return new Promise((resolve) => {
|
|
106
|
+
const ssh = new Client();
|
|
107
|
+
let stdout = "";
|
|
108
|
+
let stderr = "";
|
|
109
|
+
let done = false;
|
|
110
|
+
const timeout = opts.timeout || 6e4;
|
|
111
|
+
const timer = setTimeout(() => {
|
|
112
|
+
if (!done) {
|
|
113
|
+
done = true;
|
|
114
|
+
ssh.end();
|
|
115
|
+
resolve({ stdout, stderr, exitCode: -1 });
|
|
116
|
+
}
|
|
117
|
+
}, timeout);
|
|
118
|
+
ssh.on("ready", () => {
|
|
119
|
+
ssh.exec(command, (err, stream) => {
|
|
120
|
+
if (err) {
|
|
121
|
+
if (!done) {
|
|
122
|
+
done = true;
|
|
123
|
+
clearTimeout(timer);
|
|
124
|
+
ssh.end();
|
|
125
|
+
resolve({ stdout, stderr, exitCode: -1 });
|
|
126
|
+
}
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
stream.on("data", (d) => {
|
|
130
|
+
stdout += d.toString();
|
|
131
|
+
});
|
|
132
|
+
stream.stderr.on("data", (d) => {
|
|
133
|
+
stderr += d.toString();
|
|
134
|
+
});
|
|
135
|
+
stream.on("close", (code) => {
|
|
136
|
+
if (!done) {
|
|
137
|
+
done = true;
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
ssh.end();
|
|
140
|
+
resolve({ stdout, stderr, exitCode: code ?? 0 });
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
ssh.on("error", (err) => {
|
|
146
|
+
if (!done) {
|
|
147
|
+
done = true;
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
resolve({ stdout, stderr: err.message, exitCode: -1 });
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
ssh.connect({
|
|
153
|
+
host: opts.hostname,
|
|
154
|
+
port: opts.port,
|
|
155
|
+
username: opts.username,
|
|
156
|
+
password: opts.password,
|
|
157
|
+
privateKey: opts.privateKey,
|
|
158
|
+
passphrase: opts.passphrase,
|
|
159
|
+
readyTimeout: timeout
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
function sanitizePath(path) {
|
|
164
|
+
let normalized = path.replace(/\\/g, "/").replace(/\0/g, "");
|
|
165
|
+
const parts = normalized.split("/");
|
|
166
|
+
const resolved = [];
|
|
167
|
+
for (const part of parts) {
|
|
168
|
+
if (part === "..") {
|
|
169
|
+
if (resolved.length > 0 && resolved[resolved.length - 1] !== "") resolved.pop();
|
|
170
|
+
} else if (part !== "." && part !== "") resolved.push(part);
|
|
171
|
+
}
|
|
172
|
+
return "/" + resolved.join("/");
|
|
173
|
+
}
|
|
174
|
+
var PROTECTED_PATHS = ["/etc/", "/boot/", "/usr/", "/bin/", "/sbin/", "/lib/", "/lib64/"];
|
|
175
|
+
function assertWritablePath(path) {
|
|
176
|
+
const safe = sanitizePath(path);
|
|
177
|
+
for (const p of PROTECTED_PATHS) {
|
|
178
|
+
if (safe === p.slice(0, -1) || safe.startsWith(p)) {
|
|
179
|
+
throw new Error(`Write access denied to protected path: ${safe}`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
async function sftpReaddir(opts, dirPath) {
|
|
184
|
+
const safe = sanitizePath(dirPath);
|
|
185
|
+
return new Promise((resolve) => {
|
|
186
|
+
const ssh = new Client();
|
|
187
|
+
let done = false;
|
|
188
|
+
const timer = setTimeout(() => {
|
|
189
|
+
if (!done) {
|
|
190
|
+
done = true;
|
|
191
|
+
ssh.end();
|
|
192
|
+
resolve("Error: timeout");
|
|
193
|
+
}
|
|
194
|
+
}, 3e4);
|
|
195
|
+
ssh.on("ready", () => {
|
|
196
|
+
ssh.sftp((err, sftp) => {
|
|
197
|
+
if (err) {
|
|
198
|
+
if (!done) {
|
|
199
|
+
done = true;
|
|
200
|
+
clearTimeout(timer);
|
|
201
|
+
ssh.end();
|
|
202
|
+
resolve(`Error: ${err.message}`);
|
|
203
|
+
}
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
sftp.readdir(safe, (err2, list) => {
|
|
207
|
+
done = true;
|
|
208
|
+
clearTimeout(timer);
|
|
209
|
+
if (err2) {
|
|
210
|
+
ssh.end();
|
|
211
|
+
resolve(`Error: ${err2.message}`);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
const entries = list.map((item) => {
|
|
215
|
+
const mode = item.attrs.mode || 0;
|
|
216
|
+
const isDir = (mode & 61440) === 16384;
|
|
217
|
+
const size = item.attrs.size || 0;
|
|
218
|
+
const mtime = item.attrs.mtime ? new Date(item.attrs.mtime * 1e3).toISOString() : "";
|
|
219
|
+
return `${isDir ? "d" : "-"} ${String(size).padStart(10)} ${mtime} ${item.filename}`;
|
|
220
|
+
});
|
|
221
|
+
ssh.end();
|
|
222
|
+
resolve(entries.join("\n"));
|
|
223
|
+
});
|
|
224
|
+
});
|
|
225
|
+
});
|
|
226
|
+
ssh.on("error", (e) => {
|
|
227
|
+
if (!done) {
|
|
228
|
+
done = true;
|
|
229
|
+
clearTimeout(timer);
|
|
230
|
+
resolve(`Error: ${e.message}`);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
ssh.connect({ host: opts.hostname, port: opts.port, username: opts.username, password: opts.password, privateKey: opts.privateKey, passphrase: opts.passphrase, readyTimeout: 3e4 });
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
async function sftpRead(opts, filePath) {
|
|
237
|
+
const safe = sanitizePath(filePath);
|
|
238
|
+
return new Promise((resolve) => {
|
|
239
|
+
const ssh = new Client();
|
|
240
|
+
let done = false;
|
|
241
|
+
const timer = setTimeout(() => {
|
|
242
|
+
if (!done) {
|
|
243
|
+
done = true;
|
|
244
|
+
ssh.end();
|
|
245
|
+
resolve("Error: timeout");
|
|
246
|
+
}
|
|
247
|
+
}, 6e4);
|
|
248
|
+
ssh.on("ready", () => {
|
|
249
|
+
ssh.sftp((err, sftp) => {
|
|
250
|
+
if (err) {
|
|
251
|
+
if (!done) {
|
|
252
|
+
done = true;
|
|
253
|
+
clearTimeout(timer);
|
|
254
|
+
ssh.end();
|
|
255
|
+
resolve(`Error: ${err.message}`);
|
|
256
|
+
}
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
sftp.stat(safe, (err2, stats) => {
|
|
260
|
+
if (err2) {
|
|
261
|
+
if (!done) {
|
|
262
|
+
done = true;
|
|
263
|
+
clearTimeout(timer);
|
|
264
|
+
ssh.end();
|
|
265
|
+
resolve(`Error: ${err2.message}`);
|
|
266
|
+
}
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if ((stats.size || 0) > 1048576) {
|
|
270
|
+
if (!done) {
|
|
271
|
+
done = true;
|
|
272
|
+
clearTimeout(timer);
|
|
273
|
+
ssh.end();
|
|
274
|
+
resolve(`Error: file too large (${stats.size} bytes, max 1MB)`);
|
|
275
|
+
}
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
const chunks = [];
|
|
279
|
+
const rs = sftp.createReadStream(safe);
|
|
280
|
+
rs.on("data", (c) => chunks.push(c));
|
|
281
|
+
rs.on("end", () => {
|
|
282
|
+
if (!done) {
|
|
283
|
+
done = true;
|
|
284
|
+
clearTimeout(timer);
|
|
285
|
+
ssh.end();
|
|
286
|
+
resolve(Buffer.concat(chunks.map((c) => new Uint8Array(c))).toString("utf-8"));
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
rs.on("error", (e) => {
|
|
290
|
+
if (!done) {
|
|
291
|
+
done = true;
|
|
292
|
+
clearTimeout(timer);
|
|
293
|
+
ssh.end();
|
|
294
|
+
resolve(`Error: ${e.message}`);
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
});
|
|
299
|
+
});
|
|
300
|
+
ssh.on("error", (e) => {
|
|
301
|
+
if (!done) {
|
|
302
|
+
done = true;
|
|
303
|
+
clearTimeout(timer);
|
|
304
|
+
resolve(`Error: ${e.message}`);
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
ssh.connect({ host: opts.hostname, port: opts.port, username: opts.username, password: opts.password, privateKey: opts.privateKey, passphrase: opts.passphrase, readyTimeout: 6e4 });
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
async function sftpWrite(opts, filePath, content) {
|
|
311
|
+
const safe = sanitizePath(filePath);
|
|
312
|
+
assertWritablePath(safe);
|
|
313
|
+
return new Promise((resolve) => {
|
|
314
|
+
const ssh = new Client();
|
|
315
|
+
let done = false;
|
|
316
|
+
const timer = setTimeout(() => {
|
|
317
|
+
if (!done) {
|
|
318
|
+
done = true;
|
|
319
|
+
ssh.end();
|
|
320
|
+
resolve("Error: timeout");
|
|
321
|
+
}
|
|
322
|
+
}, 6e4);
|
|
323
|
+
ssh.on("ready", () => {
|
|
324
|
+
ssh.sftp((err, sftp) => {
|
|
325
|
+
if (err) {
|
|
326
|
+
if (!done) {
|
|
327
|
+
done = true;
|
|
328
|
+
clearTimeout(timer);
|
|
329
|
+
ssh.end();
|
|
330
|
+
resolve(`Error: ${err.message}`);
|
|
331
|
+
}
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
const ws = sftp.createWriteStream(safe, { mode: 420 });
|
|
335
|
+
ws.on("close", () => {
|
|
336
|
+
if (!done) {
|
|
337
|
+
done = true;
|
|
338
|
+
clearTimeout(timer);
|
|
339
|
+
ssh.end();
|
|
340
|
+
resolve(`Written ${content.length} bytes to ${safe}`);
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
ws.on("error", (e) => {
|
|
344
|
+
if (!done) {
|
|
345
|
+
done = true;
|
|
346
|
+
clearTimeout(timer);
|
|
347
|
+
ssh.end();
|
|
348
|
+
resolve(`Error: ${e.message}`);
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
ws.end(Buffer.from(content, "utf-8"));
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
ssh.on("error", (e) => {
|
|
355
|
+
if (!done) {
|
|
356
|
+
done = true;
|
|
357
|
+
clearTimeout(timer);
|
|
358
|
+
resolve(`Error: ${e.message}`);
|
|
359
|
+
}
|
|
360
|
+
});
|
|
361
|
+
ssh.connect({ host: opts.hostname, port: opts.port, username: opts.username, password: opts.password, privateKey: opts.privateKey, passphrase: opts.passphrase, readyTimeout: 6e4 });
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
async function sftpDelete(opts, filePath) {
|
|
365
|
+
const safe = sanitizePath(filePath);
|
|
366
|
+
assertWritablePath(safe);
|
|
367
|
+
return new Promise((resolve) => {
|
|
368
|
+
const ssh = new Client();
|
|
369
|
+
let done = false;
|
|
370
|
+
const timer = setTimeout(() => {
|
|
371
|
+
if (!done) {
|
|
372
|
+
done = true;
|
|
373
|
+
ssh.end();
|
|
374
|
+
resolve("Error: timeout");
|
|
375
|
+
}
|
|
376
|
+
}, 3e4);
|
|
377
|
+
ssh.on("ready", () => {
|
|
378
|
+
ssh.sftp((err, sftp) => {
|
|
379
|
+
if (err) {
|
|
380
|
+
if (!done) {
|
|
381
|
+
done = true;
|
|
382
|
+
clearTimeout(timer);
|
|
383
|
+
ssh.end();
|
|
384
|
+
resolve(`Error: ${err.message}`);
|
|
385
|
+
}
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
sftp.unlink(safe, (err2) => {
|
|
389
|
+
if (err2) {
|
|
390
|
+
sftp.rmdir(safe, (err22) => {
|
|
391
|
+
done = true;
|
|
392
|
+
clearTimeout(timer);
|
|
393
|
+
ssh.end();
|
|
394
|
+
resolve(err22 ? `Error: ${err2.message}` : `Deleted directory ${safe}`);
|
|
395
|
+
});
|
|
396
|
+
} else {
|
|
397
|
+
done = true;
|
|
398
|
+
clearTimeout(timer);
|
|
399
|
+
ssh.end();
|
|
400
|
+
resolve(`Deleted file ${safe}`);
|
|
401
|
+
}
|
|
402
|
+
});
|
|
403
|
+
});
|
|
404
|
+
});
|
|
405
|
+
ssh.on("error", (e) => {
|
|
406
|
+
if (!done) {
|
|
407
|
+
done = true;
|
|
408
|
+
clearTimeout(timer);
|
|
409
|
+
resolve(`Error: ${e.message}`);
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
ssh.connect({ host: opts.hostname, port: opts.port, username: opts.username, password: opts.password, privateKey: opts.privateKey, passphrase: opts.passphrase, readyTimeout: 3e4 });
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
var BLOCKED_COMMANDS = [
|
|
416
|
+
"rm -rf /",
|
|
417
|
+
"rm -fr /",
|
|
418
|
+
"mkfs",
|
|
419
|
+
"dd if=",
|
|
420
|
+
":(){ :|:& };:",
|
|
421
|
+
"shutdown",
|
|
422
|
+
"halt",
|
|
423
|
+
"init 0",
|
|
424
|
+
"init 6",
|
|
425
|
+
"> /dev/sda",
|
|
426
|
+
"mv /* /dev/null",
|
|
427
|
+
"chmod -R 000 /"
|
|
428
|
+
];
|
|
429
|
+
function assertSafeCommand(command) {
|
|
430
|
+
const lower = command.toLowerCase().trim();
|
|
431
|
+
for (const blocked of BLOCKED_COMMANDS) {
|
|
432
|
+
if (lower.includes(blocked)) {
|
|
433
|
+
throw new Error(`Blocked dangerous command pattern: "${blocked}"`);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
var TOOLS = [
|
|
438
|
+
{
|
|
439
|
+
name: "list-servers",
|
|
440
|
+
description: "List all SSH servers you have access to. Returns id, name, hostname, and tags for each server.",
|
|
441
|
+
inputSchema: { type: "object", properties: {}, required: [] }
|
|
442
|
+
},
|
|
443
|
+
{
|
|
444
|
+
name: "server-status",
|
|
445
|
+
description: "Get server status including uptime, disk usage, memory, and load average.",
|
|
446
|
+
inputSchema: {
|
|
447
|
+
type: "object",
|
|
448
|
+
properties: {
|
|
449
|
+
serverId: { type: "string", description: "UUID of the SSH server" }
|
|
450
|
+
},
|
|
451
|
+
required: ["serverId"]
|
|
452
|
+
}
|
|
453
|
+
},
|
|
454
|
+
{
|
|
455
|
+
name: "ssh-execute",
|
|
456
|
+
description: "Execute a shell command on a remote server via SSH. Some dangerous commands are blocked for safety.",
|
|
457
|
+
inputSchema: {
|
|
458
|
+
type: "object",
|
|
459
|
+
properties: {
|
|
460
|
+
serverId: { type: "string", description: "UUID of the SSH server" },
|
|
461
|
+
command: { type: "string", description: "Shell command to execute" },
|
|
462
|
+
timeout: { type: "number", description: "Timeout in milliseconds (default: 60000)" }
|
|
463
|
+
},
|
|
464
|
+
required: ["serverId", "command"]
|
|
465
|
+
}
|
|
466
|
+
},
|
|
467
|
+
{
|
|
468
|
+
name: "server-reboot",
|
|
469
|
+
description: "Reboot a remote server. This will cause downtime. The server will be unavailable until it restarts.",
|
|
470
|
+
inputSchema: {
|
|
471
|
+
type: "object",
|
|
472
|
+
properties: {
|
|
473
|
+
serverId: { type: "string", description: "UUID of the SSH server to reboot" }
|
|
474
|
+
},
|
|
475
|
+
required: ["serverId"]
|
|
476
|
+
}
|
|
477
|
+
},
|
|
478
|
+
{
|
|
479
|
+
name: "server-restart-service",
|
|
480
|
+
description: "Restart a systemd service on a remote server using systemctl restart.",
|
|
481
|
+
inputSchema: {
|
|
482
|
+
type: "object",
|
|
483
|
+
properties: {
|
|
484
|
+
serverId: { type: "string", description: "UUID of the SSH server" },
|
|
485
|
+
serviceName: { type: "string", description: "Name of the systemd service (e.g. nginx, docker, lsws)" }
|
|
486
|
+
},
|
|
487
|
+
required: ["serverId", "serviceName"]
|
|
488
|
+
}
|
|
489
|
+
},
|
|
490
|
+
{
|
|
491
|
+
name: "sftp-list",
|
|
492
|
+
description: "List files and directories at a given path on a remote server via SFTP.",
|
|
493
|
+
inputSchema: {
|
|
494
|
+
type: "object",
|
|
495
|
+
properties: {
|
|
496
|
+
serverId: { type: "string", description: "UUID of the SSH server" },
|
|
497
|
+
path: { type: "string", description: "Directory path to list (default: /)" }
|
|
498
|
+
},
|
|
499
|
+
required: ["serverId"]
|
|
500
|
+
}
|
|
501
|
+
},
|
|
502
|
+
{
|
|
503
|
+
name: "sftp-read",
|
|
504
|
+
description: "Read the contents of a text file on a remote server via SFTP (max 1MB).",
|
|
505
|
+
inputSchema: {
|
|
506
|
+
type: "object",
|
|
507
|
+
properties: {
|
|
508
|
+
serverId: { type: "string", description: "UUID of the SSH server" },
|
|
509
|
+
path: { type: "string", description: "File path to read" }
|
|
510
|
+
},
|
|
511
|
+
required: ["serverId", "path"]
|
|
512
|
+
}
|
|
513
|
+
},
|
|
514
|
+
{
|
|
515
|
+
name: "sftp-write",
|
|
516
|
+
description: "Write content to a file on a remote server via SFTP. Protected system paths are blocked.",
|
|
517
|
+
inputSchema: {
|
|
518
|
+
type: "object",
|
|
519
|
+
properties: {
|
|
520
|
+
serverId: { type: "string", description: "UUID of the SSH server" },
|
|
521
|
+
path: { type: "string", description: "File path to write" },
|
|
522
|
+
content: { type: "string", description: "File content to write" }
|
|
523
|
+
},
|
|
524
|
+
required: ["serverId", "path", "content"]
|
|
525
|
+
}
|
|
526
|
+
},
|
|
527
|
+
{
|
|
528
|
+
name: "sftp-delete",
|
|
529
|
+
description: "Delete a file or empty directory on a remote server via SFTP. Protected system paths are blocked.",
|
|
530
|
+
inputSchema: {
|
|
531
|
+
type: "object",
|
|
532
|
+
properties: {
|
|
533
|
+
serverId: { type: "string", description: "UUID of the SSH server" },
|
|
534
|
+
path: { type: "string", description: "File or directory path to delete" }
|
|
535
|
+
},
|
|
536
|
+
required: ["serverId", "path"]
|
|
537
|
+
}
|
|
538
|
+
},
|
|
539
|
+
{
|
|
540
|
+
name: "docker-list",
|
|
541
|
+
description: "List all Docker containers on a remote server (running and stopped).",
|
|
542
|
+
inputSchema: {
|
|
543
|
+
type: "object",
|
|
544
|
+
properties: {
|
|
545
|
+
serverId: { type: "string", description: "UUID of the SSH server" }
|
|
546
|
+
},
|
|
547
|
+
required: ["serverId"]
|
|
548
|
+
}
|
|
549
|
+
},
|
|
550
|
+
{
|
|
551
|
+
name: "docker-action",
|
|
552
|
+
description: "Perform an action on a Docker container: start, stop, restart, or remove.",
|
|
553
|
+
inputSchema: {
|
|
554
|
+
type: "object",
|
|
555
|
+
properties: {
|
|
556
|
+
serverId: { type: "string", description: "UUID of the SSH server" },
|
|
557
|
+
containerName: { type: "string", description: "Container name or ID" },
|
|
558
|
+
action: { type: "string", enum: ["start", "stop", "restart", "remove"], description: "Action to perform" }
|
|
559
|
+
},
|
|
560
|
+
required: ["serverId", "containerName", "action"]
|
|
561
|
+
}
|
|
562
|
+
},
|
|
563
|
+
{
|
|
564
|
+
name: "docker-logs",
|
|
565
|
+
description: "Get recent logs from a Docker container.",
|
|
566
|
+
inputSchema: {
|
|
567
|
+
type: "object",
|
|
568
|
+
properties: {
|
|
569
|
+
serverId: { type: "string", description: "UUID of the SSH server" },
|
|
570
|
+
containerName: { type: "string", description: "Container name or ID" },
|
|
571
|
+
lines: { type: "number", description: "Number of log lines to retrieve (default: 100)" }
|
|
572
|
+
},
|
|
573
|
+
required: ["serverId", "containerName"]
|
|
574
|
+
}
|
|
575
|
+
},
|
|
576
|
+
{
|
|
577
|
+
name: "env-list",
|
|
578
|
+
description: "List all stored environment configurations (app name, environment, description).",
|
|
579
|
+
inputSchema: { type: "object", properties: {}, required: [] }
|
|
580
|
+
},
|
|
581
|
+
{
|
|
582
|
+
name: "env-get",
|
|
583
|
+
description: "Retrieve the decrypted .env content for a specific app and environment.",
|
|
584
|
+
inputSchema: {
|
|
585
|
+
type: "object",
|
|
586
|
+
properties: {
|
|
587
|
+
appName: { type: "string", description: "Application name (e.g. backoffice, api, web)" },
|
|
588
|
+
environment: { type: "string", description: "Environment name (e.g. production, staging, development)" }
|
|
589
|
+
},
|
|
590
|
+
required: ["appName", "environment"]
|
|
591
|
+
}
|
|
592
|
+
},
|
|
593
|
+
{
|
|
594
|
+
name: "env-store",
|
|
595
|
+
description: "Store or update an encrypted .env configuration for an app and environment.",
|
|
596
|
+
inputSchema: {
|
|
597
|
+
type: "object",
|
|
598
|
+
properties: {
|
|
599
|
+
appName: { type: "string", description: "Application name (e.g. backoffice, api, web)" },
|
|
600
|
+
environment: { type: "string", description: "Environment name (e.g. production, staging, development)" },
|
|
601
|
+
content: { type: "string", description: "The .env file content to store" },
|
|
602
|
+
description: { type: "string", description: "Optional description" }
|
|
603
|
+
},
|
|
604
|
+
required: ["appName", "environment", "content"]
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
];
|
|
608
|
+
var server = new Server(
|
|
609
|
+
{ name: "mg-dashboard-mcp", version: "1.0.0" },
|
|
610
|
+
{ capabilities: { tools: {} } }
|
|
611
|
+
);
|
|
612
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
|
613
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
614
|
+
if (!authContext) {
|
|
615
|
+
return { content: [{ type: "text", text: "Error: not authenticated" }] };
|
|
616
|
+
}
|
|
617
|
+
const { name, arguments: toolArgs } = request.params;
|
|
618
|
+
const a = toolArgs || {};
|
|
619
|
+
try {
|
|
620
|
+
switch (name) {
|
|
621
|
+
// ----- Servers -----
|
|
622
|
+
case "list-servers": {
|
|
623
|
+
let query = supabase.from("ssh_server").select("id, name, hostname, port, username, tags, hosted_by, created_at").order("name");
|
|
624
|
+
if (authContext.allowedServerIds !== null) {
|
|
625
|
+
query = query.in("id", authContext.allowedServerIds);
|
|
626
|
+
}
|
|
627
|
+
const { data, error } = await query;
|
|
628
|
+
if (error) throw new Error(error.message);
|
|
629
|
+
const lines = (data || []).map((s) => {
|
|
630
|
+
const tags = Array.isArray(s.tags) ? s.tags.join(", ") : "";
|
|
631
|
+
return `${s.id} ${s.name} ${s.hostname}:${s.port} ${s.username} [${tags}] ${s.hosted_by || ""}`;
|
|
632
|
+
});
|
|
633
|
+
return { content: [{ type: "text", text: lines.length ? lines.join("\n") : "No servers found" }] };
|
|
634
|
+
}
|
|
635
|
+
case "server-status": {
|
|
636
|
+
const conn = await getServerConnection(String(a.serverId));
|
|
637
|
+
const cmd = 'echo "=== UPTIME ===" && uptime && echo "=== DISK ===" && df -h --total && echo "=== MEMORY ===" && free -h && echo "=== LOAD ===" && cat /proc/loadavg';
|
|
638
|
+
const result = await sshExec(conn, cmd);
|
|
639
|
+
const output = result.exitCode === 0 ? result.stdout : `Exit ${result.exitCode}
|
|
640
|
+
${result.stdout}
|
|
641
|
+
${result.stderr}`;
|
|
642
|
+
return { content: [{ type: "text", text: output }] };
|
|
643
|
+
}
|
|
644
|
+
// ----- SSH -----
|
|
645
|
+
case "ssh-execute": {
|
|
646
|
+
const command = String(a.command);
|
|
647
|
+
assertSafeCommand(command);
|
|
648
|
+
const conn = await getServerConnection(String(a.serverId));
|
|
649
|
+
if (a.timeout) conn.timeout = Number(a.timeout);
|
|
650
|
+
const result = await sshExec(conn, command);
|
|
651
|
+
const output = [`Exit code: ${result.exitCode}`];
|
|
652
|
+
if (result.stdout) output.push(`--- stdout ---
|
|
653
|
+
${result.stdout}`);
|
|
654
|
+
if (result.stderr) output.push(`--- stderr ---
|
|
655
|
+
${result.stderr}`);
|
|
656
|
+
return { content: [{ type: "text", text: output.join("\n") }] };
|
|
657
|
+
}
|
|
658
|
+
case "server-reboot": {
|
|
659
|
+
const conn = await getServerConnection(String(a.serverId));
|
|
660
|
+
const result = await sshExec(conn, "sudo reboot");
|
|
661
|
+
return { content: [{ type: "text", text: result.exitCode === 0 ? "Reboot command sent. Server will be unavailable shortly." : `Reboot failed: ${result.stderr}` }] };
|
|
662
|
+
}
|
|
663
|
+
case "server-restart-service": {
|
|
664
|
+
const service = String(a.serviceName).replace(/[^a-zA-Z0-9._@-]/g, "");
|
|
665
|
+
const conn = await getServerConnection(String(a.serverId));
|
|
666
|
+
const result = await sshExec(conn, `sudo systemctl restart ${service}`);
|
|
667
|
+
if (result.exitCode === 0) {
|
|
668
|
+
const status = await sshExec(conn, `sudo systemctl is-active ${service}`);
|
|
669
|
+
return { content: [{ type: "text", text: `Service "${service}" restarted. Status: ${status.stdout.trim()}` }] };
|
|
670
|
+
}
|
|
671
|
+
return { content: [{ type: "text", text: `Failed to restart "${service}": ${result.stderr}` }] };
|
|
672
|
+
}
|
|
673
|
+
// ----- SFTP -----
|
|
674
|
+
case "sftp-list": {
|
|
675
|
+
const conn = await getServerConnection(String(a.serverId));
|
|
676
|
+
const listing = await sftpReaddir(conn, String(a.path || "/"));
|
|
677
|
+
return { content: [{ type: "text", text: listing }] };
|
|
678
|
+
}
|
|
679
|
+
case "sftp-read": {
|
|
680
|
+
const conn = await getServerConnection(String(a.serverId));
|
|
681
|
+
const content = await sftpRead(conn, String(a.path));
|
|
682
|
+
return { content: [{ type: "text", text: content }] };
|
|
683
|
+
}
|
|
684
|
+
case "sftp-write": {
|
|
685
|
+
const conn = await getServerConnection(String(a.serverId));
|
|
686
|
+
const result = await sftpWrite(conn, String(a.path), String(a.content));
|
|
687
|
+
return { content: [{ type: "text", text: result }] };
|
|
688
|
+
}
|
|
689
|
+
case "sftp-delete": {
|
|
690
|
+
const conn = await getServerConnection(String(a.serverId));
|
|
691
|
+
const result = await sftpDelete(conn, String(a.path));
|
|
692
|
+
return { content: [{ type: "text", text: result }] };
|
|
693
|
+
}
|
|
694
|
+
// ----- Docker -----
|
|
695
|
+
case "docker-list": {
|
|
696
|
+
const conn = await getServerConnection(String(a.serverId));
|
|
697
|
+
const result = await sshExec(conn, 'docker ps -a --format "table {{.Names}} {{.Image}} {{.Status}} {{.Ports}}"');
|
|
698
|
+
return { content: [{ type: "text", text: result.exitCode === 0 ? result.stdout : `Error: ${result.stderr}` }] };
|
|
699
|
+
}
|
|
700
|
+
case "docker-action": {
|
|
701
|
+
const container = String(a.containerName).replace(/[^a-zA-Z0-9._-]/g, "");
|
|
702
|
+
const action = String(a.action);
|
|
703
|
+
if (!["start", "stop", "restart", "remove"].includes(action)) {
|
|
704
|
+
throw new Error(`Invalid action: ${action}. Use start, stop, restart, or remove.`);
|
|
705
|
+
}
|
|
706
|
+
const conn = await getServerConnection(String(a.serverId));
|
|
707
|
+
const dockerCmd = action === "remove" ? `docker rm -f ${container}` : `docker ${action} ${container}`;
|
|
708
|
+
const result = await sshExec(conn, dockerCmd);
|
|
709
|
+
return { content: [{ type: "text", text: result.exitCode === 0 ? `Container "${container}" ${action}ed successfully` : `Error: ${result.stderr}` }] };
|
|
710
|
+
}
|
|
711
|
+
case "docker-logs": {
|
|
712
|
+
const container = String(a.containerName).replace(/[^a-zA-Z0-9._-]/g, "");
|
|
713
|
+
const lines = Number(a.lines) || 100;
|
|
714
|
+
const conn = await getServerConnection(String(a.serverId));
|
|
715
|
+
const result = await sshExec(conn, `docker logs --tail ${lines} ${container} 2>&1`);
|
|
716
|
+
return { content: [{ type: "text", text: result.exitCode === 0 ? result.stdout : `Error: ${result.stderr}` }] };
|
|
717
|
+
}
|
|
718
|
+
// ----- Env Config -----
|
|
719
|
+
case "env-list": {
|
|
720
|
+
const { data, error } = await supabase.from("env_config").select("id, app_name, environment, description, updated_at").order("app_name").order("environment");
|
|
721
|
+
if (error) throw new Error(error.message);
|
|
722
|
+
const lines = (data || []).map(
|
|
723
|
+
(e) => `${e.app_name}/${e.environment} ${e.description || ""} (updated: ${e.updated_at})`
|
|
724
|
+
);
|
|
725
|
+
return { content: [{ type: "text", text: lines.length ? lines.join("\n") : "No environment configs stored" }] };
|
|
726
|
+
}
|
|
727
|
+
case "env-get": {
|
|
728
|
+
const { data, error } = await supabase.from("env_config").select("env_data_encrypted").eq("app_name", String(a.appName)).eq("environment", String(a.environment)).single();
|
|
729
|
+
if (error || !data) throw new Error(`Env config not found: ${a.appName}/${a.environment}`);
|
|
730
|
+
const decrypted = decrypt(data.env_data_encrypted);
|
|
731
|
+
return { content: [{ type: "text", text: decrypted }] };
|
|
732
|
+
}
|
|
733
|
+
case "env-store": {
|
|
734
|
+
const appName = String(a.appName);
|
|
735
|
+
const environment = String(a.environment);
|
|
736
|
+
const encrypted = encrypt(String(a.content));
|
|
737
|
+
const { data: existing } = await supabase.from("env_config").select("id").eq("app_name", appName).eq("environment", environment).single();
|
|
738
|
+
if (existing) {
|
|
739
|
+
const { error: error2 } = await supabase.from("env_config").update({
|
|
740
|
+
env_data_encrypted: encrypted,
|
|
741
|
+
description: a.description ? String(a.description) : void 0,
|
|
742
|
+
updated_by: authContext.userId,
|
|
743
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
744
|
+
}).eq("id", existing.id);
|
|
745
|
+
if (error2) throw new Error(error2.message);
|
|
746
|
+
return { content: [{ type: "text", text: `Updated env config: ${appName}/${environment}` }] };
|
|
747
|
+
}
|
|
748
|
+
const { error } = await supabase.from("env_config").insert({
|
|
749
|
+
app_name: appName,
|
|
750
|
+
environment,
|
|
751
|
+
env_data_encrypted: encrypted,
|
|
752
|
+
description: a.description ? String(a.description) : null,
|
|
753
|
+
created_by: authContext.userId,
|
|
754
|
+
updated_by: authContext.userId
|
|
755
|
+
});
|
|
756
|
+
if (error) throw new Error(error.message);
|
|
757
|
+
return { content: [{ type: "text", text: `Stored env config: ${appName}/${environment}` }] };
|
|
758
|
+
}
|
|
759
|
+
default:
|
|
760
|
+
return { content: [{ type: "text", text: `Unknown tool: ${name}` }] };
|
|
761
|
+
}
|
|
762
|
+
} catch (err) {
|
|
763
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
764
|
+
return { content: [{ type: "text", text: `Error: ${message}` }] };
|
|
765
|
+
}
|
|
766
|
+
});
|
|
767
|
+
async function main() {
|
|
768
|
+
console.error("Starting MG Dashboard MCP Server...");
|
|
769
|
+
authContext = await validateApiKey(apiKey);
|
|
770
|
+
if (!authContext) {
|
|
771
|
+
console.error("API key validation failed");
|
|
772
|
+
process.exit(1);
|
|
773
|
+
}
|
|
774
|
+
console.error("API key validated. Starting stdio transport...");
|
|
775
|
+
const transport = new StdioServerTransport();
|
|
776
|
+
await server.connect(transport);
|
|
777
|
+
console.error("MCP Server ready. Tools available: " + TOOLS.map((t) => t.name).join(", "));
|
|
778
|
+
}
|
|
779
|
+
main().catch((err) => {
|
|
780
|
+
console.error("Fatal error:", err);
|
|
781
|
+
process.exit(1);
|
|
782
|
+
});
|
|
783
|
+
//# sourceMappingURL=index.js.map
|
|
784
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["SshClient","err","err2","error"],"mappings":";;;;;;;;AAaA,IAAM,IAAA,GAAO,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA;AAEjC,SAAS,OAAO,IAAA,EAAkC;AAChD,EAAA,OAAO,KAAK,IAAA,CAAK,CAAA,CAAA,KAAK,CAAA,CAAE,UAAA,CAAW,KAAK,IAAI,CAAA,CAAA,CAAG,CAAC,CAAA,EAAG,MAAM,GAAG,CAAA,CAAE,MAAM,CAAC,CAAA,CAAE,KAAK,GAAG,CAAA;AACjF;AAEA,IAAM,MAAA,GAAS,MAAA,CAAO,SAAS,CAAA,IAAK,QAAQ,GAAA,CAAI,oBAAA;AAChD,IAAM,WAAA,GAAc,MAAA,CAAO,cAAc,CAAA,IAAK,QAAQ,GAAA,CAAI,YAAA;AAC1D,IAAM,WAAA,GAAc,MAAA,CAAO,cAAc,CAAA,IAAK,QAAQ,GAAA,CAAI,yBAAA;AAC1D,IAAM,aAAA,GAAgB,MAAA,CAAO,gBAAgB,CAAA,IAAK,QAAQ,GAAA,CAAI,cAAA;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CAAC,WAAA,EAAa;AAChB,IAAA,OAAA,CAAQ,MAAM,2BAA2B,CAAA;AACzC,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AAEA,EAAA,OAAA,CAAQ,MAAM,gDAAgD,CAAA;AAE9D,EAAA,MAAM,SAAA,GAAY,IAAI,oBAAA,EAAqB;AAC3C,EAAA,MAAM,MAAA,CAAO,QAAQ,SAAS,CAAA;AAE9B,EAAA,OAAA,CAAQ,KAAA,CAAM,qCAAA,GAAwC,KAAA,CAAM,GAAA,CAAI,CAAA,CAAA,KAAK,EAAE,IAAI,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA;AACzF;AAEA,IAAA,EAAK,CAAE,KAAA,CAAM,CAAC,GAAA,KAAQ;AACpB,EAAA,OAAA,CAAQ,KAAA,CAAM,gBAAgB,GAAG,CAAA;AACjC,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA","file":"index.js","sourcesContent":["#!/usr/bin/env node\r\n\r\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\r\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\r\nimport { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';\r\nimport { createClient } from '@supabase/supabase-js';\r\nimport { createHash, randomBytes, createCipheriv, createDecipheriv } from 'crypto';\r\nimport { Client as SshClient } from 'ssh2';\r\n\r\n// ---------------------------------------------------------------------------\r\n// CLI argument parsing\r\n// ---------------------------------------------------------------------------\r\n\r\nconst args = process.argv.slice(2);\r\n\r\nfunction getArg(name: string): string | undefined {\r\n return args.find(a => a.startsWith(`--${name}=`))?.split('=').slice(1).join('=');\r\n}\r\n\r\nconst apiKey = getArg('api-key') || process.env.MG_DASHBOARD_API_KEY;\r\nconst supabaseUrl = getArg('supabase-url') || process.env.SUPABASE_URL;\r\nconst supabaseKey = getArg('supabase-key') || process.env.SUPABASE_SERVICE_ROLE_KEY;\r\nconst encryptionKey = getArg('encryption-key') || process.env.ENCRYPTION_KEY;\r\n\r\nif (!apiKey) {\r\n console.error('API key is required. Use --api-key=dk_xxx or set MG_DASHBOARD_API_KEY');\r\n process.exit(1);\r\n}\r\n\r\nif (!supabaseUrl || !supabaseKey) {\r\n console.error('Supabase credentials required. Use --supabase-url and --supabase-key or set SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY');\r\n process.exit(1);\r\n}\r\n\r\nconst supabase = createClient(supabaseUrl, supabaseKey);\r\n\r\n// ---------------------------------------------------------------------------\r\n// Auth context\r\n// ---------------------------------------------------------------------------\r\n\r\ninterface AuthContext {\r\n userId: string;\r\n allowedServerIds: string[] | null;\r\n}\r\n\r\nlet authContext: AuthContext | null = null;\r\n\r\nasync function validateApiKey(key: string): Promise<AuthContext | null> {\r\n if (!key.startsWith('dk_') || key.length !== 67) {\r\n console.error('Invalid API key format (expected dk_ + 64 hex chars)');\r\n return null;\r\n }\r\n\r\n const keyHash = createHash('sha256').update(key).digest('hex');\r\n\r\n const { data, error } = await supabase\r\n .from('dashboard_mcp_api_key')\r\n .select('id, created_by, allowed_server_ids, is_active, expires_at')\r\n .eq('api_key_hash', keyHash)\r\n .eq('is_active', true)\r\n .single();\r\n\r\n if (error || !data) {\r\n console.error('API key not found or inactive');\r\n return null;\r\n }\r\n\r\n if (data.expires_at && new Date(data.expires_at) < new Date()) {\r\n console.error('API key has expired');\r\n return null;\r\n }\r\n\r\n await supabase\r\n .from('dashboard_mcp_api_key')\r\n .update({ last_used_at: new Date().toISOString() })\r\n .eq('id', data.id);\r\n\r\n console.error(`Authenticated as user ${data.created_by}`);\r\n\r\n return {\r\n userId: data.created_by,\r\n allowedServerIds: data.allowed_server_ids,\r\n };\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Server access helper\r\n// ---------------------------------------------------------------------------\r\n\r\nfunction assertServerAccess(serverId: string): void {\r\n if (!authContext) throw new Error('Not authenticated');\r\n if (authContext.allowedServerIds === null) return;\r\n if (!authContext.allowedServerIds.includes(serverId)) {\r\n throw new Error(`Access denied: you do not have permission for server ${serverId}`);\r\n }\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Encryption helpers (AES-256-GCM, compatible with dashboard encryption.ts)\r\n// ---------------------------------------------------------------------------\r\n\r\nconst ENC_ALGORITHM = 'aes-256-gcm';\r\nconst ENC_IV_LENGTH = 16;\r\nconst ENC_TAG_LENGTH = 16;\r\n\r\nfunction getEncryptionKey(): Buffer {\r\n if (!encryptionKey) throw new Error('ENCRYPTION_KEY is required for env operations');\r\n const buf = Buffer.from(encryptionKey, 'hex');\r\n if (buf.length !== 32) throw new Error('ENCRYPTION_KEY must be a 64-character hex string');\r\n return buf;\r\n}\r\n\r\nfunction encrypt(text: string): string {\r\n const key = getEncryptionKey();\r\n const iv = randomBytes(ENC_IV_LENGTH);\r\n const cipher = createCipheriv(ENC_ALGORITHM, new Uint8Array(key), new Uint8Array(iv));\r\n let encrypted = cipher.update(text, 'utf8', 'hex');\r\n encrypted += cipher.final('hex');\r\n const authTag = cipher.getAuthTag();\r\n return Buffer.concat([\r\n new Uint8Array(iv),\r\n new Uint8Array(authTag),\r\n new Uint8Array(Buffer.from(encrypted, 'hex')),\r\n ]).toString('base64');\r\n}\r\n\r\nfunction decrypt(payload: string): string {\r\n const key = getEncryptionKey();\r\n const buf = Buffer.from(payload, 'base64');\r\n const iv = buf.subarray(0, ENC_IV_LENGTH);\r\n const authTag = buf.subarray(ENC_IV_LENGTH, ENC_IV_LENGTH + ENC_TAG_LENGTH);\r\n const encrypted = buf.subarray(ENC_IV_LENGTH + ENC_TAG_LENGTH);\r\n const decipher = createDecipheriv(ENC_ALGORITHM, new Uint8Array(key), new Uint8Array(iv));\r\n decipher.setAuthTag(new Uint8Array(authTag));\r\n let decrypted = decipher.update(encrypted.toString('hex'), 'hex', 'utf8');\r\n decrypted += decipher.final('utf8');\r\n return decrypted;\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// SSH helpers\r\n// ---------------------------------------------------------------------------\r\n\r\ninterface SshConnectionOptions {\r\n hostname: string;\r\n port: number;\r\n username: string;\r\n password?: string;\r\n privateKey?: string;\r\n passphrase?: string;\r\n timeout?: number;\r\n}\r\n\r\ninterface SshResult {\r\n stdout: string;\r\n stderr: string;\r\n exitCode: number;\r\n}\r\n\r\nasync function getServerConnection(serverId: string): Promise<SshConnectionOptions> {\r\n assertServerAccess(serverId);\r\n\r\n const { data, error } = await supabase\r\n .from('ssh_server')\r\n .select('hostname, port, username, password_encrypted, ssh_key_encrypted, ssh_key_passphrase_encrypted')\r\n .eq('id', serverId)\r\n .single();\r\n\r\n if (error || !data) throw new Error(`Server not found: ${serverId}`);\r\n if (!encryptionKey) throw new Error('ENCRYPTION_KEY required to decrypt server credentials');\r\n\r\n return {\r\n hostname: data.hostname,\r\n port: data.port || 22,\r\n username: data.username,\r\n password: data.password_encrypted ? decrypt(data.password_encrypted) : undefined,\r\n privateKey: data.ssh_key_encrypted ? decrypt(data.ssh_key_encrypted) : undefined,\r\n passphrase: data.ssh_key_passphrase_encrypted ? decrypt(data.ssh_key_passphrase_encrypted) : undefined,\r\n };\r\n}\r\n\r\nasync function sshExec(opts: SshConnectionOptions, command: string): Promise<SshResult> {\r\n return new Promise((resolve) => {\r\n const ssh = new SshClient();\r\n let stdout = '';\r\n let stderr = '';\r\n let done = false;\r\n const timeout = opts.timeout || 60_000;\r\n\r\n const timer = setTimeout(() => {\r\n if (!done) { done = true; ssh.end(); resolve({ stdout, stderr, exitCode: -1 }); }\r\n }, timeout);\r\n\r\n ssh.on('ready', () => {\r\n ssh.exec(command, (err, stream) => {\r\n if (err) {\r\n if (!done) { done = true; clearTimeout(timer); ssh.end(); resolve({ stdout, stderr, exitCode: -1 }); }\r\n return;\r\n }\r\n stream.on('data', (d: Buffer) => { stdout += d.toString(); });\r\n stream.stderr.on('data', (d: Buffer) => { stderr += d.toString(); });\r\n stream.on('close', (code: number | null) => {\r\n if (!done) { done = true; clearTimeout(timer); ssh.end(); resolve({ stdout, stderr, exitCode: code ?? 0 }); }\r\n });\r\n });\r\n });\r\n\r\n ssh.on('error', (err) => {\r\n if (!done) { done = true; clearTimeout(timer); resolve({ stdout, stderr: err.message, exitCode: -1 }); }\r\n });\r\n\r\n ssh.connect({\r\n host: opts.hostname, port: opts.port, username: opts.username,\r\n password: opts.password, privateKey: opts.privateKey, passphrase: opts.passphrase,\r\n readyTimeout: timeout,\r\n });\r\n });\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// SFTP helpers\r\n// ---------------------------------------------------------------------------\r\n\r\nfunction sanitizePath(path: string): string {\r\n let normalized = path.replace(/\\\\/g, '/').replace(/\\0/g, '');\r\n const parts = normalized.split('/');\r\n const resolved: string[] = [];\r\n for (const part of parts) {\r\n if (part === '..') { if (resolved.length > 0 && resolved[resolved.length - 1] !== '') resolved.pop(); }\r\n else if (part !== '.' && part !== '') resolved.push(part);\r\n }\r\n return '/' + resolved.join('/');\r\n}\r\n\r\nconst PROTECTED_PATHS = ['/etc/', '/boot/', '/usr/', '/bin/', '/sbin/', '/lib/', '/lib64/'];\r\n\r\nfunction assertWritablePath(path: string): void {\r\n const safe = sanitizePath(path);\r\n for (const p of PROTECTED_PATHS) {\r\n if (safe === p.slice(0, -1) || safe.startsWith(p)) {\r\n throw new Error(`Write access denied to protected path: ${safe}`);\r\n }\r\n }\r\n}\r\n\r\nasync function sftpReaddir(opts: SshConnectionOptions, dirPath: string): Promise<string> {\r\n const safe = sanitizePath(dirPath);\r\n return new Promise((resolve) => {\r\n const ssh = new SshClient();\r\n let done = false;\r\n const timer = setTimeout(() => { if (!done) { done = true; ssh.end(); resolve('Error: timeout'); } }, 30_000);\r\n\r\n ssh.on('ready', () => {\r\n ssh.sftp((err, sftp) => {\r\n if (err) { if (!done) { done = true; clearTimeout(timer); ssh.end(); resolve(`Error: ${err.message}`); } return; }\r\n sftp.readdir(safe, (err, list) => {\r\n done = true; clearTimeout(timer);\r\n if (err) { ssh.end(); resolve(`Error: ${err.message}`); return; }\r\n const entries = list.map(item => {\r\n const mode = item.attrs.mode || 0;\r\n const isDir = (mode & 0o170000) === 0o040000;\r\n const size = item.attrs.size || 0;\r\n const mtime = item.attrs.mtime ? new Date(item.attrs.mtime * 1000).toISOString() : '';\r\n return `${isDir ? 'd' : '-'} ${String(size).padStart(10)} ${mtime} ${item.filename}`;\r\n });\r\n ssh.end();\r\n resolve(entries.join('\\n'));\r\n });\r\n });\r\n });\r\n ssh.on('error', (e) => { if (!done) { done = true; clearTimeout(timer); resolve(`Error: ${e.message}`); } });\r\n ssh.connect({ host: opts.hostname, port: opts.port, username: opts.username, password: opts.password, privateKey: opts.privateKey, passphrase: opts.passphrase, readyTimeout: 30_000 });\r\n });\r\n}\r\n\r\nasync function sftpRead(opts: SshConnectionOptions, filePath: string): Promise<string> {\r\n const safe = sanitizePath(filePath);\r\n return new Promise((resolve) => {\r\n const ssh = new SshClient();\r\n let done = false;\r\n const timer = setTimeout(() => { if (!done) { done = true; ssh.end(); resolve('Error: timeout'); } }, 60_000);\r\n\r\n ssh.on('ready', () => {\r\n ssh.sftp((err, sftp) => {\r\n if (err) { if (!done) { done = true; clearTimeout(timer); ssh.end(); resolve(`Error: ${err.message}`); } return; }\r\n sftp.stat(safe, (err, stats) => {\r\n if (err) { if (!done) { done = true; clearTimeout(timer); ssh.end(); resolve(`Error: ${err.message}`); } return; }\r\n if ((stats.size || 0) > 1_048_576) {\r\n if (!done) { done = true; clearTimeout(timer); ssh.end(); resolve(`Error: file too large (${stats.size} bytes, max 1MB)`); }\r\n return;\r\n }\r\n const chunks: Buffer[] = [];\r\n const rs = sftp.createReadStream(safe);\r\n rs.on('data', (c: Buffer) => chunks.push(c));\r\n rs.on('end', () => { if (!done) { done = true; clearTimeout(timer); ssh.end(); resolve(Buffer.concat(chunks.map(c => new Uint8Array(c))).toString('utf-8')); } });\r\n rs.on('error', (e: Error) => { if (!done) { done = true; clearTimeout(timer); ssh.end(); resolve(`Error: ${e.message}`); } });\r\n });\r\n });\r\n });\r\n ssh.on('error', (e) => { if (!done) { done = true; clearTimeout(timer); resolve(`Error: ${e.message}`); } });\r\n ssh.connect({ host: opts.hostname, port: opts.port, username: opts.username, password: opts.password, privateKey: opts.privateKey, passphrase: opts.passphrase, readyTimeout: 60_000 });\r\n });\r\n}\r\n\r\nasync function sftpWrite(opts: SshConnectionOptions, filePath: string, content: string): Promise<string> {\r\n const safe = sanitizePath(filePath);\r\n assertWritablePath(safe);\r\n return new Promise((resolve) => {\r\n const ssh = new SshClient();\r\n let done = false;\r\n const timer = setTimeout(() => { if (!done) { done = true; ssh.end(); resolve('Error: timeout'); } }, 60_000);\r\n\r\n ssh.on('ready', () => {\r\n ssh.sftp((err, sftp) => {\r\n if (err) { if (!done) { done = true; clearTimeout(timer); ssh.end(); resolve(`Error: ${err.message}`); } return; }\r\n const ws = sftp.createWriteStream(safe, { mode: 0o644 });\r\n ws.on('close', () => { if (!done) { done = true; clearTimeout(timer); ssh.end(); resolve(`Written ${content.length} bytes to ${safe}`); } });\r\n ws.on('error', (e: Error) => { if (!done) { done = true; clearTimeout(timer); ssh.end(); resolve(`Error: ${e.message}`); } });\r\n ws.end(Buffer.from(content, 'utf-8'));\r\n });\r\n });\r\n ssh.on('error', (e) => { if (!done) { done = true; clearTimeout(timer); resolve(`Error: ${e.message}`); } });\r\n ssh.connect({ host: opts.hostname, port: opts.port, username: opts.username, password: opts.password, privateKey: opts.privateKey, passphrase: opts.passphrase, readyTimeout: 60_000 });\r\n });\r\n}\r\n\r\nasync function sftpDelete(opts: SshConnectionOptions, filePath: string): Promise<string> {\r\n const safe = sanitizePath(filePath);\r\n assertWritablePath(safe);\r\n return new Promise((resolve) => {\r\n const ssh = new SshClient();\r\n let done = false;\r\n const timer = setTimeout(() => { if (!done) { done = true; ssh.end(); resolve('Error: timeout'); } }, 30_000);\r\n\r\n ssh.on('ready', () => {\r\n ssh.sftp((err, sftp) => {\r\n if (err) { if (!done) { done = true; clearTimeout(timer); ssh.end(); resolve(`Error: ${err.message}`); } return; }\r\n sftp.unlink(safe, (err) => {\r\n if (err) {\r\n sftp.rmdir(safe, (err2) => {\r\n done = true; clearTimeout(timer); ssh.end();\r\n resolve(err2 ? `Error: ${err.message}` : `Deleted directory ${safe}`);\r\n });\r\n } else {\r\n done = true; clearTimeout(timer); ssh.end();\r\n resolve(`Deleted file ${safe}`);\r\n }\r\n });\r\n });\r\n });\r\n ssh.on('error', (e) => { if (!done) { done = true; clearTimeout(timer); resolve(`Error: ${e.message}`); } });\r\n ssh.connect({ host: opts.hostname, port: opts.port, username: opts.username, password: opts.password, privateKey: opts.privateKey, passphrase: opts.passphrase, readyTimeout: 30_000 });\r\n });\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Safety: dangerous command blocklist\r\n// ---------------------------------------------------------------------------\r\n\r\nconst BLOCKED_COMMANDS = [\r\n 'rm -rf /', 'rm -fr /', 'mkfs', 'dd if=', ':(){ :|:& };:',\r\n 'shutdown', 'halt', 'init 0', 'init 6',\r\n '> /dev/sda', 'mv /* /dev/null', 'chmod -R 000 /',\r\n];\r\n\r\nfunction assertSafeCommand(command: string): void {\r\n const lower = command.toLowerCase().trim();\r\n for (const blocked of BLOCKED_COMMANDS) {\r\n if (lower.includes(blocked)) {\r\n throw new Error(`Blocked dangerous command pattern: \"${blocked}\"`);\r\n }\r\n }\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Tool definitions\r\n// ---------------------------------------------------------------------------\r\n\r\nconst TOOLS = [\r\n {\r\n name: 'list-servers',\r\n description: 'List all SSH servers you have access to. Returns id, name, hostname, and tags for each server.',\r\n inputSchema: { type: 'object' as const, properties: {}, required: [] },\r\n },\r\n {\r\n name: 'server-status',\r\n description: 'Get server status including uptime, disk usage, memory, and load average.',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n serverId: { type: 'string', description: 'UUID of the SSH server' },\r\n },\r\n required: ['serverId'],\r\n },\r\n },\r\n {\r\n name: 'ssh-execute',\r\n description: 'Execute a shell command on a remote server via SSH. Some dangerous commands are blocked for safety.',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n serverId: { type: 'string', description: 'UUID of the SSH server' },\r\n command: { type: 'string', description: 'Shell command to execute' },\r\n timeout: { type: 'number', description: 'Timeout in milliseconds (default: 60000)' },\r\n },\r\n required: ['serverId', 'command'],\r\n },\r\n },\r\n {\r\n name: 'server-reboot',\r\n description: 'Reboot a remote server. This will cause downtime. The server will be unavailable until it restarts.',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n serverId: { type: 'string', description: 'UUID of the SSH server to reboot' },\r\n },\r\n required: ['serverId'],\r\n },\r\n },\r\n {\r\n name: 'server-restart-service',\r\n description: 'Restart a systemd service on a remote server using systemctl restart.',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n serverId: { type: 'string', description: 'UUID of the SSH server' },\r\n serviceName: { type: 'string', description: 'Name of the systemd service (e.g. nginx, docker, lsws)' },\r\n },\r\n required: ['serverId', 'serviceName'],\r\n },\r\n },\r\n {\r\n name: 'sftp-list',\r\n description: 'List files and directories at a given path on a remote server via SFTP.',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n serverId: { type: 'string', description: 'UUID of the SSH server' },\r\n path: { type: 'string', description: 'Directory path to list (default: /)' },\r\n },\r\n required: ['serverId'],\r\n },\r\n },\r\n {\r\n name: 'sftp-read',\r\n description: 'Read the contents of a text file on a remote server via SFTP (max 1MB).',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n serverId: { type: 'string', description: 'UUID of the SSH server' },\r\n path: { type: 'string', description: 'File path to read' },\r\n },\r\n required: ['serverId', 'path'],\r\n },\r\n },\r\n {\r\n name: 'sftp-write',\r\n description: 'Write content to a file on a remote server via SFTP. Protected system paths are blocked.',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n serverId: { type: 'string', description: 'UUID of the SSH server' },\r\n path: { type: 'string', description: 'File path to write' },\r\n content: { type: 'string', description: 'File content to write' },\r\n },\r\n required: ['serverId', 'path', 'content'],\r\n },\r\n },\r\n {\r\n name: 'sftp-delete',\r\n description: 'Delete a file or empty directory on a remote server via SFTP. Protected system paths are blocked.',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n serverId: { type: 'string', description: 'UUID of the SSH server' },\r\n path: { type: 'string', description: 'File or directory path to delete' },\r\n },\r\n required: ['serverId', 'path'],\r\n },\r\n },\r\n {\r\n name: 'docker-list',\r\n description: 'List all Docker containers on a remote server (running and stopped).',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n serverId: { type: 'string', description: 'UUID of the SSH server' },\r\n },\r\n required: ['serverId'],\r\n },\r\n },\r\n {\r\n name: 'docker-action',\r\n description: 'Perform an action on a Docker container: start, stop, restart, or remove.',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n serverId: { type: 'string', description: 'UUID of the SSH server' },\r\n containerName: { type: 'string', description: 'Container name or ID' },\r\n action: { type: 'string', enum: ['start', 'stop', 'restart', 'remove'], description: 'Action to perform' },\r\n },\r\n required: ['serverId', 'containerName', 'action'],\r\n },\r\n },\r\n {\r\n name: 'docker-logs',\r\n description: 'Get recent logs from a Docker container.',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n serverId: { type: 'string', description: 'UUID of the SSH server' },\r\n containerName: { type: 'string', description: 'Container name or ID' },\r\n lines: { type: 'number', description: 'Number of log lines to retrieve (default: 100)' },\r\n },\r\n required: ['serverId', 'containerName'],\r\n },\r\n },\r\n {\r\n name: 'env-list',\r\n description: 'List all stored environment configurations (app name, environment, description).',\r\n inputSchema: { type: 'object' as const, properties: {}, required: [] },\r\n },\r\n {\r\n name: 'env-get',\r\n description: 'Retrieve the decrypted .env content for a specific app and environment.',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n appName: { type: 'string', description: 'Application name (e.g. backoffice, api, web)' },\r\n environment: { type: 'string', description: 'Environment name (e.g. production, staging, development)' },\r\n },\r\n required: ['appName', 'environment'],\r\n },\r\n },\r\n {\r\n name: 'env-store',\r\n description: 'Store or update an encrypted .env configuration for an app and environment.',\r\n inputSchema: {\r\n type: 'object' as const,\r\n properties: {\r\n appName: { type: 'string', description: 'Application name (e.g. backoffice, api, web)' },\r\n environment: { type: 'string', description: 'Environment name (e.g. production, staging, development)' },\r\n content: { type: 'string', description: 'The .env file content to store' },\r\n description: { type: 'string', description: 'Optional description' },\r\n },\r\n required: ['appName', 'environment', 'content'],\r\n },\r\n },\r\n];\r\n\r\n// ---------------------------------------------------------------------------\r\n// MCP Server\r\n// ---------------------------------------------------------------------------\r\n\r\nconst server = new Server(\r\n { name: 'mg-dashboard-mcp', version: '1.0.0' },\r\n { capabilities: { tools: {} } },\r\n);\r\n\r\nserver.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));\r\n\r\nserver.setRequestHandler(CallToolRequestSchema, async (request) => {\r\n if (!authContext) {\r\n return { content: [{ type: 'text', text: 'Error: not authenticated' }] };\r\n }\r\n\r\n const { name, arguments: toolArgs } = request.params;\r\n const a = (toolArgs || {}) as Record<string, unknown>;\r\n\r\n try {\r\n switch (name) {\r\n // ----- Servers -----\r\n case 'list-servers': {\r\n let query = supabase\r\n .from('ssh_server')\r\n .select('id, name, hostname, port, username, tags, hosted_by, created_at')\r\n .order('name');\r\n\r\n if (authContext.allowedServerIds !== null) {\r\n query = query.in('id', authContext.allowedServerIds);\r\n }\r\n\r\n const { data, error } = await query;\r\n if (error) throw new Error(error.message);\r\n\r\n const lines = (data || []).map(s => {\r\n const tags = Array.isArray(s.tags) ? (s.tags as string[]).join(', ') : '';\r\n return `${s.id} ${s.name} ${s.hostname}:${s.port} ${s.username} [${tags}] ${s.hosted_by || ''}`;\r\n });\r\n\r\n return { content: [{ type: 'text', text: lines.length ? lines.join('\\n') : 'No servers found' }] };\r\n }\r\n\r\n case 'server-status': {\r\n const conn = await getServerConnection(String(a.serverId));\r\n const cmd = 'echo \"=== UPTIME ===\" && uptime && echo \"=== DISK ===\" && df -h --total && echo \"=== MEMORY ===\" && free -h && echo \"=== LOAD ===\" && cat /proc/loadavg';\r\n const result = await sshExec(conn, cmd);\r\n const output = result.exitCode === 0 ? result.stdout : `Exit ${result.exitCode}\\n${result.stdout}\\n${result.stderr}`;\r\n return { content: [{ type: 'text', text: output }] };\r\n }\r\n\r\n // ----- SSH -----\r\n case 'ssh-execute': {\r\n const command = String(a.command);\r\n assertSafeCommand(command);\r\n const conn = await getServerConnection(String(a.serverId));\r\n if (a.timeout) conn.timeout = Number(a.timeout);\r\n const result = await sshExec(conn, command);\r\n const output = [`Exit code: ${result.exitCode}`];\r\n if (result.stdout) output.push(`--- stdout ---\\n${result.stdout}`);\r\n if (result.stderr) output.push(`--- stderr ---\\n${result.stderr}`);\r\n return { content: [{ type: 'text', text: output.join('\\n') }] };\r\n }\r\n\r\n case 'server-reboot': {\r\n const conn = await getServerConnection(String(a.serverId));\r\n const result = await sshExec(conn, 'sudo reboot');\r\n return { content: [{ type: 'text', text: result.exitCode === 0 ? 'Reboot command sent. Server will be unavailable shortly.' : `Reboot failed: ${result.stderr}` }] };\r\n }\r\n\r\n case 'server-restart-service': {\r\n const service = String(a.serviceName).replace(/[^a-zA-Z0-9._@-]/g, '');\r\n const conn = await getServerConnection(String(a.serverId));\r\n const result = await sshExec(conn, `sudo systemctl restart ${service}`);\r\n if (result.exitCode === 0) {\r\n const status = await sshExec(conn, `sudo systemctl is-active ${service}`);\r\n return { content: [{ type: 'text', text: `Service \"${service}\" restarted. Status: ${status.stdout.trim()}` }] };\r\n }\r\n return { content: [{ type: 'text', text: `Failed to restart \"${service}\": ${result.stderr}` }] };\r\n }\r\n\r\n // ----- SFTP -----\r\n case 'sftp-list': {\r\n const conn = await getServerConnection(String(a.serverId));\r\n const listing = await sftpReaddir(conn, String(a.path || '/'));\r\n return { content: [{ type: 'text', text: listing }] };\r\n }\r\n\r\n case 'sftp-read': {\r\n const conn = await getServerConnection(String(a.serverId));\r\n const content = await sftpRead(conn, String(a.path));\r\n return { content: [{ type: 'text', text: content }] };\r\n }\r\n\r\n case 'sftp-write': {\r\n const conn = await getServerConnection(String(a.serverId));\r\n const result = await sftpWrite(conn, String(a.path), String(a.content));\r\n return { content: [{ type: 'text', text: result }] };\r\n }\r\n\r\n case 'sftp-delete': {\r\n const conn = await getServerConnection(String(a.serverId));\r\n const result = await sftpDelete(conn, String(a.path));\r\n return { content: [{ type: 'text', text: result }] };\r\n }\r\n\r\n // ----- Docker -----\r\n case 'docker-list': {\r\n const conn = await getServerConnection(String(a.serverId));\r\n const result = await sshExec(conn, 'docker ps -a --format \"table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}\"');\r\n return { content: [{ type: 'text', text: result.exitCode === 0 ? result.stdout : `Error: ${result.stderr}` }] };\r\n }\r\n\r\n case 'docker-action': {\r\n const container = String(a.containerName).replace(/[^a-zA-Z0-9._-]/g, '');\r\n const action = String(a.action);\r\n if (!['start', 'stop', 'restart', 'remove'].includes(action)) {\r\n throw new Error(`Invalid action: ${action}. Use start, stop, restart, or remove.`);\r\n }\r\n const conn = await getServerConnection(String(a.serverId));\r\n const dockerCmd = action === 'remove' ? `docker rm -f ${container}` : `docker ${action} ${container}`;\r\n const result = await sshExec(conn, dockerCmd);\r\n return { content: [{ type: 'text', text: result.exitCode === 0 ? `Container \"${container}\" ${action}ed successfully` : `Error: ${result.stderr}` }] };\r\n }\r\n\r\n case 'docker-logs': {\r\n const container = String(a.containerName).replace(/[^a-zA-Z0-9._-]/g, '');\r\n const lines = Number(a.lines) || 100;\r\n const conn = await getServerConnection(String(a.serverId));\r\n const result = await sshExec(conn, `docker logs --tail ${lines} ${container} 2>&1`);\r\n return { content: [{ type: 'text', text: result.exitCode === 0 ? result.stdout : `Error: ${result.stderr}` }] };\r\n }\r\n\r\n // ----- Env Config -----\r\n case 'env-list': {\r\n const { data, error } = await supabase\r\n .from('env_config')\r\n .select('id, app_name, environment, description, updated_at')\r\n .order('app_name')\r\n .order('environment');\r\n\r\n if (error) throw new Error(error.message);\r\n const lines = (data || []).map(e =>\r\n `${e.app_name}/${e.environment} ${e.description || ''} (updated: ${e.updated_at})`\r\n );\r\n return { content: [{ type: 'text', text: lines.length ? lines.join('\\n') : 'No environment configs stored' }] };\r\n }\r\n\r\n case 'env-get': {\r\n const { data, error } = await supabase\r\n .from('env_config')\r\n .select('env_data_encrypted')\r\n .eq('app_name', String(a.appName))\r\n .eq('environment', String(a.environment))\r\n .single();\r\n\r\n if (error || !data) throw new Error(`Env config not found: ${a.appName}/${a.environment}`);\r\n const decrypted = decrypt(data.env_data_encrypted);\r\n return { content: [{ type: 'text', text: decrypted }] };\r\n }\r\n\r\n case 'env-store': {\r\n const appName = String(a.appName);\r\n const environment = String(a.environment);\r\n const encrypted = encrypt(String(a.content));\r\n\r\n const { data: existing } = await supabase\r\n .from('env_config')\r\n .select('id')\r\n .eq('app_name', appName)\r\n .eq('environment', environment)\r\n .single();\r\n\r\n if (existing) {\r\n const { error } = await supabase\r\n .from('env_config')\r\n .update({\r\n env_data_encrypted: encrypted,\r\n description: a.description ? String(a.description) : undefined,\r\n updated_by: authContext.userId,\r\n updated_at: new Date().toISOString(),\r\n })\r\n .eq('id', existing.id);\r\n if (error) throw new Error(error.message);\r\n return { content: [{ type: 'text', text: `Updated env config: ${appName}/${environment}` }] };\r\n }\r\n\r\n const { error } = await supabase.from('env_config').insert({\r\n app_name: appName,\r\n environment,\r\n env_data_encrypted: encrypted,\r\n description: a.description ? String(a.description) : null,\r\n created_by: authContext.userId,\r\n updated_by: authContext.userId,\r\n });\r\n if (error) throw new Error(error.message);\r\n return { content: [{ type: 'text', text: `Stored env config: ${appName}/${environment}` }] };\r\n }\r\n\r\n default:\r\n return { content: [{ type: 'text', text: `Unknown tool: ${name}` }] };\r\n }\r\n } catch (err) {\r\n const message = err instanceof Error ? err.message : String(err);\r\n return { content: [{ type: 'text', text: `Error: ${message}` }] };\r\n }\r\n});\r\n\r\n// ---------------------------------------------------------------------------\r\n// Main\r\n// ---------------------------------------------------------------------------\r\n\r\nasync function main() {\r\n console.error('Starting MG Dashboard MCP Server...');\r\n\r\n authContext = await validateApiKey(apiKey!);\r\n if (!authContext) {\r\n console.error('API key validation failed');\r\n process.exit(1);\r\n }\r\n\r\n console.error('API key validated. Starting stdio transport...');\r\n\r\n const transport = new StdioServerTransport();\r\n await server.connect(transport);\r\n\r\n console.error('MCP Server ready. Tools available: ' + TOOLS.map(t => t.name).join(', '));\r\n}\r\n\r\nmain().catch((err) => {\r\n console.error('Fatal error:', err);\r\n process.exit(1);\r\n});\r\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mgsoftwarebv/mg-dashboard-mcp",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "MCP Server for MG Dashboard - SSH, SFTP, Docker, and environment config tools for Cursor",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"mg-dashboard-mcp": "dist/index.js"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "tsup",
|
|
12
|
+
"dev": "tsup --watch",
|
|
13
|
+
"start": "node dist/index.js",
|
|
14
|
+
"typecheck": "tsc --noEmit"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"mcp",
|
|
18
|
+
"dashboard",
|
|
19
|
+
"ssh",
|
|
20
|
+
"sftp",
|
|
21
|
+
"docker",
|
|
22
|
+
"cursor",
|
|
23
|
+
"mg-software"
|
|
24
|
+
],
|
|
25
|
+
"author": "MG Software B.V. <info@mgsoftware.nl> (https://www.mgsoftware.nl)",
|
|
26
|
+
"license": "MIT",
|
|
27
|
+
"homepage": "https://www.mgsoftware.nl",
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@modelcontextprotocol/sdk": "^1.0.4",
|
|
30
|
+
"@supabase/supabase-js": "^2.50.0",
|
|
31
|
+
"ssh2": "^1.15.0"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@types/node": "^20.0.0",
|
|
35
|
+
"@types/ssh2": "^1.15.0",
|
|
36
|
+
"tsup": "^8.0.0",
|
|
37
|
+
"typescript": "^5.0.0"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist"
|
|
41
|
+
],
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public",
|
|
44
|
+
"registry": "https://registry.npmjs.org/"
|
|
45
|
+
}
|
|
46
|
+
}
|