#!/usr/bin/env bun import { sleep, spawn } from "bun"; import { chmod, lstat, mkdir, readFile, rename, rmdir, unlink, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { parseArgs } from "node:util"; import { Buffer } from "node:buffer"; const PACKAGE = "@usex/mikrotik-mcp"; const LABEL = "dev.usestrict.mikrotik-mcp"; const UNIT = "mikrotik-mcp.service"; const TASK = "MikroTik MCP"; export type Platform = "darwin" | "linux" | "win32"; export interface ServiceState { format: 1; platform: Platform; bun: string; cli: string; installRoot: string; config: string; cwd: string; args: string[]; port: number; dashboardPort: number; } export interface UpgradeIO { install: () => Promise; installedVersion: () => Promise; restart: () => Promise; ready: (version: string) => Promise; wait: () => Promise; } /** Restart only a verified installation, and require the running MCP to report that version. */ export async function upgrade(io: UpgradeIO): Promise { await io.install(); const version = await io.installedVersion(); if (!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(version)) throw new Error("Installed CLI did not return a valid version; service was not restarted."); await io.restart(); for (let attempt = 0; attempt < 30; attempt++) { if (await io.ready(version)) return version; await io.wait(); } throw new Error( "Service did not become ready. Check the service logs listed by mikrotik-mcp-service status.", ); } /** Run host service-management commands as argv arrays, never through a shell. */ async function command( args: string[], env = process.env, visible = false, /** Discard the child's stderr: for probes whose failure is an answer, not an error. */ quiet = false, ): Promise { const child = spawn(args, { cwd: homedir(), env, stdout: visible ? "inherit" : "pipe", stderr: quiet ? "ignore" : "inherit", }); const output = visible ? "" : await new Response(child.stdout as ReadableStream).text(); if ((await child.exited) !== 0) throw new Error(`Command failed: ${args[0]} ${args[1] ?? ""}`); return output.trim(); } /** Run a noisy command silently; show what it printed only when it fails. */ async function captured(args: string[], env = process.env): Promise { const child = spawn(args, { cwd: homedir(), env, stdout: "pipe", stderr: "pipe" }); const read = (stream: unknown): Promise => stream ? new Response(stream as ReadableStream).text() : Promise.resolve(""); const [stdout, stderr] = await Promise.all([read(child.stdout), read(child.stderr)]); if ((await child.exited) === 0) return; const printed = `${stdout}${stderr}`.trim(); if (printed) console.warn(printed); throw new Error(`Command failed: ${args[0]} ${args[1] ?? ""}`); } /** What a running server says about itself over MCP. Empty when it does not answer. */ export interface ServerProbe { version?: string; /** Number of tools in `tools/list`; requested only with `tools: true`. */ tools?: number; } /** One JSON-RPC message from a plain-JSON or event-stream MCP response. */ async function rpcPayload(response: Response): Promise { const text = await response.text(); const payload = response.headers.get("content-type")?.includes("text/event-stream") ? text .split("\n") .find((line) => line.startsWith("data:")) ?.slice(5) .trim() : text; return JSON.parse(payload ?? "null"); } /** Ask the HTTP MCP server who it is — its real version, not just a listening port. */ export async function probe( endpoint: string, opts: { tools?: boolean } = {}, ): Promise { let session: string | null = null; const post = (body: unknown, extra: Record = {}): Promise => fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream", ...extra, }, body: JSON.stringify(body), signal: AbortSignal.timeout(2000), }); try { const response = await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "mikrotik-mcp-upgrade", version: "1.0.0" }, }, }); session = response.headers.get("mcp-session-id"); if (!response.ok) return {}; const version = (await rpcPayload(response))?.result?.serverInfo?.version; const found: ServerProbe = typeof version === "string" ? { version } : {}; if (opts.tools && session) { const withSession = { "mcp-session-id": session }; await post({ jsonrpc: "2.0", method: "notifications/initialized" }, withSession); const listed = await post({ jsonrpc: "2.0", id: 2, method: "tools/list" }, withSession); const tools = listed.ok ? (await rpcPayload(listed))?.result?.tools : undefined; if (Array.isArray(tools)) found.tools = tools.length; } return found; } catch { return {}; } finally { if (session) await fetch(endpoint, { method: "DELETE", headers: { "mcp-session-id": session }, signal: AbortSignal.timeout(2000), }).catch(() => {}); } } /** Confirm the actual HTTP MCP server version, not just a listening port. */ export async function ready(endpoint: string, version: string): Promise { return (await probe(endpoint)).version === version; } /** Accept only supported OSes and bounded, distinct local listener ports. */ export function validatePorts(mcp: number, dashboard: number): void { if ( ![mcp, dashboard].every((port) => Number.isInteger(port) && port >= 1024 && port <= 65535) || mcp === dashboard ) throw new Error("Use distinct MCP/dashboard ports between 1024 and 65535."); } /** Escape systemd specifiers and variable expansion without invoking a shell. */ export function systemdQuote(value: string, commandLine = false): string { if (/[\r\n\0]/.test(value)) throw new Error("Paths must not contain control characters."); const escaped = value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("%", "%%"); return `"${commandLine ? escaped.replaceAll("$", () => "$$") : escaped}"`; } /** Quote a Windows argv element using the CommandLineToArgvW backslash rules. */ export function windowsQuote(value: string): string { if (/[\r\n\0]/.test(value)) throw new Error("Paths must not contain control characters."); return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`; } /** Preserve literal data in PowerShell single-quoted strings. */ export function psQuote(value: string): string { if (/[\r\n\0]/.test(value)) throw new Error("Paths must not contain control characters."); return `'${value.replaceAll("'", "''")}'`; } /** Render a per-user Linux unit with loopback listeners and restart supervision. */ export function linuxUnit(state: ServiceState): string { return `[Unit]\nDescription=MikroTik MCP shared service\nAfter=network.target\n\n[Service]\nType=simple\nWorkingDirectory=${systemdQuote(state.cwd)}\nExecStart=${[state.bun, state.cli, ...state.args].map((arg) => systemdQuote(arg, true)).join(" ")}\nRestart=always\nRestartSec=5\nTimeoutStopSec=30\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`; } /** Create a password-free, current-user Windows logon task with bounded restart retries. */ export function windowsInstall(state: ServiceState): string { return `$ErrorActionPreference='Stop' $user=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name $action=New-ScheduledTaskAction -Execute ${psQuote(state.bun)} -Argument ${psQuote([state.cli, ...state.args].map(windowsQuote).join(" "))} -WorkingDirectory ${psQuote(state.cwd)} $trigger=New-ScheduledTaskTrigger -AtLogOn -User $user $principal=New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited $settings=New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries Register-ScheduledTask -TaskName ${psQuote(TASK)} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description 'MikroTik MCP per-user shared service' | Out-Null Start-ScheduledTask -TaskName ${psQuote(TASK)}`; } /** Use encoded PowerShell so user paths are not interpreted by a command shell. */ async function powershell(script: string): Promise { return command([ "powershell.exe", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(`$ErrorActionPreference='Stop'\n${script}`, "utf16le").toString("base64"), ]); } /** Locate only this tool's per-user native service registration. */ function nativeFile(platform: Platform): string { return platform === "darwin" ? join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`) : join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "systemd", "user", UNIT); } /** Read optional files without masking permission or filesystem errors. */ async function optionalFile(path: string): Promise { try { return await readFile(path, "utf8"); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; } } /** Persist complete metadata privately before exposing it to subsequent commands. */ async function save(path: string, content: string, mode = 0o600): Promise { await mkdir(dirname(path), { recursive: true, mode: 0o700 }); const temporary = `${path}.${process.pid}.tmp`; try { await writeFile(temporary, content, { mode }); await rename(temporary, path); if (process.platform !== "win32") await chmod(path, mode); } finally { await unlink(temporary).catch(() => {}); } } // ── Terminal output ───────────────────────────────────────────────────────── /** * figlet "Small" rendering of "MikroTik MCP" — the banner `src/cli-logo.ts` * draws when the server starts. It is embedded as text because this file is * also copied to `~/.mikrotik-mcp/service/manager.ts` and run from there with * no `node_modules`, so it cannot import figlet. A test keeps it identical to * figlet's output. */ export const BANNER: readonly string[] = [ " __ __ _ _ _____ _ _ __ __ ___ ___ ", " | \\/ (_) |___ _ __|_ _(_) |__ | \\/ |/ __| _ \\", " | |\\/| | | / / '_/ _ \\| | | | / / | |\\/| | (__| _/", " |_| |_|_|_\\_\\_| \\___/|_| |_|_\\_\\ |_| |_|\\___|_| ", ]; /** Brand gradient: violet → sky → teal, as in the server banner and dashboard. */ const BRAND: readonly (readonly [number, number, number])[] = [ [157, 123, 255], [50, 145, 255], [45, 212, 191], ]; const ESC = "\x1B["; const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g"); /** Printed width of a string, without colour codes. */ const width = (text: string): number => text.replace(ANSI, "").length; /** Colour helpers that turn into plain text when colour is off. */ function palette(on: boolean) { const wrap = (code: string) => (text: string): string => on ? `${ESC}${code}m${text}${ESC}0m` : text; return { on, bold: wrap("1"), dim: wrap("90"), ok: wrap("38;2;45;212;191"), bad: wrap("38;2;255;107;107"), warn: wrap("38;2;245;166;35"), sky: wrap("38;2;50;145;255"), violet: wrap("38;2;157;123;255"), }; } /** Colour only for a person at a terminal; `NO_COLOR` always wins. */ const useColor = (): boolean => process.stderr.isTTY === true && !process.env.NO_COLOR; /** One line coloured left to right across the brand gradient. */ function gradient(line: string): string { const last = Math.max(1, line.length - 1); let out = ""; for (let i = 0; i < line.length; i++) { const at = (i / last) * (BRAND.length - 1); const from = BRAND[Math.floor(at)]; const to = BRAND[Math.min(BRAND.length - 1, Math.floor(at) + 1)]; const mix = at - Math.floor(at); const [r, g, b] = from.map((channel, k) => Math.round(channel + (to[k] - channel) * mix)); out += line[i] === " " ? " " : `${ESC}38;2;${r};${g};${b}m${line[i]}`; } return `${out}${ESC}0m`; } /** The banner with a one-line caption under it. */ export function banner(caption: string, on: boolean): string { const c = palette(on); const art = BANNER.map((line) => (on ? gradient(line) : line)).join("\n"); return `\n${art}\n\n ${c.dim("Shared service")} ${c.dim("·")} ${c.bold(caption)}`; } type Rows = [label: string, value: string][]; /** The rows of a panel as aligned `label value` lines. */ function panelLines(rows: Rows, c: ReturnType): string[] { const labelWidth = Math.max(...rows.map(([label]) => label.length)); return rows.map(([label, value]) => `${c.dim(label.padEnd(labelWidth))} ${value}`); } /** Inner width a panel needs for its title and rows. */ function panelWidth(title: string, rows: Rows): number { return Math.max(title.length + 2, ...panelLines(rows, palette(false)).map(width)); } /** A titled box of `label value` rows, at least `min` wide so stacked panels line up. */ export function panel(title: string, rows: Rows, on: boolean, min = 0): string { const c = palette(on); const lines = panelLines(rows, c); const inner = Math.max(min, panelWidth(title, rows)); const top = `${c.dim("╭─")} ${c.bold(title)} ${c.dim(`${"─".repeat(inner - title.length - 1)}╮`)}`; const body = lines.map( (line) => `${c.dim("│")} ${line}${" ".repeat(inner - width(line))} ${c.dim("│")}`, ); return [top, ...body, c.dim(`╰${"─".repeat(inner + 2)}╯`)].map((l) => ` ${l}`).join("\n"); } /** `ps` elapsed time (`[[dd-]hh:]mm:ss`) as "1d 2h", "2h 3m" or "3m 4s". */ export function uptime(etime: string): string | undefined { const match = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+)$/.exec(etime.trim()); if (!match) return undefined; const [days, hours, minutes, seconds] = match.slice(1).map((part) => Number(part ?? 0)); if (days) return `${days}d ${hours}h`; if (hours) return `${hours}h ${minutes}m`; return `${minutes}m ${seconds}s`; } /** `state` and `pid` from `launchctl print gui//