@usex/mikrotik-mcp 6.13.0 → 6.14.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/package.json +1 -1
- package/schemas/devtools-manifest.json +1 -1
- package/schemas/tool-catalog.json +1 -1
- package/scripts/service.ts +561 -63
package/package.json
CHANGED
package/scripts/service.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
import { sleep, spawn } from "bun";
|
|
3
|
-
import { chmod, mkdir, readFile, rename, rmdir, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { chmod, lstat, mkdir, readFile, rename, rmdir, unlink, writeFile } from "node:fs/promises";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { dirname, join, resolve } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
@@ -50,53 +50,98 @@ export async function upgrade(io: UpgradeIO): Promise<string> {
|
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
/** Run host service-management commands as argv arrays, never through a shell. */
|
|
53
|
-
async function command(
|
|
53
|
+
async function command(
|
|
54
|
+
args: string[],
|
|
55
|
+
env = process.env,
|
|
56
|
+
visible = false,
|
|
57
|
+
/** Discard the child's stderr: for probes whose failure is an answer, not an error. */
|
|
58
|
+
quiet = false,
|
|
59
|
+
): Promise<string> {
|
|
54
60
|
const child = spawn(args, {
|
|
55
61
|
cwd: homedir(),
|
|
56
62
|
env,
|
|
57
63
|
stdout: visible ? "inherit" : "pipe",
|
|
58
|
-
stderr: "inherit",
|
|
64
|
+
stderr: quiet ? "ignore" : "inherit",
|
|
59
65
|
});
|
|
60
66
|
const output = visible ? "" : await new Response(child.stdout as ReadableStream).text();
|
|
61
67
|
if ((await child.exited) !== 0) throw new Error(`Command failed: ${args[0]} ${args[1] ?? ""}`);
|
|
62
68
|
return output.trim();
|
|
63
69
|
}
|
|
64
70
|
|
|
65
|
-
/**
|
|
66
|
-
|
|
71
|
+
/** Run a noisy command silently; show what it printed only when it fails. */
|
|
72
|
+
async function captured(args: string[], env = process.env): Promise<void> {
|
|
73
|
+
const child = spawn(args, { cwd: homedir(), env, stdout: "pipe", stderr: "pipe" });
|
|
74
|
+
const read = (stream: unknown): Promise<string> =>
|
|
75
|
+
stream ? new Response(stream as ReadableStream).text() : Promise.resolve("");
|
|
76
|
+
const [stdout, stderr] = await Promise.all([read(child.stdout), read(child.stderr)]);
|
|
77
|
+
if ((await child.exited) === 0) return;
|
|
78
|
+
const printed = `${stdout}${stderr}`.trim();
|
|
79
|
+
if (printed) console.warn(printed);
|
|
80
|
+
throw new Error(`Command failed: ${args[0]} ${args[1] ?? ""}`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** What a running server says about itself over MCP. Empty when it does not answer. */
|
|
84
|
+
export interface ServerProbe {
|
|
85
|
+
version?: string;
|
|
86
|
+
/** Number of tools in `tools/list`; requested only with `tools: true`. */
|
|
87
|
+
tools?: number;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** One JSON-RPC message from a plain-JSON or event-stream MCP response. */
|
|
91
|
+
async function rpcPayload(response: Response): Promise<any> {
|
|
92
|
+
const text = await response.text();
|
|
93
|
+
const payload = response.headers.get("content-type")?.includes("text/event-stream")
|
|
94
|
+
? text
|
|
95
|
+
.split("\n")
|
|
96
|
+
.find((line) => line.startsWith("data:"))
|
|
97
|
+
?.slice(5)
|
|
98
|
+
.trim()
|
|
99
|
+
: text;
|
|
100
|
+
return JSON.parse(payload ?? "null");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Ask the HTTP MCP server who it is — its real version, not just a listening port. */
|
|
104
|
+
export async function probe(
|
|
105
|
+
endpoint: string,
|
|
106
|
+
opts: { tools?: boolean } = {},
|
|
107
|
+
): Promise<ServerProbe> {
|
|
67
108
|
let session: string | null = null;
|
|
68
|
-
|
|
69
|
-
|
|
109
|
+
const post = (body: unknown, extra: Record<string, string> = {}): Promise<Response> =>
|
|
110
|
+
fetch(endpoint, {
|
|
70
111
|
method: "POST",
|
|
71
112
|
headers: {
|
|
72
113
|
"Content-Type": "application/json",
|
|
73
114
|
Accept: "application/json, text/event-stream",
|
|
115
|
+
...extra,
|
|
74
116
|
},
|
|
75
|
-
body: JSON.stringify(
|
|
76
|
-
jsonrpc: "2.0",
|
|
77
|
-
id: 1,
|
|
78
|
-
method: "initialize",
|
|
79
|
-
params: {
|
|
80
|
-
protocolVersion: "2025-03-26",
|
|
81
|
-
capabilities: {},
|
|
82
|
-
clientInfo: { name: "mikrotik-mcp-upgrade", version: "1.0.0" },
|
|
83
|
-
},
|
|
84
|
-
}),
|
|
117
|
+
body: JSON.stringify(body),
|
|
85
118
|
signal: AbortSignal.timeout(2000),
|
|
86
119
|
});
|
|
120
|
+
try {
|
|
121
|
+
const response = await post({
|
|
122
|
+
jsonrpc: "2.0",
|
|
123
|
+
id: 1,
|
|
124
|
+
method: "initialize",
|
|
125
|
+
params: {
|
|
126
|
+
protocolVersion: "2025-03-26",
|
|
127
|
+
capabilities: {},
|
|
128
|
+
clientInfo: { name: "mikrotik-mcp-upgrade", version: "1.0.0" },
|
|
129
|
+
},
|
|
130
|
+
});
|
|
87
131
|
session = response.headers.get("mcp-session-id");
|
|
88
|
-
if (!response.ok) return
|
|
89
|
-
const
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
132
|
+
if (!response.ok) return {};
|
|
133
|
+
const version = (await rpcPayload(response))?.result?.serverInfo?.version;
|
|
134
|
+
const found: ServerProbe = typeof version === "string" ? { version } : {};
|
|
135
|
+
if (opts.tools && session) {
|
|
136
|
+
const withSession = { "mcp-session-id": session };
|
|
137
|
+
await post({ jsonrpc: "2.0", method: "notifications/initialized" }, withSession);
|
|
138
|
+
const listed = await post({ jsonrpc: "2.0", id: 2, method: "tools/list" }, withSession);
|
|
139
|
+
const tools = listed.ok ? (await rpcPayload(listed))?.result?.tools : undefined;
|
|
140
|
+
if (Array.isArray(tools)) found.tools = tools.length;
|
|
141
|
+
}
|
|
142
|
+
return found;
|
|
98
143
|
} catch {
|
|
99
|
-
return
|
|
144
|
+
return {};
|
|
100
145
|
} finally {
|
|
101
146
|
if (session)
|
|
102
147
|
await fetch(endpoint, {
|
|
@@ -107,6 +152,11 @@ export async function ready(endpoint: string, version: string): Promise<boolean>
|
|
|
107
152
|
}
|
|
108
153
|
}
|
|
109
154
|
|
|
155
|
+
/** Confirm the actual HTTP MCP server version, not just a listening port. */
|
|
156
|
+
export async function ready(endpoint: string, version: string): Promise<boolean> {
|
|
157
|
+
return (await probe(endpoint)).version === version;
|
|
158
|
+
}
|
|
159
|
+
|
|
110
160
|
/** Accept only supported OSes and bounded, distinct local listener ports. */
|
|
111
161
|
export function validatePorts(mcp: number, dashboard: number): void {
|
|
112
162
|
if (
|
|
@@ -193,6 +243,355 @@ async function save(path: string, content: string, mode = 0o600): Promise<void>
|
|
|
193
243
|
}
|
|
194
244
|
}
|
|
195
245
|
|
|
246
|
+
// ── Terminal output ─────────────────────────────────────────────────────────
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* figlet "Small" rendering of "MikroTik MCP" — the banner `src/cli-logo.ts`
|
|
250
|
+
* draws when the server starts. It is embedded as text because this file is
|
|
251
|
+
* also copied to `~/.mikrotik-mcp/service/manager.ts` and run from there with
|
|
252
|
+
* no `node_modules`, so it cannot import figlet. A test keeps it identical to
|
|
253
|
+
* figlet's output.
|
|
254
|
+
*/
|
|
255
|
+
export const BANNER: readonly string[] = [
|
|
256
|
+
" __ __ _ _ _____ _ _ __ __ ___ ___ ",
|
|
257
|
+
" | \\/ (_) |___ _ __|_ _(_) |__ | \\/ |/ __| _ \\",
|
|
258
|
+
" | |\\/| | | / / '_/ _ \\| | | | / / | |\\/| | (__| _/",
|
|
259
|
+
" |_| |_|_|_\\_\\_| \\___/|_| |_|_\\_\\ |_| |_|\\___|_| ",
|
|
260
|
+
];
|
|
261
|
+
/** Brand gradient: violet → sky → teal, as in the server banner and dashboard. */
|
|
262
|
+
const BRAND: readonly (readonly [number, number, number])[] = [
|
|
263
|
+
[157, 123, 255],
|
|
264
|
+
[50, 145, 255],
|
|
265
|
+
[45, 212, 191],
|
|
266
|
+
];
|
|
267
|
+
const ESC = "\x1B[";
|
|
268
|
+
const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g");
|
|
269
|
+
/** Printed width of a string, without colour codes. */
|
|
270
|
+
const width = (text: string): number => text.replace(ANSI, "").length;
|
|
271
|
+
|
|
272
|
+
/** Colour helpers that turn into plain text when colour is off. */
|
|
273
|
+
function palette(on: boolean) {
|
|
274
|
+
const wrap =
|
|
275
|
+
(code: string) =>
|
|
276
|
+
(text: string): string =>
|
|
277
|
+
on ? `${ESC}${code}m${text}${ESC}0m` : text;
|
|
278
|
+
return {
|
|
279
|
+
on,
|
|
280
|
+
bold: wrap("1"),
|
|
281
|
+
dim: wrap("90"),
|
|
282
|
+
ok: wrap("38;2;45;212;191"),
|
|
283
|
+
bad: wrap("38;2;255;107;107"),
|
|
284
|
+
warn: wrap("38;2;245;166;35"),
|
|
285
|
+
sky: wrap("38;2;50;145;255"),
|
|
286
|
+
violet: wrap("38;2;157;123;255"),
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Colour only for a person at a terminal; `NO_COLOR` always wins. */
|
|
291
|
+
const useColor = (): boolean => process.stderr.isTTY === true && !process.env.NO_COLOR;
|
|
292
|
+
|
|
293
|
+
/** One line coloured left to right across the brand gradient. */
|
|
294
|
+
function gradient(line: string): string {
|
|
295
|
+
const last = Math.max(1, line.length - 1);
|
|
296
|
+
let out = "";
|
|
297
|
+
for (let i = 0; i < line.length; i++) {
|
|
298
|
+
const at = (i / last) * (BRAND.length - 1);
|
|
299
|
+
const from = BRAND[Math.floor(at)];
|
|
300
|
+
const to = BRAND[Math.min(BRAND.length - 1, Math.floor(at) + 1)];
|
|
301
|
+
const mix = at - Math.floor(at);
|
|
302
|
+
const [r, g, b] = from.map((channel, k) => Math.round(channel + (to[k] - channel) * mix));
|
|
303
|
+
out += line[i] === " " ? " " : `${ESC}38;2;${r};${g};${b}m${line[i]}`;
|
|
304
|
+
}
|
|
305
|
+
return `${out}${ESC}0m`;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** The banner with a one-line caption under it. */
|
|
309
|
+
export function banner(caption: string, on: boolean): string {
|
|
310
|
+
const c = palette(on);
|
|
311
|
+
const art = BANNER.map((line) => (on ? gradient(line) : line)).join("\n");
|
|
312
|
+
return `\n${art}\n\n ${c.dim("Shared service")} ${c.dim("·")} ${c.bold(caption)}`;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
type Rows = [label: string, value: string][];
|
|
316
|
+
|
|
317
|
+
/** The rows of a panel as aligned `label value` lines. */
|
|
318
|
+
function panelLines(rows: Rows, c: ReturnType<typeof palette>): string[] {
|
|
319
|
+
const labelWidth = Math.max(...rows.map(([label]) => label.length));
|
|
320
|
+
return rows.map(([label, value]) => `${c.dim(label.padEnd(labelWidth))} ${value}`);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Inner width a panel needs for its title and rows. */
|
|
324
|
+
function panelWidth(title: string, rows: Rows): number {
|
|
325
|
+
return Math.max(title.length + 2, ...panelLines(rows, palette(false)).map(width));
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** A titled box of `label value` rows, at least `min` wide so stacked panels line up. */
|
|
329
|
+
export function panel(title: string, rows: Rows, on: boolean, min = 0): string {
|
|
330
|
+
const c = palette(on);
|
|
331
|
+
const lines = panelLines(rows, c);
|
|
332
|
+
const inner = Math.max(min, panelWidth(title, rows));
|
|
333
|
+
const top = `${c.dim("╭─")} ${c.bold(title)} ${c.dim(`${"─".repeat(inner - title.length - 1)}╮`)}`;
|
|
334
|
+
const body = lines.map(
|
|
335
|
+
(line) => `${c.dim("│")} ${line}${" ".repeat(inner - width(line))} ${c.dim("│")}`,
|
|
336
|
+
);
|
|
337
|
+
return [top, ...body, c.dim(`╰${"─".repeat(inner + 2)}╯`)].map((l) => ` ${l}`).join("\n");
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** `ps` elapsed time (`[[dd-]hh:]mm:ss`) as "1d 2h", "2h 3m" or "3m 4s". */
|
|
341
|
+
export function uptime(etime: string): string | undefined {
|
|
342
|
+
const match = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)$/.exec(etime.trim());
|
|
343
|
+
if (!match) return undefined;
|
|
344
|
+
const [days, hours, minutes, seconds] = match.slice(1).map((part) => Number(part ?? 0));
|
|
345
|
+
if (days) return `${days}d ${hours}h`;
|
|
346
|
+
if (hours) return `${hours}h ${minutes}m`;
|
|
347
|
+
return `${minutes}m ${seconds}s`;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** `state` and `pid` from `launchctl print gui/<uid>/<label>`. */
|
|
351
|
+
export function parseLaunchctl(text: string): { running: boolean; pid?: number } {
|
|
352
|
+
const pid = /^\s*pid = (\d+)/m.exec(text);
|
|
353
|
+
return { running: /^\s*state = running/m.test(text), ...(pid ? { pid: Number(pid[1]) } : {}) };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** `ActiveState` and `MainPID` from `systemctl --user show`. */
|
|
357
|
+
export function parseSystemd(text: string): { running: boolean; pid?: number } {
|
|
358
|
+
const pid = Number(/^MainPID=(\d+)/m.exec(text)?.[1] ?? 0);
|
|
359
|
+
return { running: /^ActiveState=active$/m.test(text), ...(pid ? { pid } : {}) };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Everything `status` shows. A missing field means "could not find out". */
|
|
363
|
+
export interface ServiceReport {
|
|
364
|
+
platform: Platform;
|
|
365
|
+
running: boolean;
|
|
366
|
+
pid?: number;
|
|
367
|
+
uptime?: string;
|
|
368
|
+
/** Version of the files on disk. */
|
|
369
|
+
installed?: string;
|
|
370
|
+
/** Version the running server reports over MCP. */
|
|
371
|
+
serving?: string;
|
|
372
|
+
/** Newest version on the npm registry. */
|
|
373
|
+
latest?: string;
|
|
374
|
+
tools?: number;
|
|
375
|
+
mcp: string;
|
|
376
|
+
dashboard: string;
|
|
377
|
+
dashboardUp: boolean;
|
|
378
|
+
config: string;
|
|
379
|
+
devices?: { total: number; enabled: number };
|
|
380
|
+
data: string;
|
|
381
|
+
logs: string;
|
|
382
|
+
commands: string;
|
|
383
|
+
bun: string;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const SUPERVISOR: Record<Platform, string> = {
|
|
387
|
+
darwin: "launchd LaunchAgent · starts at login · restarts if it stops",
|
|
388
|
+
linux: "systemd user unit · restarts after exit",
|
|
389
|
+
win32: "Task Scheduler task · starts at login",
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
/** Collect the facts for `status`. Every probe is bounded and may come back empty. */
|
|
393
|
+
async function inspect(state: ServiceState): Promise<ServiceReport> {
|
|
394
|
+
const quietly = <T>(work: Promise<T>): Promise<T | undefined> => work.catch(() => undefined);
|
|
395
|
+
const mcp = `http://127.0.0.1:${state.port}/mcp`;
|
|
396
|
+
const dashboard = `http://127.0.0.1:${state.dashboardPort}`;
|
|
397
|
+
const native = async (): Promise<{ running: boolean; pid?: number }> => {
|
|
398
|
+
if (state.platform === "darwin")
|
|
399
|
+
return parseLaunchctl(
|
|
400
|
+
await command(
|
|
401
|
+
["/bin/launchctl", "print", `gui/${process.getuid!()}/${LABEL}`],
|
|
402
|
+
process.env,
|
|
403
|
+
false,
|
|
404
|
+
true,
|
|
405
|
+
),
|
|
406
|
+
);
|
|
407
|
+
if (state.platform === "linux")
|
|
408
|
+
return parseSystemd(
|
|
409
|
+
await command(
|
|
410
|
+
["systemctl", "--user", "show", UNIT, "-p", "ActiveState", "-p", "MainPID"],
|
|
411
|
+
process.env,
|
|
412
|
+
false,
|
|
413
|
+
true,
|
|
414
|
+
),
|
|
415
|
+
);
|
|
416
|
+
return {
|
|
417
|
+
running: (await powershell(`(Get-ScheduledTask -TaskName ${psQuote(TASK)}).State`)).includes(
|
|
418
|
+
"Running",
|
|
419
|
+
),
|
|
420
|
+
};
|
|
421
|
+
};
|
|
422
|
+
const logs = async (): Promise<string> => {
|
|
423
|
+
if (state.platform === "linux") return `journalctl --user -u ${UNIT}`;
|
|
424
|
+
if (state.platform === "win32") return "Task Scheduler › MikroTik MCP › Last Run Result";
|
|
425
|
+
const plist = (await optionalFile(nativeFile("darwin"))) ?? "";
|
|
426
|
+
return (
|
|
427
|
+
/<key>StandardErrorPath<\/key>\s*<string>([^<]+)<\/string>/.exec(plist)?.[1] ??
|
|
428
|
+
"LaunchAgent StandardErrorPath / StandardOutPath"
|
|
429
|
+
);
|
|
430
|
+
};
|
|
431
|
+
const devices = async (): Promise<{ total: number; enabled: number } | undefined> => {
|
|
432
|
+
const all = Object.values(
|
|
433
|
+
(JSON.parse((await optionalFile(state.config)) ?? "{}").devices ?? {}) as Record<
|
|
434
|
+
string,
|
|
435
|
+
{ disabled?: boolean }
|
|
436
|
+
>,
|
|
437
|
+
);
|
|
438
|
+
return { total: all.length, enabled: all.filter((device) => !device?.disabled).length };
|
|
439
|
+
};
|
|
440
|
+
const latest = async (): Promise<string | undefined> => {
|
|
441
|
+
const response = await fetch(
|
|
442
|
+
`https://registry.npmjs.org/${PACKAGE.replace("/", "%2f")}/latest`,
|
|
443
|
+
{
|
|
444
|
+
signal: AbortSignal.timeout(2500),
|
|
445
|
+
},
|
|
446
|
+
);
|
|
447
|
+
const version = response.ok
|
|
448
|
+
? ((await response.json()) as { version?: unknown })?.version
|
|
449
|
+
: undefined;
|
|
450
|
+
return typeof version === "string" ? version : undefined;
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
const [process_, installed, served, dashboardUp, newest, deviceCount, logPath] =
|
|
454
|
+
await Promise.all([
|
|
455
|
+
quietly(native()),
|
|
456
|
+
quietly(command([state.bun, state.cli, "--version"], process.env, false, true)),
|
|
457
|
+
probe(mcp, { tools: true }),
|
|
458
|
+
quietly(
|
|
459
|
+
(async () =>
|
|
460
|
+
(await fetch(dashboard, { signal: AbortSignal.timeout(2000) })).status < 500)(),
|
|
461
|
+
),
|
|
462
|
+
quietly(latest()),
|
|
463
|
+
quietly(devices()),
|
|
464
|
+
quietly(logs()),
|
|
465
|
+
]);
|
|
466
|
+
const pid = process_?.pid;
|
|
467
|
+
const elapsed =
|
|
468
|
+
pid && state.platform !== "win32"
|
|
469
|
+
? await quietly(
|
|
470
|
+
command(["/bin/ps", "-o", "etime=", "-p", String(pid)], process.env, false, true),
|
|
471
|
+
)
|
|
472
|
+
: undefined;
|
|
473
|
+
return {
|
|
474
|
+
platform: state.platform,
|
|
475
|
+
running: process_?.running ?? false,
|
|
476
|
+
pid,
|
|
477
|
+
uptime: elapsed ? uptime(elapsed) : undefined,
|
|
478
|
+
installed: installed || undefined,
|
|
479
|
+
serving: served.version,
|
|
480
|
+
latest: newest,
|
|
481
|
+
tools: served.tools,
|
|
482
|
+
mcp,
|
|
483
|
+
dashboard,
|
|
484
|
+
dashboardUp: dashboardUp === true,
|
|
485
|
+
config: state.config,
|
|
486
|
+
devices: deviceCount,
|
|
487
|
+
data: state.cwd,
|
|
488
|
+
logs: logPath ?? "",
|
|
489
|
+
commands: join(state.installRoot, "bin"),
|
|
490
|
+
bun: `${process.versions.bun ?? "?"} ${state.bun}`,
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** Compare dotted versions numerically: negative when `a` is older than `b`. */
|
|
495
|
+
function compareVersions(a: string, b: string): number {
|
|
496
|
+
const parts = (v: string): number[] =>
|
|
497
|
+
v.split(/[.-]/).map((part) => Number.parseInt(part, 10) || 0);
|
|
498
|
+
const [x, y] = [parts(a), parts(b)];
|
|
499
|
+
for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) - (y[i] ?? 0);
|
|
500
|
+
return 0;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** The `status` screen: what runs, which version, where it answers, where things live. */
|
|
504
|
+
export function renderStatus(report: ServiceReport, on: boolean): string {
|
|
505
|
+
const c = palette(on);
|
|
506
|
+
const home = homedir();
|
|
507
|
+
const tidy = (path: string): string =>
|
|
508
|
+
home && path.startsWith(home) ? `~${path.slice(home.length)}` : path;
|
|
509
|
+
const answering = report.serving !== undefined;
|
|
510
|
+
const advice: string[] = [];
|
|
511
|
+
|
|
512
|
+
const stateLine = report.running
|
|
513
|
+
? `${c.ok("●")} ${c.bold("running")}${
|
|
514
|
+
report.pid
|
|
515
|
+
? c.dim(` pid ${report.pid}${report.uptime ? ` · up ${report.uptime}` : ""}`)
|
|
516
|
+
: ""
|
|
517
|
+
}`
|
|
518
|
+
: `${c.bad("○")} ${c.bold("stopped")}`;
|
|
519
|
+
if (!report.running)
|
|
520
|
+
advice.push(`${c.bad("✗")} The service is not running. Start it: mikrotik-mcp-service restart`);
|
|
521
|
+
else if (!answering)
|
|
522
|
+
advice.push(
|
|
523
|
+
`${c.warn("!")} The process runs but MCP does not answer yet. Check the logs below.`,
|
|
524
|
+
);
|
|
525
|
+
|
|
526
|
+
let versionLine = report.installed ? `${c.bold(report.installed)} installed` : c.dim("unknown");
|
|
527
|
+
if (answering) {
|
|
528
|
+
versionLine =
|
|
529
|
+
report.serving === report.installed
|
|
530
|
+
? `${c.bold(report.serving!)} ${c.dim("running and installed")}`
|
|
531
|
+
: `${c.warn(report.serving!)} running ${c.dim("·")} ${c.bold(report.installed ?? "?")} installed`;
|
|
532
|
+
if (report.installed && report.serving !== report.installed)
|
|
533
|
+
advice.push(
|
|
534
|
+
`${c.warn("!")} Version ${report.installed} is installed but ${report.serving} is still running. Apply it: mikrotik-mcp-service restart`,
|
|
535
|
+
);
|
|
536
|
+
}
|
|
537
|
+
let latestLine = c.dim("could not reach the npm registry");
|
|
538
|
+
if (report.latest) {
|
|
539
|
+
const behind = report.installed ? compareVersions(report.installed, report.latest) < 0 : false;
|
|
540
|
+
latestLine = behind
|
|
541
|
+
? `${c.warn(report.latest)} ${c.dim("available")}`
|
|
542
|
+
: `${report.latest} ${c.dim("· up to date")}`;
|
|
543
|
+
if (behind)
|
|
544
|
+
advice.push(
|
|
545
|
+
`${c.sky("↑")} Update available: ${report.installed} → ${report.latest}. Run: mikrotik-mcp-upgrade`,
|
|
546
|
+
);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
const mark = (up: boolean): string => (up ? c.ok("✓ answering") : c.bad("✗ no answer"));
|
|
550
|
+
const service: Rows = [
|
|
551
|
+
["State", stateLine],
|
|
552
|
+
["Supervisor", SUPERVISOR[report.platform]],
|
|
553
|
+
["Version", versionLine],
|
|
554
|
+
["Latest", latestLine],
|
|
555
|
+
];
|
|
556
|
+
if (report.tools !== undefined)
|
|
557
|
+
service.push(["Tools", `${report.tools} ${c.dim("in tools/list")}`]);
|
|
558
|
+
const deviceNote = report.devices
|
|
559
|
+
? c.dim(
|
|
560
|
+
` ${report.devices.total} device${report.devices.total === 1 ? "" : "s"}, ${report.devices.enabled} enabled`,
|
|
561
|
+
)
|
|
562
|
+
: "";
|
|
563
|
+
|
|
564
|
+
const urlWidth = Math.max(report.mcp.length, report.dashboard.length);
|
|
565
|
+
const endpoints: Rows = [
|
|
566
|
+
["MCP", `${c.sky(report.mcp.padEnd(urlWidth))} ${mark(answering)}`],
|
|
567
|
+
["Dashboard", `${c.sky(report.dashboard.padEnd(urlWidth))} ${mark(report.dashboardUp)}`],
|
|
568
|
+
];
|
|
569
|
+
const files: Rows = [
|
|
570
|
+
["Config", `${tidy(report.config)}${deviceNote}`],
|
|
571
|
+
["Data", tidy(report.data)],
|
|
572
|
+
["Logs", tidy(report.logs)],
|
|
573
|
+
["Commands", tidy(report.commands)],
|
|
574
|
+
["Bun", tidy(report.bun)],
|
|
575
|
+
];
|
|
576
|
+
// One width for all three, so the boxes stack as a single column.
|
|
577
|
+
const min = Math.max(
|
|
578
|
+
panelWidth("Service", service),
|
|
579
|
+
panelWidth("Endpoints", endpoints),
|
|
580
|
+
panelWidth("Files", files),
|
|
581
|
+
);
|
|
582
|
+
|
|
583
|
+
return [
|
|
584
|
+
banner("status", on),
|
|
585
|
+
panel("Service", service, on, min),
|
|
586
|
+
panel("Endpoints", endpoints, on, min),
|
|
587
|
+
panel("Files", files, on, min),
|
|
588
|
+
advice.length
|
|
589
|
+
? advice.map((line) => ` ${line}`).join("\n")
|
|
590
|
+
: ` ${c.ok("✓")} ${c.dim("Everything is in order.")}`,
|
|
591
|
+
` ${c.dim("Commands: mikrotik-mcp-upgrade · mikrotik-mcp-service restart | status | uninstall")}\n`,
|
|
592
|
+
].join("\n\n");
|
|
593
|
+
}
|
|
594
|
+
|
|
196
595
|
/** Adopt the existing macOS helper's LaunchAgent without replacing its environment or flags. */
|
|
197
596
|
async function adoptMac(): Promise<ServiceState | undefined> {
|
|
198
597
|
if (!(await optionalFile(nativeFile("darwin")))) return;
|
|
@@ -339,17 +738,49 @@ async function ensureStarted(state: ServiceState): Promise<void> {
|
|
|
339
738
|
}
|
|
340
739
|
}
|
|
341
740
|
|
|
741
|
+
const COMMANDS: [name: string, action: string][] = [
|
|
742
|
+
["mikrotik-mcp-service", ""],
|
|
743
|
+
["mikrotik-mcp-upgrade", "upgrade"],
|
|
744
|
+
];
|
|
745
|
+
/** First line of the POSIX wrapper; also how one of ours is recognised. */
|
|
746
|
+
const WRAPPER_HEAD = "#!/bin/sh\nexec ";
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* Remove the POSIX command wrappers this installer wrote into Bun's global bin
|
|
750
|
+
* directory, before `bun add --global` runs.
|
|
751
|
+
*
|
|
752
|
+
* The package declares bins with the same two names. Bun links them as
|
|
753
|
+
* symlinks and fails the whole install with `EEXIST` when a regular file is in
|
|
754
|
+
* the way — which left the new version on disk but the service not restarted.
|
|
755
|
+
* Only our own wrappers are removed: a symlink is Bun's link, and any other
|
|
756
|
+
* file is not ours to delete.
|
|
757
|
+
*/
|
|
758
|
+
export async function removeCommandWrappers(bin: string): Promise<void> {
|
|
759
|
+
if (process.platform === "win32") return; // `.cmd` wrappers do not collide with Bun's shims
|
|
760
|
+
for (const [name] of COMMANDS) {
|
|
761
|
+
const file = join(bin, name);
|
|
762
|
+
const info = await lstat(file).catch(() => null);
|
|
763
|
+
if (!info?.isFile()) continue;
|
|
764
|
+
const text = await readFile(file, "utf8").catch(() => "");
|
|
765
|
+
if (text.startsWith(WRAPPER_HEAD) && text.includes("manager.ts")) await unlink(file);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
342
769
|
/** Expose the same two commands on every OS, independent of the source checkout. */
|
|
343
|
-
async function installCommands(
|
|
770
|
+
export async function installCommands(
|
|
771
|
+
directory: string,
|
|
772
|
+
bun: string,
|
|
773
|
+
/** Skip the PATH reminder: for upgrade, which only repairs existing commands. */
|
|
774
|
+
quiet = false,
|
|
775
|
+
): Promise<void> {
|
|
344
776
|
const manager = join(directory, "manager.ts");
|
|
345
777
|
if (resolve(fileURLToPath(import.meta.url)) !== resolve(manager))
|
|
346
778
|
await save(manager, await readFile(fileURLToPath(import.meta.url), "utf8"));
|
|
347
779
|
const bin = (await command([bun, "pm", "-g", "bin"])).trim();
|
|
348
780
|
const shellQuote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
]) {
|
|
781
|
+
const wrapper = (action: string): string =>
|
|
782
|
+
`${WRAPPER_HEAD}${shellQuote(bun)} ${shellQuote(manager)} ${action} "$@"\n`;
|
|
783
|
+
for (const [name, action] of COMMANDS) {
|
|
353
784
|
if (process.platform === "win32") {
|
|
354
785
|
const quoted = [bun, manager]
|
|
355
786
|
.map((value) => windowsQuote(value).replaceAll("%", "%%"))
|
|
@@ -358,12 +789,13 @@ async function installCommands(directory: string, bun: string): Promise<void> {
|
|
|
358
789
|
join(bin, `${name}.cmd`),
|
|
359
790
|
`@echo off\r\nsetlocal DisableDelayedExpansion\r\n${quoted} ${action} %*\r\nexit /b %errorlevel%\r\n`,
|
|
360
791
|
);
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
792
|
+
continue;
|
|
793
|
+
}
|
|
794
|
+
// Bun already linked the package's own command here: keep it. Writing a
|
|
795
|
+
// file over it would make the next `bun add --global` fail with EEXIST.
|
|
796
|
+
const existing = await lstat(join(bin, name)).catch(() => null);
|
|
797
|
+
if (existing?.isSymbolicLink()) continue;
|
|
798
|
+
await save(join(bin, name), wrapper(action), 0o755);
|
|
367
799
|
}
|
|
368
800
|
// The first macOS-only helper lived here and can shadow Bun's bin on PATH.
|
|
369
801
|
if (process.platform === "darwin") {
|
|
@@ -373,11 +805,12 @@ async function installCommands(directory: string, bun: string): Promise<void> {
|
|
|
373
805
|
source?.includes('const LABEL = "dev.usestrict.mikrotik-mcp"') &&
|
|
374
806
|
source.includes("macOS only; no sudo.")
|
|
375
807
|
)
|
|
376
|
-
await save(legacy,
|
|
808
|
+
await save(legacy, wrapper("upgrade"), 0o755);
|
|
377
809
|
}
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
810
|
+
if (!quiet)
|
|
811
|
+
console.warn(
|
|
812
|
+
`Commands installed in ${bin}. If your terminal cannot find them, add this directory to PATH.`,
|
|
813
|
+
);
|
|
381
814
|
}
|
|
382
815
|
|
|
383
816
|
/** Verify the CLI and the live MCP version after service activation. */
|
|
@@ -528,8 +961,10 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
|
|
|
528
961
|
"dist",
|
|
529
962
|
"cli.js",
|
|
530
963
|
);
|
|
531
|
-
if (!(await optionalFile(cli)))
|
|
964
|
+
if (!(await optionalFile(cli))) {
|
|
965
|
+
await removeCommandWrappers(bin);
|
|
532
966
|
await command([bun, "add", "--global", `${PACKAGE}@latest`], process.env, true);
|
|
967
|
+
}
|
|
533
968
|
await command([bun, cli, "--version"]);
|
|
534
969
|
const args = [
|
|
535
970
|
"serve",
|
|
@@ -584,27 +1019,90 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
|
|
|
584
1019
|
"Service removed. Config, SSH keys and history were kept. Run install to enable it again.",
|
|
585
1020
|
);
|
|
586
1021
|
} else if (options.action === "upgrade") {
|
|
587
|
-
const
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
1022
|
+
const on = useColor();
|
|
1023
|
+
const c = palette(on);
|
|
1024
|
+
const say = (line: string): void => console.warn(` ${line}`);
|
|
1025
|
+
const mcp = `http://127.0.0.1:${state.port}/mcp`;
|
|
1026
|
+
console.warn(`${banner("upgrade", on)}\n`);
|
|
1027
|
+
const before = (await probe(mcp)).version;
|
|
1028
|
+
say(`${c.dim("•")} Running now ${before ? c.bold(before) : c.dim("not answering")}`);
|
|
1029
|
+
const started = Date.now();
|
|
1030
|
+
// How far the upgrade got, so a failure says what state the service is in.
|
|
1031
|
+
let stage: "install" | "restart" | "ready" = "install";
|
|
1032
|
+
try {
|
|
1033
|
+
const version = await upgrade({
|
|
1034
|
+
install: async () => {
|
|
1035
|
+
say(`${c.sky("◆")} Installing ${PACKAGE}@latest ${c.dim("…")}`);
|
|
1036
|
+
await removeCommandWrappers(join(state.installRoot, "bin"));
|
|
1037
|
+
try {
|
|
1038
|
+
await captured([state.bun, "add", "--global", "--no-cache", `${PACKAGE}@latest`], {
|
|
1039
|
+
...process.env,
|
|
1040
|
+
BUN_INSTALL: state.installRoot,
|
|
1041
|
+
});
|
|
1042
|
+
} finally {
|
|
1043
|
+
// Bun links the package's commands on success. If it did not (the
|
|
1044
|
+
// install failed), put the wrappers back so the commands still exist.
|
|
1045
|
+
await installCommands(directory, state.bun, true);
|
|
1046
|
+
}
|
|
1047
|
+
// Wrappers outside Bun's bin (an older `~/.local/bin` helper) run the
|
|
1048
|
+
// manager copy. Refresh it from the package just installed, or it
|
|
1049
|
+
// would stay at the version that first ran `install` forever.
|
|
1050
|
+
const packaged = await optionalFile(
|
|
1051
|
+
join(dirname(dirname(state.cli)), "scripts", "service.ts"),
|
|
1052
|
+
);
|
|
1053
|
+
if (packaged) await save(join(directory, "manager.ts"), packaged);
|
|
1054
|
+
},
|
|
1055
|
+
installedVersion: async () => {
|
|
1056
|
+
const installed = await command([state.bun, state.cli, "--version"]);
|
|
1057
|
+
say(`${c.ok("✓")} Installed ${c.bold(installed)}`);
|
|
1058
|
+
stage = "restart";
|
|
1059
|
+
return installed;
|
|
1060
|
+
},
|
|
1061
|
+
restart: async () => {
|
|
1062
|
+
await control(state, "restart");
|
|
1063
|
+
say(`${c.ok("✓")} Restarted ${c.dim(SUPERVISOR[state.platform].split(" · ")[0])}`);
|
|
1064
|
+
say(
|
|
1065
|
+
`${c.sky("◆")} Waiting ${c.dim("for the server to answer as the new version …")}`,
|
|
1066
|
+
);
|
|
1067
|
+
stage = "ready";
|
|
1068
|
+
},
|
|
1069
|
+
ready: (wanted) => ready(mcp, wanted),
|
|
1070
|
+
wait: () => sleep(1000),
|
|
1071
|
+
});
|
|
1072
|
+
const after = await probe(mcp, { tools: true });
|
|
1073
|
+
say(`${c.ok("✓")} Ready ${c.dim("the server answers as")} ${c.bold(version)}`);
|
|
1074
|
+
const changed = before !== undefined && before !== version;
|
|
1075
|
+
const rows: Rows = [
|
|
1076
|
+
[
|
|
1077
|
+
"Version",
|
|
1078
|
+
changed ? `${before} ${c.dim("→")} ${c.bold(c.ok(version))}` : c.bold(version),
|
|
1079
|
+
],
|
|
1080
|
+
["Took", `${Math.max(1, Math.round((Date.now() - started) / 1000))}s`],
|
|
1081
|
+
["MCP", c.sky(mcp)],
|
|
1082
|
+
["Dashboard", c.sky(`http://127.0.0.1:${state.dashboardPort}`)],
|
|
1083
|
+
];
|
|
1084
|
+
if (after.tools !== undefined)
|
|
1085
|
+
rows.push(["Tools", `${after.tools} ${c.dim("in tools/list")}`]);
|
|
605
1086
|
console.warn(
|
|
606
|
-
|
|
1087
|
+
`\n${panel(changed ? "Upgrade complete" : "Already current · reinstalled", rows, on)}\n\n` +
|
|
1088
|
+
` ${c.dim("Client URLs and config are unchanged.")}\n` +
|
|
1089
|
+
` ${c.dim("Reconnect your MCP clients so they load the new tool list.")}\n`,
|
|
607
1090
|
);
|
|
1091
|
+
} catch (error) {
|
|
1092
|
+
const what =
|
|
1093
|
+
stage === "install"
|
|
1094
|
+
? `Upgrade stopped during install. The service was not restarted${before ? `; ${before} keeps running` : ""}.`
|
|
1095
|
+
: stage === "restart"
|
|
1096
|
+
? "The new version is installed but the restart failed. Run: mikrotik-mcp-service restart"
|
|
1097
|
+
: "The service restarted but did not answer as the new version. Check: mikrotik-mcp-service status";
|
|
1098
|
+
say(`${c.bad("✗")} ${what}\n`);
|
|
1099
|
+
throw error;
|
|
1100
|
+
}
|
|
1101
|
+
} else if (options.action === "status") {
|
|
1102
|
+
console.warn(renderStatus(await inspect(state), useColor()));
|
|
1103
|
+
} else {
|
|
1104
|
+
await control(state, "restart");
|
|
1105
|
+
await waitReady(state);
|
|
608
1106
|
}
|
|
609
1107
|
} finally {
|
|
610
1108
|
await rmdir(lock);
|