@usex/mikrotik-mcp 6.13.0 → 6.15.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/cli.js +1389 -445
- package/dist/index.d.ts +106 -101
- package/dist/index.js +1 -1
- package/dist/shared/{cli-4xzq2n6j.js → cli-4aqtcr9k.js} +1 -1
- package/dist/shared/{cli-1vn2bbpy.js → cli-4n039739.js} +65 -22
- package/dist/shared/{cli-w6km895r.js → cli-57nggfz3.js} +1 -1
- package/dist/shared/{cli-rcx7e9h4.js → cli-5hgbedxa.js} +4 -2
- package/dist/shared/{cli-r1ng5cjy.js → cli-9x2ne7hp.js} +1 -1
- package/dist/shared/cli-b7rbwm6j.js +109 -0
- package/dist/shared/{library-1nhmbsv0.js → library-1sy0ph9r.js} +1 -1
- package/dist/shared/{library-1swafsvq.js → library-28w0j1ny.js} +1 -1
- package/dist/shared/{library-2wd7mt3g.js → library-7qr2sc9x.js} +62 -19
- package/dist/shared/{library-0qn06vwr.js → library-nt9fygza.js} +1 -1
- package/dist/shared/{library-jpmbkkz7.js → library-twpgma2r.js} +1 -1
- package/dist/ui/observability.html +293 -90
- package/package.json +5 -1
- package/schemas/config.schema.json +16 -2
- package/schemas/devtools-manifest.json +1 -1
- package/schemas/tool-catalog.json +1 -1
- package/scripts/service.ts +780 -73
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,476 @@ 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
|
+
/** Configured routers. Empty list = none configured; undefined = config unreadable. */
|
|
380
|
+
devices?: DeviceRow[];
|
|
381
|
+
/** True when `devices` carries live health from the running server. */
|
|
382
|
+
devicesLive: boolean;
|
|
383
|
+
data: string;
|
|
384
|
+
logs: string;
|
|
385
|
+
commands: string;
|
|
386
|
+
bun: string;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** One configured router, with the health the running server last measured. */
|
|
390
|
+
export interface DeviceRow {
|
|
391
|
+
name: string;
|
|
392
|
+
isDefault: boolean;
|
|
393
|
+
disabled: boolean;
|
|
394
|
+
/** true = reachable, false = unreachable, null = not probed (or no live data). */
|
|
395
|
+
reachable: boolean | null;
|
|
396
|
+
version?: string;
|
|
397
|
+
latencyMs?: number;
|
|
398
|
+
cpuLoad?: number;
|
|
399
|
+
memUsedPct?: number;
|
|
400
|
+
uptime?: string;
|
|
401
|
+
error?: string;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** Keep text from a config file or a router on one line of the terminal. */
|
|
405
|
+
function oneLine(text: unknown, max = 60): string {
|
|
406
|
+
const flat = [...String(text ?? "")]
|
|
407
|
+
.map((char) => (char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127 ? " " : char))
|
|
408
|
+
.join("")
|
|
409
|
+
.replace(/ {2,}/g, " ")
|
|
410
|
+
.trim();
|
|
411
|
+
return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const SUPERVISOR: Record<Platform, string> = {
|
|
415
|
+
darwin: "launchd LaunchAgent · starts at login · restarts if it stops",
|
|
416
|
+
linux: "systemd user unit · restarts after exit",
|
|
417
|
+
win32: "Task Scheduler task · starts at login",
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
/** Collect the facts for `status`. Every probe is bounded and may come back empty. */
|
|
421
|
+
async function inspect(state: ServiceState): Promise<ServiceReport> {
|
|
422
|
+
const quietly = <T>(work: Promise<T>): Promise<T | undefined> => work.catch(() => undefined);
|
|
423
|
+
const mcp = `http://127.0.0.1:${state.port}/mcp`;
|
|
424
|
+
const dashboard = `http://127.0.0.1:${state.dashboardPort}`;
|
|
425
|
+
const native = async (): Promise<{ running: boolean; pid?: number }> => {
|
|
426
|
+
if (state.platform === "darwin")
|
|
427
|
+
return parseLaunchctl(
|
|
428
|
+
await command(
|
|
429
|
+
["/bin/launchctl", "print", `gui/${process.getuid!()}/${LABEL}`],
|
|
430
|
+
process.env,
|
|
431
|
+
false,
|
|
432
|
+
true,
|
|
433
|
+
),
|
|
434
|
+
);
|
|
435
|
+
if (state.platform === "linux")
|
|
436
|
+
return parseSystemd(
|
|
437
|
+
await command(
|
|
438
|
+
["systemctl", "--user", "show", UNIT, "-p", "ActiveState", "-p", "MainPID"],
|
|
439
|
+
process.env,
|
|
440
|
+
false,
|
|
441
|
+
true,
|
|
442
|
+
),
|
|
443
|
+
);
|
|
444
|
+
return {
|
|
445
|
+
running: (await powershell(`(Get-ScheduledTask -TaskName ${psQuote(TASK)}).State`)).includes(
|
|
446
|
+
"Running",
|
|
447
|
+
),
|
|
448
|
+
};
|
|
449
|
+
};
|
|
450
|
+
const logs = async (): Promise<string> => {
|
|
451
|
+
if (state.platform === "linux") return `journalctl --user -u ${UNIT}`;
|
|
452
|
+
if (state.platform === "win32") return "Task Scheduler › MikroTik MCP › Last Run Result";
|
|
453
|
+
const plist = (await optionalFile(nativeFile("darwin"))) ?? "";
|
|
454
|
+
return (
|
|
455
|
+
/<key>StandardErrorPath<\/key>\s*<string>([^<]+)<\/string>/.exec(plist)?.[1] ??
|
|
456
|
+
"LaunchAgent StandardErrorPath / StandardOutPath"
|
|
457
|
+
);
|
|
458
|
+
};
|
|
459
|
+
const devices = async (): Promise<{ rows: DeviceRow[]; live: boolean }> => {
|
|
460
|
+
const config = JSON.parse((await optionalFile(state.config)) ?? "{}") as {
|
|
461
|
+
devices?: Record<string, { disabled?: boolean }>;
|
|
462
|
+
defaultDevice?: string;
|
|
463
|
+
dashboard?: { token?: string };
|
|
464
|
+
};
|
|
465
|
+
const configured: DeviceRow[] = Object.entries(config.devices ?? {}).map(([name, device]) => ({
|
|
466
|
+
name: oneLine(name, 40),
|
|
467
|
+
isDefault: name === config.defaultDevice,
|
|
468
|
+
disabled: device?.disabled === true,
|
|
469
|
+
reachable: null,
|
|
470
|
+
}));
|
|
471
|
+
// Live health comes from the running server's dashboard API — the same
|
|
472
|
+
// numbers the dashboard shows, with no extra connection to any router.
|
|
473
|
+
try {
|
|
474
|
+
const flag = state.args.indexOf("--dashboard-token");
|
|
475
|
+
const token = config.dashboard?.token ?? (flag >= 0 ? state.args[flag + 1] : undefined);
|
|
476
|
+
const response = await fetch(`${dashboard}/api/devices`, {
|
|
477
|
+
headers: token ? { authorization: `Bearer ${token}` } : {},
|
|
478
|
+
signal: AbortSignal.timeout(2500),
|
|
479
|
+
});
|
|
480
|
+
if (!response.ok) return { rows: configured, live: false };
|
|
481
|
+
const body = (await response.json()) as {
|
|
482
|
+
devices?: {
|
|
483
|
+
name?: unknown;
|
|
484
|
+
isDefault?: unknown;
|
|
485
|
+
disabled?: unknown;
|
|
486
|
+
status?: Record<string, unknown> | null;
|
|
487
|
+
}[];
|
|
488
|
+
};
|
|
489
|
+
if (!Array.isArray(body.devices)) return { rows: configured, live: false };
|
|
490
|
+
const number = (value: unknown): number | undefined =>
|
|
491
|
+
typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
492
|
+
const text = (value: unknown): string | undefined =>
|
|
493
|
+
typeof value === "string" && value ? oneLine(value) : undefined;
|
|
494
|
+
return {
|
|
495
|
+
live: true,
|
|
496
|
+
rows: body.devices.map((device) => ({
|
|
497
|
+
name: oneLine(device.name, 40),
|
|
498
|
+
isDefault: device.isDefault === true,
|
|
499
|
+
disabled: device.disabled === true,
|
|
500
|
+
reachable: typeof device.status?.reachable === "boolean" ? device.status.reachable : null,
|
|
501
|
+
version: text(device.status?.version),
|
|
502
|
+
latencyMs: number(device.status?.latencyMs),
|
|
503
|
+
cpuLoad: number(device.status?.cpuLoad),
|
|
504
|
+
memUsedPct: number(device.status?.memUsedPct),
|
|
505
|
+
uptime: text(device.status?.uptime),
|
|
506
|
+
error: text(device.status?.error),
|
|
507
|
+
})),
|
|
508
|
+
};
|
|
509
|
+
} catch {
|
|
510
|
+
return { rows: configured, live: false };
|
|
511
|
+
}
|
|
512
|
+
};
|
|
513
|
+
const latest = async (): Promise<string | undefined> => {
|
|
514
|
+
const response = await fetch(
|
|
515
|
+
`https://registry.npmjs.org/${PACKAGE.replace("/", "%2f")}/latest`,
|
|
516
|
+
{
|
|
517
|
+
signal: AbortSignal.timeout(2500),
|
|
518
|
+
},
|
|
519
|
+
);
|
|
520
|
+
const version = response.ok
|
|
521
|
+
? ((await response.json()) as { version?: unknown })?.version
|
|
522
|
+
: undefined;
|
|
523
|
+
return typeof version === "string" ? version : undefined;
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
const [process_, installed, served, dashboardUp, newest, deviceCount, logPath] =
|
|
527
|
+
await Promise.all([
|
|
528
|
+
quietly(native()),
|
|
529
|
+
quietly(command([state.bun, state.cli, "--version"], process.env, false, true)),
|
|
530
|
+
probe(mcp, { tools: true }),
|
|
531
|
+
quietly(
|
|
532
|
+
(async () =>
|
|
533
|
+
(await fetch(dashboard, { signal: AbortSignal.timeout(2000) })).status < 500)(),
|
|
534
|
+
),
|
|
535
|
+
quietly(latest()),
|
|
536
|
+
quietly(devices()),
|
|
537
|
+
quietly(logs()),
|
|
538
|
+
]);
|
|
539
|
+
const pid = process_?.pid;
|
|
540
|
+
const elapsed =
|
|
541
|
+
pid && state.platform !== "win32"
|
|
542
|
+
? await quietly(
|
|
543
|
+
command(["/bin/ps", "-o", "etime=", "-p", String(pid)], process.env, false, true),
|
|
544
|
+
)
|
|
545
|
+
: undefined;
|
|
546
|
+
return {
|
|
547
|
+
platform: state.platform,
|
|
548
|
+
running: process_?.running ?? false,
|
|
549
|
+
pid,
|
|
550
|
+
uptime: elapsed ? uptime(elapsed) : undefined,
|
|
551
|
+
installed: installed || undefined,
|
|
552
|
+
serving: served.version,
|
|
553
|
+
latest: newest,
|
|
554
|
+
tools: served.tools,
|
|
555
|
+
mcp,
|
|
556
|
+
dashboard,
|
|
557
|
+
dashboardUp: dashboardUp === true,
|
|
558
|
+
config: state.config,
|
|
559
|
+
devices: deviceCount?.rows,
|
|
560
|
+
devicesLive: deviceCount?.live === true,
|
|
561
|
+
data: state.cwd,
|
|
562
|
+
logs: logPath ?? "",
|
|
563
|
+
commands: join(state.installRoot, "bin"),
|
|
564
|
+
bun: `${process.versions.bun ?? "?"} ${state.bun}`,
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** Compare dotted versions numerically: negative when `a` is older than `b`. */
|
|
569
|
+
function compareVersions(a: string, b: string): number {
|
|
570
|
+
const parts = (v: string): number[] =>
|
|
571
|
+
v.split(/[.-]/).map((part) => Number.parseInt(part, 10) || 0);
|
|
572
|
+
const [x, y] = [parts(a), parts(b)];
|
|
573
|
+
for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) - (y[i] ?? 0);
|
|
574
|
+
return 0;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/** The `status` screen: what runs, which version, where it answers, where things live. */
|
|
578
|
+
export function renderStatus(report: ServiceReport, on: boolean): string {
|
|
579
|
+
const c = palette(on);
|
|
580
|
+
const home = homedir();
|
|
581
|
+
const tidy = (path: string): string =>
|
|
582
|
+
home && path.startsWith(home) ? `~${path.slice(home.length)}` : path;
|
|
583
|
+
const answering = report.serving !== undefined;
|
|
584
|
+
const advice: string[] = [];
|
|
585
|
+
|
|
586
|
+
const stateLine = report.running
|
|
587
|
+
? `${c.ok("●")} ${c.bold("running")}${
|
|
588
|
+
report.pid
|
|
589
|
+
? c.dim(` pid ${report.pid}${report.uptime ? ` · up ${report.uptime}` : ""}`)
|
|
590
|
+
: ""
|
|
591
|
+
}`
|
|
592
|
+
: `${c.bad("○")} ${c.bold("stopped")}`;
|
|
593
|
+
if (!report.running)
|
|
594
|
+
advice.push(`${c.bad("✗")} The service is not running. Start it: mikrotik-mcp-service restart`);
|
|
595
|
+
else if (!answering)
|
|
596
|
+
advice.push(
|
|
597
|
+
`${c.warn("!")} The process runs but MCP does not answer yet. Check the logs below.`,
|
|
598
|
+
);
|
|
599
|
+
|
|
600
|
+
let versionLine = report.installed ? `${c.bold(report.installed)} installed` : c.dim("unknown");
|
|
601
|
+
if (answering) {
|
|
602
|
+
versionLine =
|
|
603
|
+
report.serving === report.installed
|
|
604
|
+
? `${c.bold(report.serving!)} ${c.dim("running and installed")}`
|
|
605
|
+
: `${c.warn(report.serving!)} running ${c.dim("·")} ${c.bold(report.installed ?? "?")} installed`;
|
|
606
|
+
if (report.installed && report.serving !== report.installed)
|
|
607
|
+
advice.push(
|
|
608
|
+
`${c.warn("!")} Version ${report.installed} is installed but ${report.serving} is still running. Apply it: mikrotik-mcp-service restart`,
|
|
609
|
+
);
|
|
610
|
+
}
|
|
611
|
+
let latestLine = c.dim("could not reach the npm registry");
|
|
612
|
+
if (report.latest) {
|
|
613
|
+
const behind = report.installed ? compareVersions(report.installed, report.latest) < 0 : false;
|
|
614
|
+
latestLine = behind
|
|
615
|
+
? `${c.warn(report.latest)} ${c.dim("available")}`
|
|
616
|
+
: `${report.latest} ${c.dim("· up to date")}`;
|
|
617
|
+
if (behind)
|
|
618
|
+
advice.push(
|
|
619
|
+
`${c.sky("↑")} Update available: ${report.installed} → ${report.latest}. Run: mikrotik-mcp-upgrade`,
|
|
620
|
+
);
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
const mark = (up: boolean): string => (up ? c.ok("✓ answering") : c.bad("✗ no answer"));
|
|
624
|
+
const service: Rows = [
|
|
625
|
+
["State", stateLine],
|
|
626
|
+
["Supervisor", SUPERVISOR[report.platform]],
|
|
627
|
+
["Version", versionLine],
|
|
628
|
+
["Latest", latestLine],
|
|
629
|
+
];
|
|
630
|
+
if (report.tools !== undefined)
|
|
631
|
+
service.push(["Tools", `${report.tools} ${c.dim("in tools/list")}`]);
|
|
632
|
+
const fleet = report.devices ?? [];
|
|
633
|
+
const count = {
|
|
634
|
+
disabled: fleet.filter((d) => d.disabled).length,
|
|
635
|
+
online: fleet.filter((d) => !d.disabled && d.reachable === true).length,
|
|
636
|
+
offline: fleet.filter((d) => !d.disabled && d.reachable === false).length,
|
|
637
|
+
};
|
|
638
|
+
const pending = fleet.length - count.disabled - count.online - count.offline;
|
|
639
|
+
const summary = [`${c.bold(String(fleet.length))} configured`];
|
|
640
|
+
if (report.devicesLive) {
|
|
641
|
+
summary.push(`${c.ok(String(count.online))} online`);
|
|
642
|
+
if (count.offline) summary.push(`${c.bad(String(count.offline))} offline`);
|
|
643
|
+
if (pending) summary.push(`${pending} not checked yet`);
|
|
644
|
+
} else summary.push(`${fleet.length - count.disabled} enabled`);
|
|
645
|
+
if (count.disabled) summary.push(`${count.disabled} disabled`);
|
|
646
|
+
const MAX_DEVICE_ROWS = 12;
|
|
647
|
+
const nameWidth = Math.max(0, ...fleet.slice(0, MAX_DEVICE_ROWS).map((d) => d.name.length));
|
|
648
|
+
const deviceLine = (d: DeviceRow): string => {
|
|
649
|
+
const name = `${c.bold(d.name.padEnd(nameWidth))} ${d.isDefault ? c.violet("★") : " "}`;
|
|
650
|
+
if (d.disabled) return `${c.dim("◌")} ${name} ${c.dim("disabled")}`;
|
|
651
|
+
if (d.reachable === true) {
|
|
652
|
+
const facts = [
|
|
653
|
+
d.version ? `RouterOS ${d.version.replace(/\s*\(.*\)$/, "")}` : undefined,
|
|
654
|
+
d.latencyMs !== undefined ? `${Math.round(d.latencyMs)} ms` : undefined,
|
|
655
|
+
d.cpuLoad !== undefined ? `CPU ${Math.round(d.cpuLoad)}%` : undefined,
|
|
656
|
+
d.memUsedPct !== undefined ? `RAM ${Math.round(d.memUsedPct)}%` : undefined,
|
|
657
|
+
// Seconds are noise next to days and hours.
|
|
658
|
+
d.uptime ? `up ${d.uptime.replace(/(?<=[wdhm])\d+s$/, "")}` : undefined,
|
|
659
|
+
].filter(Boolean);
|
|
660
|
+
return `${c.ok("●")} ${name} ${c.ok("online ")} ${c.dim(facts.join(" · "))}`;
|
|
661
|
+
}
|
|
662
|
+
if (d.reachable === false)
|
|
663
|
+
return `${c.bad("○")} ${name} ${c.bad("offline")} ${c.dim(d.error ?? "no answer")}`;
|
|
664
|
+
return `${c.dim("·")} ${name} ${c.dim(report.devicesLive ? "not checked yet" : "state unknown")}`;
|
|
665
|
+
};
|
|
666
|
+
const devices: Rows = [["Summary", summary.join(c.dim(" · "))]];
|
|
667
|
+
if (!report.devices) devices[0] = ["Summary", c.dim("the config file could not be read")];
|
|
668
|
+
fleet
|
|
669
|
+
.slice(0, MAX_DEVICE_ROWS)
|
|
670
|
+
.forEach((d, i) => devices.push([i === 0 ? "Routers" : "", deviceLine(d)]));
|
|
671
|
+
if (fleet.length > MAX_DEVICE_ROWS)
|
|
672
|
+
devices.push(["", c.dim(`… and ${fleet.length - MAX_DEVICE_ROWS} more (see the dashboard)`)]);
|
|
673
|
+
if (report.devices && !report.devicesLive && fleet.length)
|
|
674
|
+
devices.push(["", c.dim("Live state needs the running service and its dashboard.")]);
|
|
675
|
+
if (count.offline)
|
|
676
|
+
advice.push(
|
|
677
|
+
`${c.warn("!")} ${count.offline} device${count.offline === 1 ? " is" : "s are"} offline: ${fleet
|
|
678
|
+
.filter((d) => !d.disabled && d.reachable === false)
|
|
679
|
+
.map((d) => d.name)
|
|
680
|
+
.join(", ")}`,
|
|
681
|
+
);
|
|
682
|
+
|
|
683
|
+
const urlWidth = Math.max(report.mcp.length, report.dashboard.length);
|
|
684
|
+
const endpoints: Rows = [
|
|
685
|
+
["MCP", `${c.sky(report.mcp.padEnd(urlWidth))} ${mark(answering)}`],
|
|
686
|
+
["Dashboard", `${c.sky(report.dashboard.padEnd(urlWidth))} ${mark(report.dashboardUp)}`],
|
|
687
|
+
];
|
|
688
|
+
const files: Rows = [
|
|
689
|
+
["Config", tidy(report.config)],
|
|
690
|
+
["Data", tidy(report.data)],
|
|
691
|
+
["Logs", tidy(report.logs)],
|
|
692
|
+
["Commands", tidy(report.commands)],
|
|
693
|
+
["Bun", tidy(report.bun)],
|
|
694
|
+
];
|
|
695
|
+
// One width for all three, so the boxes stack as a single column.
|
|
696
|
+
const min = Math.max(
|
|
697
|
+
panelWidth("Service", service),
|
|
698
|
+
panelWidth("Endpoints", endpoints),
|
|
699
|
+
panelWidth("Devices", devices),
|
|
700
|
+
panelWidth("Files", files),
|
|
701
|
+
);
|
|
702
|
+
|
|
703
|
+
return [
|
|
704
|
+
banner("status", on),
|
|
705
|
+
panel("Service", service, on, min),
|
|
706
|
+
panel("Endpoints", endpoints, on, min),
|
|
707
|
+
panel("Devices", devices, on, min),
|
|
708
|
+
panel("Files", files, on, min),
|
|
709
|
+
advice.length
|
|
710
|
+
? advice.map((line) => ` ${line}`).join("\n")
|
|
711
|
+
: ` ${c.ok("✓")} ${c.dim("Everything is in order.")}`,
|
|
712
|
+
` ${c.dim("Commands: mikrotik-mcp-upgrade · mikrotik-mcp-service restart | status | uninstall")}\n`,
|
|
713
|
+
].join("\n\n");
|
|
714
|
+
}
|
|
715
|
+
|
|
196
716
|
/** Adopt the existing macOS helper's LaunchAgent without replacing its environment or flags. */
|
|
197
717
|
async function adoptMac(): Promise<ServiceState | undefined> {
|
|
198
718
|
if (!(await optionalFile(nativeFile("darwin")))) return;
|
|
@@ -339,17 +859,49 @@ async function ensureStarted(state: ServiceState): Promise<void> {
|
|
|
339
859
|
}
|
|
340
860
|
}
|
|
341
861
|
|
|
862
|
+
const COMMANDS: [name: string, action: string][] = [
|
|
863
|
+
["mikrotik-mcp-service", ""],
|
|
864
|
+
["mikrotik-mcp-upgrade", "upgrade"],
|
|
865
|
+
];
|
|
866
|
+
/** First line of the POSIX wrapper; also how one of ours is recognised. */
|
|
867
|
+
const WRAPPER_HEAD = "#!/bin/sh\nexec ";
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* Remove the POSIX command wrappers this installer wrote into Bun's global bin
|
|
871
|
+
* directory, before `bun add --global` runs.
|
|
872
|
+
*
|
|
873
|
+
* The package declares bins with the same two names. Bun links them as
|
|
874
|
+
* symlinks and fails the whole install with `EEXIST` when a regular file is in
|
|
875
|
+
* the way — which left the new version on disk but the service not restarted.
|
|
876
|
+
* Only our own wrappers are removed: a symlink is Bun's link, and any other
|
|
877
|
+
* file is not ours to delete.
|
|
878
|
+
*/
|
|
879
|
+
export async function removeCommandWrappers(bin: string): Promise<void> {
|
|
880
|
+
if (process.platform === "win32") return; // `.cmd` wrappers do not collide with Bun's shims
|
|
881
|
+
for (const [name] of COMMANDS) {
|
|
882
|
+
const file = join(bin, name);
|
|
883
|
+
const info = await lstat(file).catch(() => null);
|
|
884
|
+
if (!info?.isFile()) continue;
|
|
885
|
+
const text = await readFile(file, "utf8").catch(() => "");
|
|
886
|
+
if (text.startsWith(WRAPPER_HEAD) && text.includes("manager.ts")) await unlink(file);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
342
890
|
/** Expose the same two commands on every OS, independent of the source checkout. */
|
|
343
|
-
async function installCommands(
|
|
891
|
+
export async function installCommands(
|
|
892
|
+
directory: string,
|
|
893
|
+
bun: string,
|
|
894
|
+
/** Skip the PATH reminder: for upgrade, which only repairs existing commands. */
|
|
895
|
+
quiet = false,
|
|
896
|
+
): Promise<void> {
|
|
344
897
|
const manager = join(directory, "manager.ts");
|
|
345
898
|
if (resolve(fileURLToPath(import.meta.url)) !== resolve(manager))
|
|
346
899
|
await save(manager, await readFile(fileURLToPath(import.meta.url), "utf8"));
|
|
347
900
|
const bin = (await command([bun, "pm", "-g", "bin"])).trim();
|
|
348
901
|
const shellQuote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
]) {
|
|
902
|
+
const wrapper = (action: string): string =>
|
|
903
|
+
`${WRAPPER_HEAD}${shellQuote(bun)} ${shellQuote(manager)} ${action} "$@"\n`;
|
|
904
|
+
for (const [name, action] of COMMANDS) {
|
|
353
905
|
if (process.platform === "win32") {
|
|
354
906
|
const quoted = [bun, manager]
|
|
355
907
|
.map((value) => windowsQuote(value).replaceAll("%", "%%"))
|
|
@@ -358,12 +910,13 @@ async function installCommands(directory: string, bun: string): Promise<void> {
|
|
|
358
910
|
join(bin, `${name}.cmd`),
|
|
359
911
|
`@echo off\r\nsetlocal DisableDelayedExpansion\r\n${quoted} ${action} %*\r\nexit /b %errorlevel%\r\n`,
|
|
360
912
|
);
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
913
|
+
continue;
|
|
914
|
+
}
|
|
915
|
+
// Bun already linked the package's own command here: keep it. Writing a
|
|
916
|
+
// file over it would make the next `bun add --global` fail with EEXIST.
|
|
917
|
+
const existing = await lstat(join(bin, name)).catch(() => null);
|
|
918
|
+
if (existing?.isSymbolicLink()) continue;
|
|
919
|
+
await save(join(bin, name), wrapper(action), 0o755);
|
|
367
920
|
}
|
|
368
921
|
// The first macOS-only helper lived here and can shadow Bun's bin on PATH.
|
|
369
922
|
if (process.platform === "darwin") {
|
|
@@ -373,15 +926,17 @@ async function installCommands(directory: string, bun: string): Promise<void> {
|
|
|
373
926
|
source?.includes('const LABEL = "dev.usestrict.mikrotik-mcp"') &&
|
|
374
927
|
source.includes("macOS only; no sudo.")
|
|
375
928
|
)
|
|
376
|
-
await save(legacy,
|
|
929
|
+
await save(legacy, wrapper("upgrade"), 0o755);
|
|
377
930
|
}
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
931
|
+
if (!quiet)
|
|
932
|
+
console.warn(
|
|
933
|
+
`Commands installed in ${bin}. If your terminal cannot find them, add this directory to PATH.`,
|
|
934
|
+
);
|
|
381
935
|
}
|
|
382
936
|
|
|
383
937
|
/** Verify the CLI and the live MCP version after service activation. */
|
|
384
|
-
|
|
938
|
+
/** Wait until the running server answers as the installed version; returns that version. */
|
|
939
|
+
async function waitReady(state: ServiceState): Promise<string> {
|
|
385
940
|
const version = await command([state.bun, state.cli, "--version"]);
|
|
386
941
|
await upgrade({
|
|
387
942
|
install: async () => {},
|
|
@@ -390,9 +945,30 @@ async function waitReady(state: ServiceState): Promise<void> {
|
|
|
390
945
|
ready: (v) => ready(`http://127.0.0.1:${state.port}/mcp`, v),
|
|
391
946
|
wait: () => sleep(1000),
|
|
392
947
|
});
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
948
|
+
return version;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/** The `--help` screen. */
|
|
952
|
+
export function renderHelp(on: boolean): string {
|
|
953
|
+
const c = palette(on);
|
|
954
|
+
const row = (commandLine: string, what: string): string =>
|
|
955
|
+
` ${c.bold(commandLine.padEnd(46))}${c.dim(what)}`;
|
|
956
|
+
return [
|
|
957
|
+
banner("help", on),
|
|
958
|
+
"",
|
|
959
|
+
row("mikrotik-mcp-service install", "Install and start the service"),
|
|
960
|
+
row(" [--config devices.json]", "Use an existing config file"),
|
|
961
|
+
row(" [--mcp-port 8000] [--dashboard-port 9090]", "Choose the local ports"),
|
|
962
|
+
row("mikrotik-mcp-service status", "Service, versions, endpoints and devices"),
|
|
963
|
+
row("mikrotik-mcp-service restart", "Restart without updating"),
|
|
964
|
+
row("mikrotik-mcp-upgrade", "Install the latest version and restart"),
|
|
965
|
+
row("mikrotik-mcp-service uninstall", "Stop and remove automatic startup"),
|
|
966
|
+
"",
|
|
967
|
+
` ${c.dim("No config? Install creates a disabled example router; configure it in the dashboard.")}`,
|
|
968
|
+
` ${c.dim("Runs as your login user: macOS launchd, Linux systemd --user, Windows logon task.")}`,
|
|
969
|
+
` ${c.dim("Uninstall keeps your config, keys and history. Bun required. No sudo.")}`,
|
|
970
|
+
"",
|
|
971
|
+
].join("\n");
|
|
396
972
|
}
|
|
397
973
|
|
|
398
974
|
/** Parse a deliberately small CLI with strict options and explicit install-only flags. */
|
|
@@ -433,15 +1009,18 @@ export function serviceOptions(argv: string[]): {
|
|
|
433
1009
|
export async function main(argv = process.argv.slice(2)): Promise<void> {
|
|
434
1010
|
const options = serviceOptions(argv);
|
|
435
1011
|
if (options.action === "help") {
|
|
436
|
-
console.warn(
|
|
437
|
-
`MikroTik MCP shared service (Bun required)\n\n mikrotik-mcp-service install [--config devices.json]\n mikrotik-mcp-upgrade\n mikrotik-mcp-service restart | status | uninstall\n\nOptional install ports: --mcp-port 8000 --dashboard-port 9090\nNo config? Install creates a disabled example router; configure it in the dashboard.\nRuns as your login user: macOS launchd, Linux systemd --user, Windows logon task.\nUninstall keeps your config, keys and history. No sudo required.`,
|
|
438
|
-
);
|
|
1012
|
+
console.warn(renderHelp(useColor()));
|
|
439
1013
|
return;
|
|
440
1014
|
}
|
|
441
1015
|
if (!["darwin", "linux", "win32"].includes(process.platform))
|
|
442
1016
|
throw new Error("Supported platforms: Windows, macOS, Linux with systemd.");
|
|
443
1017
|
if (process.getuid?.() === 0) throw new Error("Run as your regular login user, without sudo.");
|
|
444
1018
|
const platform = process.platform as Platform;
|
|
1019
|
+
const on = useColor();
|
|
1020
|
+
const c = palette(on);
|
|
1021
|
+
const say = (line: string): void => console.warn(` ${line}`);
|
|
1022
|
+
const tidy = (path: string): string =>
|
|
1023
|
+
homedir() && path.startsWith(homedir()) ? `~${path.slice(homedir().length)}` : path;
|
|
445
1024
|
const directory = join(homedir(), ".mikrotik-mcp", "service");
|
|
446
1025
|
const metadata = join(directory, "service.json");
|
|
447
1026
|
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
@@ -460,6 +1039,8 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
|
|
|
460
1039
|
throw new Error("Incompatible service metadata; nothing changed.");
|
|
461
1040
|
if (!state && platform === "darwin") state = await adoptMac();
|
|
462
1041
|
if (options.action === "install") {
|
|
1042
|
+
console.warn(`${banner("install", on)}\n`);
|
|
1043
|
+
const fresh = !state;
|
|
463
1044
|
if (state) {
|
|
464
1045
|
if (
|
|
465
1046
|
(options.config && resolve(options.config) !== state.config) ||
|
|
@@ -528,8 +1109,10 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
|
|
|
528
1109
|
"dist",
|
|
529
1110
|
"cli.js",
|
|
530
1111
|
);
|
|
531
|
-
if (!(await optionalFile(cli)))
|
|
1112
|
+
if (!(await optionalFile(cli))) {
|
|
1113
|
+
await removeCommandWrappers(bin);
|
|
532
1114
|
await command([bun, "add", "--global", `${PACKAGE}@latest`], process.env, true);
|
|
1115
|
+
}
|
|
533
1116
|
await command([bun, cli, "--version"]);
|
|
534
1117
|
const args = [
|
|
535
1118
|
"serve",
|
|
@@ -566,45 +1149,169 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
|
|
|
566
1149
|
await save(metadata, JSON.stringify(state, null, 2));
|
|
567
1150
|
}
|
|
568
1151
|
await save(metadata, JSON.stringify(state, null, 2));
|
|
569
|
-
|
|
1152
|
+
say(
|
|
1153
|
+
fresh
|
|
1154
|
+
? `${c.ok("✓")} Config ${tidy(state.config)}`
|
|
1155
|
+
: `${c.dim("•")} Already installed ${c.dim("— checking that it runs")}`,
|
|
1156
|
+
);
|
|
1157
|
+
await installCommands(directory, state.bun, true);
|
|
1158
|
+
const bin = join(state.installRoot, "bin");
|
|
1159
|
+
say(`${c.ok("✓")} Commands ${tidy(bin)}`);
|
|
570
1160
|
await ensureStarted(state);
|
|
571
|
-
|
|
1161
|
+
say(`${c.ok("✓")} Registered ${c.dim(SUPERVISOR[platform])}`);
|
|
1162
|
+
say(`${c.sky("◆")} Waiting ${c.dim("for the server to answer …")}`);
|
|
1163
|
+
const version = await waitReady(state);
|
|
1164
|
+
say(`${c.ok("✓")} Ready ${c.dim("the server answers as")} ${c.bold(version)}`);
|
|
1165
|
+
const mcp = `http://127.0.0.1:${state.port}/mcp`;
|
|
1166
|
+
const onPath = (process.env.PATH ?? "").split(platform === "win32" ? ";" : ":").includes(bin);
|
|
1167
|
+
console.warn(
|
|
1168
|
+
[
|
|
1169
|
+
"",
|
|
1170
|
+
panel(
|
|
1171
|
+
fresh ? "Service installed" : "Service running",
|
|
1172
|
+
[
|
|
1173
|
+
["Version", c.bold(version)],
|
|
1174
|
+
["MCP", c.sky(mcp)],
|
|
1175
|
+
["Dashboard", c.sky(`http://127.0.0.1:${state.dashboardPort}`)],
|
|
1176
|
+
["Config", tidy(state.config)],
|
|
1177
|
+
],
|
|
1178
|
+
on,
|
|
1179
|
+
),
|
|
1180
|
+
"",
|
|
1181
|
+
` ${c.dim("Add this URL to your MCP clients:")} ${mcp}`,
|
|
1182
|
+
// Only when it matters: the commands are not reachable from this shell.
|
|
1183
|
+
...(onPath
|
|
1184
|
+
? []
|
|
1185
|
+
: [
|
|
1186
|
+
` ${c.warn("!")} ${tidy(bin)} is not on your PATH. Add it to run the commands by name.`,
|
|
1187
|
+
]),
|
|
1188
|
+
` ${c.dim("Next: mikrotik-mcp-service status · mikrotik-mcp-upgrade")}`,
|
|
1189
|
+
"",
|
|
1190
|
+
].join("\n"),
|
|
1191
|
+
);
|
|
572
1192
|
return;
|
|
573
1193
|
}
|
|
574
1194
|
if (!state)
|
|
575
1195
|
throw new Error("Service is not installed. Run mikrotik-mcp-service install first.");
|
|
576
1196
|
if (options.action === "uninstall") {
|
|
1197
|
+
console.warn(`${banner("uninstall", on)}\n`);
|
|
577
1198
|
await control(state, "remove");
|
|
578
1199
|
if (platform !== "win32") await unlink(nativeFile(platform));
|
|
579
1200
|
if (platform === "linux") await command(["systemctl", "--user", "daemon-reload"]);
|
|
580
1201
|
await unlink(metadata).catch((error) => {
|
|
581
1202
|
if (error.code !== "ENOENT") throw error;
|
|
582
1203
|
});
|
|
1204
|
+
say(`${c.ok("✓")} Stopped ${c.dim("and removed from automatic startup")}`);
|
|
583
1205
|
console.warn(
|
|
584
|
-
|
|
1206
|
+
`\n${panel(
|
|
1207
|
+
"Service removed · kept on this machine",
|
|
1208
|
+
[
|
|
1209
|
+
["Config", tidy(state.config)],
|
|
1210
|
+
["Data", `${tidy(state.cwd)} ${c.dim("history, snapshots, SSH keys")}`],
|
|
1211
|
+
["Package", `${tidy(dirname(dirname(state.cli)))}`],
|
|
1212
|
+
],
|
|
1213
|
+
on,
|
|
1214
|
+
)}\n\n ${c.dim("Enable it again: mikrotik-mcp-service install")}\n`,
|
|
585
1215
|
);
|
|
586
1216
|
} else if (options.action === "upgrade") {
|
|
587
|
-
const
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
1217
|
+
const mcp = `http://127.0.0.1:${state.port}/mcp`;
|
|
1218
|
+
console.warn(`${banner("upgrade", on)}\n`);
|
|
1219
|
+
const before = (await probe(mcp)).version;
|
|
1220
|
+
say(`${c.dim("•")} Running now ${before ? c.bold(before) : c.dim("not answering")}`);
|
|
1221
|
+
const started = Date.now();
|
|
1222
|
+
// How far the upgrade got, so a failure says what state the service is in.
|
|
1223
|
+
let stage: "install" | "restart" | "ready" = "install";
|
|
1224
|
+
try {
|
|
1225
|
+
const version = await upgrade({
|
|
1226
|
+
install: async () => {
|
|
1227
|
+
say(`${c.sky("◆")} Installing ${PACKAGE}@latest ${c.dim("…")}`);
|
|
1228
|
+
await removeCommandWrappers(join(state.installRoot, "bin"));
|
|
1229
|
+
try {
|
|
1230
|
+
await captured([state.bun, "add", "--global", "--no-cache", `${PACKAGE}@latest`], {
|
|
1231
|
+
...process.env,
|
|
1232
|
+
BUN_INSTALL: state.installRoot,
|
|
1233
|
+
});
|
|
1234
|
+
} finally {
|
|
1235
|
+
// Bun links the package's commands on success. If it did not (the
|
|
1236
|
+
// install failed), put the wrappers back so the commands still exist.
|
|
1237
|
+
await installCommands(directory, state.bun, true);
|
|
1238
|
+
}
|
|
1239
|
+
// Wrappers outside Bun's bin (an older `~/.local/bin` helper) run the
|
|
1240
|
+
// manager copy. Refresh it from the package just installed, or it
|
|
1241
|
+
// would stay at the version that first ran `install` forever.
|
|
1242
|
+
const packaged = await optionalFile(
|
|
1243
|
+
join(dirname(dirname(state.cli)), "scripts", "service.ts"),
|
|
1244
|
+
);
|
|
1245
|
+
if (packaged) await save(join(directory, "manager.ts"), packaged);
|
|
1246
|
+
},
|
|
1247
|
+
installedVersion: async () => {
|
|
1248
|
+
const installed = await command([state.bun, state.cli, "--version"]);
|
|
1249
|
+
say(`${c.ok("✓")} Installed ${c.bold(installed)}`);
|
|
1250
|
+
stage = "restart";
|
|
1251
|
+
return installed;
|
|
1252
|
+
},
|
|
1253
|
+
restart: async () => {
|
|
1254
|
+
await control(state, "restart");
|
|
1255
|
+
say(`${c.ok("✓")} Restarted ${c.dim(SUPERVISOR[state.platform].split(" · ")[0])}`);
|
|
1256
|
+
say(
|
|
1257
|
+
`${c.sky("◆")} Waiting ${c.dim("for the server to answer as the new version …")}`,
|
|
1258
|
+
);
|
|
1259
|
+
stage = "ready";
|
|
1260
|
+
},
|
|
1261
|
+
ready: (wanted) => ready(mcp, wanted),
|
|
1262
|
+
wait: () => sleep(1000),
|
|
1263
|
+
});
|
|
1264
|
+
const after = await probe(mcp, { tools: true });
|
|
1265
|
+
say(`${c.ok("✓")} Ready ${c.dim("the server answers as")} ${c.bold(version)}`);
|
|
1266
|
+
const changed = before !== undefined && before !== version;
|
|
1267
|
+
const rows: Rows = [
|
|
1268
|
+
[
|
|
1269
|
+
"Version",
|
|
1270
|
+
changed ? `${before} ${c.dim("→")} ${c.bold(c.ok(version))}` : c.bold(version),
|
|
1271
|
+
],
|
|
1272
|
+
["Took", `${Math.max(1, Math.round((Date.now() - started) / 1000))}s`],
|
|
1273
|
+
["MCP", c.sky(mcp)],
|
|
1274
|
+
["Dashboard", c.sky(`http://127.0.0.1:${state.dashboardPort}`)],
|
|
1275
|
+
];
|
|
1276
|
+
if (after.tools !== undefined)
|
|
1277
|
+
rows.push(["Tools", `${after.tools} ${c.dim("in tools/list")}`]);
|
|
605
1278
|
console.warn(
|
|
606
|
-
|
|
1279
|
+
`\n${panel(changed ? "Upgrade complete" : "Already current · reinstalled", rows, on)}\n\n` +
|
|
1280
|
+
` ${c.dim("Client URLs and config are unchanged.")}\n` +
|
|
1281
|
+
` ${c.dim("Reconnect your MCP clients so they load the new tool list.")}\n`,
|
|
607
1282
|
);
|
|
1283
|
+
} catch (error) {
|
|
1284
|
+
const what =
|
|
1285
|
+
stage === "install"
|
|
1286
|
+
? `Upgrade stopped during install. The service was not restarted${before ? `; ${before} keeps running` : ""}.`
|
|
1287
|
+
: stage === "restart"
|
|
1288
|
+
? "The new version is installed but the restart failed. Run: mikrotik-mcp-service restart"
|
|
1289
|
+
: "The service restarted but did not answer as the new version. Check: mikrotik-mcp-service status";
|
|
1290
|
+
say(`${c.bad("✗")} ${what}\n`);
|
|
1291
|
+
throw error;
|
|
1292
|
+
}
|
|
1293
|
+
} else if (options.action === "status") {
|
|
1294
|
+
console.warn(renderStatus(await inspect(state), on));
|
|
1295
|
+
} else {
|
|
1296
|
+
console.warn(`${banner("restart", on)}\n`);
|
|
1297
|
+
const started = Date.now();
|
|
1298
|
+
await control(state, "restart");
|
|
1299
|
+
say(`${c.ok("✓")} Restarted ${c.dim(SUPERVISOR[platform].split(" · ")[0])}`);
|
|
1300
|
+
say(`${c.sky("◆")} Waiting ${c.dim("for the server to answer …")}`);
|
|
1301
|
+
const version = await waitReady(state);
|
|
1302
|
+
say(`${c.ok("✓")} Ready ${c.dim("the server answers as")} ${c.bold(version)}`);
|
|
1303
|
+
console.warn(
|
|
1304
|
+
`\n${panel(
|
|
1305
|
+
"Service restarted",
|
|
1306
|
+
[
|
|
1307
|
+
["Version", c.bold(version)],
|
|
1308
|
+
["Took", `${Math.max(1, Math.round((Date.now() - started) / 1000))}s`],
|
|
1309
|
+
["MCP", c.sky(`http://127.0.0.1:${state.port}/mcp`)],
|
|
1310
|
+
["Dashboard", c.sky(`http://127.0.0.1:${state.dashboardPort}`)],
|
|
1311
|
+
],
|
|
1312
|
+
on,
|
|
1313
|
+
)}\n\n ${c.dim("Reconnect your MCP clients if they do not reconnect by themselves.")}\n`,
|
|
1314
|
+
);
|
|
608
1315
|
}
|
|
609
1316
|
} finally {
|
|
610
1317
|
await rmdir(lock);
|