@usex/mikrotik-mcp 6.11.0 → 6.13.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 +42 -5361
- package/dist/index.d.ts +76 -3
- package/dist/index.js +858 -6179
- package/dist/shared/{cli-xkhmxe9c.js → cli-1vn2bbpy.js} +6033 -398
- package/dist/shared/{cli-xgyy9he1.js → cli-4xzq2n6j.js} +1 -1
- package/dist/shared/{cli-p3rfcsg3.js → cli-r1ng5cjy.js} +1 -1
- package/dist/shared/{cli-vrfw477g.js → cli-rcx7e9h4.js} +1 -1
- package/dist/shared/{cli-n6heg9q6.js → cli-w6km895r.js} +1 -1
- package/dist/shared/{library-qx9hax3s.js → library-0qn06vwr.js} +1 -1
- package/dist/shared/{library-dc9pv2hm.js → library-1nhmbsv0.js} +1 -1
- package/dist/shared/{library-zwdxcca2.js → library-1swafsvq.js} +1 -1
- package/dist/shared/{library-w2eyfdqz.js → library-2wd7mt3g.js} +6033 -399
- package/dist/shared/{library-y783969c.js → library-jpmbkkz7.js} +1 -1
- package/dist/ui/observability.html +69 -69
- package/package.json +20 -16
- package/schemas/config.schema.json +13 -0
- package/schemas/devtools-manifest.json +3 -3
- package/schemas/tool-catalog.json +383 -10
- package/schemas/tools/apply_plan.json +6 -1
- package/schemas/tools/update_bfd_configuration.json +8 -0
- package/schemas/tools/update_bgp_connection.json +8 -0
- package/schemas/tools/update_bridge.json +8 -0
- package/schemas/tools/update_dns_static.json +8 -0
- package/schemas/tools/update_dot1x_client.json +8 -0
- package/schemas/tools/update_dot1x_server.json +8 -0
- package/schemas/tools/update_filter_rule.json +8 -0
- package/schemas/tools/update_igmp_proxy_interface.json +8 -0
- package/schemas/tools/update_ip_pool.json +8 -0
- package/schemas/tools/update_ipsec_peer.json +8 -0
- package/schemas/tools/update_ipsec_profile.json +8 -0
- package/schemas/tools/update_ipsec_proposal.json +8 -0
- package/schemas/tools/update_ipv6_filter_rule.json +8 -0
- package/schemas/tools/update_ipv6_mangle_rule.json +8 -0
- package/schemas/tools/update_ipv6_nat_rule.json +8 -0
- package/schemas/tools/update_ipv6_nd.json +8 -0
- package/schemas/tools/update_ipv6_pool.json +8 -0
- package/schemas/tools/update_ipv6_raw_rule.json +8 -0
- package/schemas/tools/update_mangle_rule.json +8 -0
- package/schemas/tools/update_nat_rule.json +8 -0
- package/schemas/tools/update_ospf_instance.json +8 -0
- package/schemas/tools/update_ovpn_server.json +8 -0
- package/schemas/tools/update_ppp_profile.json +8 -0
- package/schemas/tools/update_ppp_secret.json +8 -0
- package/schemas/tools/update_queue_interface.json +8 -0
- package/schemas/tools/update_queue_tree.json +8 -0
- package/schemas/tools/update_queue_type.json +8 -0
- package/schemas/tools/update_radius_server.json +8 -0
- package/schemas/tools/update_rip_instance.json +8 -0
- package/schemas/tools/update_route.json +8 -0
- package/schemas/tools/update_routing_filter_rule.json +8 -0
- package/schemas/tools/update_routing_id.json +8 -0
- package/schemas/tools/update_routing_rule.json +8 -0
- package/schemas/tools/update_routing_table.json +8 -0
- package/schemas/tools/update_rpki_session.json +8 -0
- package/schemas/tools/update_simple_queue.json +8 -0
- package/schemas/tools/update_switch.json +8 -0
- package/schemas/tools/update_switch_port.json +8 -0
- package/schemas/tools/update_switch_port_isolation.json +8 -0
- package/schemas/tools/update_switch_rule.json +8 -0
- package/schemas/tools/update_traffic_monitor.json +8 -0
- package/schemas/tools/update_user_manager_user.json +8 -0
- package/schemas/tools/update_vlan_interface.json +8 -0
- package/schemas/tools/update_wireguard_interface.json +8 -0
- package/schemas/tools/update_wireguard_peer.json +8 -0
- package/schemas/tools/update_wireless_interface.json +8 -0
- package/scripts/service.ts +618 -0
- package/scripts/upgrade.ts +7 -0
|
@@ -0,0 +1,618 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { sleep, spawn } from "bun";
|
|
3
|
+
import { chmod, mkdir, readFile, rename, rmdir, unlink, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
import { Buffer } from "node:buffer";
|
|
9
|
+
|
|
10
|
+
const PACKAGE = "@usex/mikrotik-mcp";
|
|
11
|
+
const LABEL = "dev.usestrict.mikrotik-mcp";
|
|
12
|
+
const UNIT = "mikrotik-mcp.service";
|
|
13
|
+
const TASK = "MikroTik MCP";
|
|
14
|
+
export type Platform = "darwin" | "linux" | "win32";
|
|
15
|
+
export interface ServiceState {
|
|
16
|
+
format: 1;
|
|
17
|
+
platform: Platform;
|
|
18
|
+
bun: string;
|
|
19
|
+
cli: string;
|
|
20
|
+
installRoot: string;
|
|
21
|
+
config: string;
|
|
22
|
+
cwd: string;
|
|
23
|
+
args: string[];
|
|
24
|
+
port: number;
|
|
25
|
+
dashboardPort: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface UpgradeIO {
|
|
29
|
+
install: () => Promise<void>;
|
|
30
|
+
installedVersion: () => Promise<string>;
|
|
31
|
+
restart: () => Promise<void>;
|
|
32
|
+
ready: (version: string) => Promise<boolean>;
|
|
33
|
+
wait: () => Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Restart only a verified installation, and require the running MCP to report that version. */
|
|
37
|
+
export async function upgrade(io: UpgradeIO): Promise<string> {
|
|
38
|
+
await io.install();
|
|
39
|
+
const version = await io.installedVersion();
|
|
40
|
+
if (!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(version))
|
|
41
|
+
throw new Error("Installed CLI did not return a valid version; service was not restarted.");
|
|
42
|
+
await io.restart();
|
|
43
|
+
for (let attempt = 0; attempt < 30; attempt++) {
|
|
44
|
+
if (await io.ready(version)) return version;
|
|
45
|
+
await io.wait();
|
|
46
|
+
}
|
|
47
|
+
throw new Error(
|
|
48
|
+
"Service did not become ready. Check the service logs listed by mikrotik-mcp-service status.",
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Run host service-management commands as argv arrays, never through a shell. */
|
|
53
|
+
async function command(args: string[], env = process.env, visible = false): Promise<string> {
|
|
54
|
+
const child = spawn(args, {
|
|
55
|
+
cwd: homedir(),
|
|
56
|
+
env,
|
|
57
|
+
stdout: visible ? "inherit" : "pipe",
|
|
58
|
+
stderr: "inherit",
|
|
59
|
+
});
|
|
60
|
+
const output = visible ? "" : await new Response(child.stdout as ReadableStream).text();
|
|
61
|
+
if ((await child.exited) !== 0) throw new Error(`Command failed: ${args[0]} ${args[1] ?? ""}`);
|
|
62
|
+
return output.trim();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Confirm the actual HTTP MCP server version, not just a listening port. */
|
|
66
|
+
export async function ready(endpoint: string, version: string): Promise<boolean> {
|
|
67
|
+
let session: string | null = null;
|
|
68
|
+
try {
|
|
69
|
+
const response = await fetch(endpoint, {
|
|
70
|
+
method: "POST",
|
|
71
|
+
headers: {
|
|
72
|
+
"Content-Type": "application/json",
|
|
73
|
+
Accept: "application/json, text/event-stream",
|
|
74
|
+
},
|
|
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
|
+
}),
|
|
85
|
+
signal: AbortSignal.timeout(2000),
|
|
86
|
+
});
|
|
87
|
+
session = response.headers.get("mcp-session-id");
|
|
88
|
+
if (!response.ok) return false;
|
|
89
|
+
const text = await response.text();
|
|
90
|
+
const payload = response.headers.get("content-type")?.includes("text/event-stream")
|
|
91
|
+
? text
|
|
92
|
+
.split("\n")
|
|
93
|
+
.find((line) => line.startsWith("data:"))
|
|
94
|
+
?.slice(5)
|
|
95
|
+
.trim()
|
|
96
|
+
: text;
|
|
97
|
+
return JSON.parse(payload ?? "null")?.result?.serverInfo?.version === version;
|
|
98
|
+
} catch {
|
|
99
|
+
return false;
|
|
100
|
+
} finally {
|
|
101
|
+
if (session)
|
|
102
|
+
await fetch(endpoint, {
|
|
103
|
+
method: "DELETE",
|
|
104
|
+
headers: { "mcp-session-id": session },
|
|
105
|
+
signal: AbortSignal.timeout(2000),
|
|
106
|
+
}).catch(() => {});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Accept only supported OSes and bounded, distinct local listener ports. */
|
|
111
|
+
export function validatePorts(mcp: number, dashboard: number): void {
|
|
112
|
+
if (
|
|
113
|
+
![mcp, dashboard].every((port) => Number.isInteger(port) && port >= 1024 && port <= 65535) ||
|
|
114
|
+
mcp === dashboard
|
|
115
|
+
)
|
|
116
|
+
throw new Error("Use distinct MCP/dashboard ports between 1024 and 65535.");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Escape systemd specifiers and variable expansion without invoking a shell. */
|
|
120
|
+
export function systemdQuote(value: string, commandLine = false): string {
|
|
121
|
+
if (/[\r\n\0]/.test(value)) throw new Error("Paths must not contain control characters.");
|
|
122
|
+
const escaped = value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("%", "%%");
|
|
123
|
+
return `"${commandLine ? escaped.replaceAll("$", () => "$$") : escaped}"`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Quote a Windows argv element using the CommandLineToArgvW backslash rules. */
|
|
127
|
+
export function windowsQuote(value: string): string {
|
|
128
|
+
if (/[\r\n\0]/.test(value)) throw new Error("Paths must not contain control characters.");
|
|
129
|
+
return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Preserve literal data in PowerShell single-quoted strings. */
|
|
133
|
+
export function psQuote(value: string): string {
|
|
134
|
+
if (/[\r\n\0]/.test(value)) throw new Error("Paths must not contain control characters.");
|
|
135
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Render a per-user Linux unit with loopback listeners and restart supervision. */
|
|
139
|
+
export function linuxUnit(state: ServiceState): string {
|
|
140
|
+
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\nEnvironment=MIKROTIK_LOG_LEVEL=warn\n\n[Install]\nWantedBy=default.target\n`;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Create a password-free, current-user Windows logon task with bounded restart retries. */
|
|
144
|
+
export function windowsInstall(state: ServiceState): string {
|
|
145
|
+
return `$ErrorActionPreference='Stop'
|
|
146
|
+
$user=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
|
|
147
|
+
$action=New-ScheduledTaskAction -Execute ${psQuote(state.bun)} -Argument ${psQuote([state.cli, ...state.args].map(windowsQuote).join(" "))} -WorkingDirectory ${psQuote(state.cwd)}
|
|
148
|
+
$trigger=New-ScheduledTaskTrigger -AtLogOn -User $user
|
|
149
|
+
$principal=New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
|
|
150
|
+
$settings=New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
|
|
151
|
+
Register-ScheduledTask -TaskName ${psQuote(TASK)} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description 'MikroTik MCP per-user shared service' | Out-Null
|
|
152
|
+
Start-ScheduledTask -TaskName ${psQuote(TASK)}`;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Use encoded PowerShell so user paths are not interpreted by a command shell. */
|
|
156
|
+
async function powershell(script: string): Promise<string> {
|
|
157
|
+
return command([
|
|
158
|
+
"powershell.exe",
|
|
159
|
+
"-NoProfile",
|
|
160
|
+
"-NonInteractive",
|
|
161
|
+
"-EncodedCommand",
|
|
162
|
+
Buffer.from(`$ErrorActionPreference='Stop'\n${script}`, "utf16le").toString("base64"),
|
|
163
|
+
]);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Locate only this tool's per-user native service registration. */
|
|
167
|
+
function nativeFile(platform: Platform): string {
|
|
168
|
+
return platform === "darwin"
|
|
169
|
+
? join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`)
|
|
170
|
+
: join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "systemd", "user", UNIT);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Read optional files without masking permission or filesystem errors. */
|
|
174
|
+
async function optionalFile(path: string): Promise<string | undefined> {
|
|
175
|
+
try {
|
|
176
|
+
return await readFile(path, "utf8");
|
|
177
|
+
} catch (error) {
|
|
178
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Persist complete metadata privately before exposing it to subsequent commands. */
|
|
184
|
+
async function save(path: string, content: string, mode = 0o600): Promise<void> {
|
|
185
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
186
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
187
|
+
try {
|
|
188
|
+
await writeFile(temporary, content, { mode });
|
|
189
|
+
await rename(temporary, path);
|
|
190
|
+
if (process.platform !== "win32") await chmod(path, mode);
|
|
191
|
+
} finally {
|
|
192
|
+
await unlink(temporary).catch(() => {});
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Adopt the existing macOS helper's LaunchAgent without replacing its environment or flags. */
|
|
197
|
+
async function adoptMac(): Promise<ServiceState | undefined> {
|
|
198
|
+
if (!(await optionalFile(nativeFile("darwin")))) return;
|
|
199
|
+
const agent = JSON.parse(
|
|
200
|
+
await command(["/usr/bin/plutil", "-convert", "json", "-o", "-", nativeFile("darwin")]),
|
|
201
|
+
);
|
|
202
|
+
const [bun, cli, ...args] = agent.ProgramArguments ?? [];
|
|
203
|
+
const suffix = `/install/global/node_modules/${PACKAGE}/dist/cli.js`;
|
|
204
|
+
const option = (name: string) => {
|
|
205
|
+
const i = args.indexOf(name);
|
|
206
|
+
return i < 0 ? undefined : args[i + 1];
|
|
207
|
+
};
|
|
208
|
+
if (
|
|
209
|
+
agent.Label !== LABEL ||
|
|
210
|
+
typeof cli !== "string" ||
|
|
211
|
+
!cli.endsWith(suffix) ||
|
|
212
|
+
!bun?.startsWith("/") ||
|
|
213
|
+
option("--transport") !== "streamable-http" ||
|
|
214
|
+
!["localhost", "127.0.0.1"].includes(option("--mcp-host"))
|
|
215
|
+
)
|
|
216
|
+
throw new Error(
|
|
217
|
+
"Existing LaunchAgent is not a supported Bun loopback service; it was left unchanged.",
|
|
218
|
+
);
|
|
219
|
+
const config = option("--config");
|
|
220
|
+
if (!config) throw new Error("Existing LaunchAgent has no explicit config path.");
|
|
221
|
+
const configuration = JSON.parse(await readFile(config, "utf8"));
|
|
222
|
+
const port = Number(option("--mcp-port"));
|
|
223
|
+
const dashboardPort = Number(option("--dashboard-port") ?? configuration.dashboard?.port ?? 9090);
|
|
224
|
+
validatePorts(port, dashboardPort);
|
|
225
|
+
return {
|
|
226
|
+
format: 1,
|
|
227
|
+
platform: "darwin",
|
|
228
|
+
bun,
|
|
229
|
+
cli,
|
|
230
|
+
installRoot: cli.slice(0, -suffix.length),
|
|
231
|
+
config,
|
|
232
|
+
cwd: agent.WorkingDirectory || homedir(),
|
|
233
|
+
args,
|
|
234
|
+
port,
|
|
235
|
+
dashboardPort,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Control only the saved OS service; router configuration is never involved. */
|
|
240
|
+
async function control(
|
|
241
|
+
state: ServiceState,
|
|
242
|
+
action: "restart" | "status" | "remove",
|
|
243
|
+
): Promise<void> {
|
|
244
|
+
if (state.platform === "darwin") {
|
|
245
|
+
const target = `gui/${process.getuid!()}/${LABEL}`;
|
|
246
|
+
await command(
|
|
247
|
+
action === "restart"
|
|
248
|
+
? ["/bin/launchctl", "kickstart", "-k", target]
|
|
249
|
+
: action === "status"
|
|
250
|
+
? ["/bin/launchctl", "print", target]
|
|
251
|
+
: ["/bin/launchctl", "bootout", target],
|
|
252
|
+
process.env,
|
|
253
|
+
action === "status",
|
|
254
|
+
);
|
|
255
|
+
} else if (state.platform === "linux") {
|
|
256
|
+
await command(
|
|
257
|
+
[
|
|
258
|
+
"systemctl",
|
|
259
|
+
"--user",
|
|
260
|
+
...(action === "remove" ? ["disable", "--now"] : [action]),
|
|
261
|
+
UNIT,
|
|
262
|
+
...(action === "status" ? ["--no-pager"] : []),
|
|
263
|
+
],
|
|
264
|
+
process.env,
|
|
265
|
+
action === "status",
|
|
266
|
+
);
|
|
267
|
+
} else {
|
|
268
|
+
const name = psQuote(TASK);
|
|
269
|
+
const stop = `Stop-ScheduledTask -TaskName ${name}\nfor($i=0;$i -lt 30;$i++){if((Get-ScheduledTask -TaskName ${name}).State -ne 'Running'){break};Start-Sleep -Seconds 1}\nif((Get-ScheduledTask -TaskName ${name}).State -eq 'Running'){throw 'Task did not stop; refusing to start another process.'}`;
|
|
270
|
+
console.warn(
|
|
271
|
+
await powershell(
|
|
272
|
+
action === "status"
|
|
273
|
+
? `Get-ScheduledTask -TaskName ${name} | Select-Object TaskName,State | ConvertTo-Json`
|
|
274
|
+
: action === "restart"
|
|
275
|
+
? `${stop}\nStart-ScheduledTask -TaskName ${name}`
|
|
276
|
+
: `${stop}\nUnregister-ScheduledTask -TaskName ${name} -Confirm:$false`,
|
|
277
|
+
),
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Install the native registration after conflict checks and package verification. */
|
|
283
|
+
async function register(state: ServiceState): Promise<void> {
|
|
284
|
+
if (state.platform === "darwin") {
|
|
285
|
+
const file = nativeFile(state.platform);
|
|
286
|
+
await save(
|
|
287
|
+
file,
|
|
288
|
+
JSON.stringify({
|
|
289
|
+
Label: LABEL,
|
|
290
|
+
ProgramArguments: [state.bun, state.cli, ...state.args],
|
|
291
|
+
WorkingDirectory: state.cwd,
|
|
292
|
+
RunAtLoad: true,
|
|
293
|
+
KeepAlive: true,
|
|
294
|
+
ExitTimeOut: 30,
|
|
295
|
+
ThrottleInterval: 10,
|
|
296
|
+
Umask: 63,
|
|
297
|
+
EnvironmentVariables: { MIKROTIK_LOG_LEVEL: "warn" },
|
|
298
|
+
StandardOutPath: join(state.cwd, "service.stdout.log"),
|
|
299
|
+
StandardErrorPath: join(state.cwd, "service.stderr.log"),
|
|
300
|
+
}),
|
|
301
|
+
);
|
|
302
|
+
await command(["/usr/bin/plutil", "-convert", "xml1", file]);
|
|
303
|
+
await command(["/bin/launchctl", "bootstrap", `gui/${process.getuid!()}`, file]);
|
|
304
|
+
} else if (state.platform === "linux") {
|
|
305
|
+
await save(nativeFile(state.platform), linuxUnit(state));
|
|
306
|
+
await command(["systemctl", "--user", "daemon-reload"]);
|
|
307
|
+
await command(["systemctl", "--user", "enable", "--now", UNIT]);
|
|
308
|
+
} else await powershell(windowsInstall(state));
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Recover an interrupted installation and start an existing registration without duplicating it. */
|
|
312
|
+
async function ensureStarted(state: ServiceState): Promise<void> {
|
|
313
|
+
if (state.platform === "darwin") {
|
|
314
|
+
if (!(await optionalFile(nativeFile("darwin")))) return register(state);
|
|
315
|
+
try {
|
|
316
|
+
await command(["/bin/launchctl", "print", `gui/${process.getuid!()}/${LABEL}`]);
|
|
317
|
+
} catch {
|
|
318
|
+
await command([
|
|
319
|
+
"/bin/launchctl",
|
|
320
|
+
"bootstrap",
|
|
321
|
+
`gui/${process.getuid!()}`,
|
|
322
|
+
nativeFile("darwin"),
|
|
323
|
+
]);
|
|
324
|
+
}
|
|
325
|
+
} else if (state.platform === "linux") {
|
|
326
|
+
if (!(await optionalFile(nativeFile("linux")))) return register(state);
|
|
327
|
+
await command(["systemctl", "--user", "daemon-reload"]);
|
|
328
|
+
await command(["systemctl", "--user", "enable", "--now", UNIT]);
|
|
329
|
+
} else {
|
|
330
|
+
if (
|
|
331
|
+
!(
|
|
332
|
+
await powershell(
|
|
333
|
+
`if(Get-ScheduledTask -TaskName ${psQuote(TASK)} -ErrorAction SilentlyContinue){'exists'}`,
|
|
334
|
+
)
|
|
335
|
+
).includes("exists")
|
|
336
|
+
)
|
|
337
|
+
return register(state);
|
|
338
|
+
await powershell(`Start-ScheduledTask -TaskName ${psQuote(TASK)}`);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Expose the same two commands on every OS, independent of the source checkout. */
|
|
343
|
+
async function installCommands(directory: string, bun: string): Promise<void> {
|
|
344
|
+
const manager = join(directory, "manager.ts");
|
|
345
|
+
if (resolve(fileURLToPath(import.meta.url)) !== resolve(manager))
|
|
346
|
+
await save(manager, await readFile(fileURLToPath(import.meta.url), "utf8"));
|
|
347
|
+
const bin = (await command([bun, "pm", "-g", "bin"])).trim();
|
|
348
|
+
const shellQuote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
349
|
+
for (const [name, action] of [
|
|
350
|
+
["mikrotik-mcp-service", ""],
|
|
351
|
+
["mikrotik-mcp-upgrade", "upgrade"],
|
|
352
|
+
]) {
|
|
353
|
+
if (process.platform === "win32") {
|
|
354
|
+
const quoted = [bun, manager]
|
|
355
|
+
.map((value) => windowsQuote(value).replaceAll("%", "%%"))
|
|
356
|
+
.join(" ");
|
|
357
|
+
await save(
|
|
358
|
+
join(bin, `${name}.cmd`),
|
|
359
|
+
`@echo off\r\nsetlocal DisableDelayedExpansion\r\n${quoted} ${action} %*\r\nexit /b %errorlevel%\r\n`,
|
|
360
|
+
);
|
|
361
|
+
} else
|
|
362
|
+
await save(
|
|
363
|
+
join(bin, name),
|
|
364
|
+
`#!/bin/sh\nexec ${shellQuote(bun)} ${shellQuote(manager)} ${action} "$@"\n`,
|
|
365
|
+
0o755,
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
// The first macOS-only helper lived here and can shadow Bun's bin on PATH.
|
|
369
|
+
if (process.platform === "darwin") {
|
|
370
|
+
const legacy = join(homedir(), ".local", "bin", "mikrotik-mcp-upgrade");
|
|
371
|
+
const source = await optionalFile(legacy);
|
|
372
|
+
if (
|
|
373
|
+
source?.includes('const LABEL = "dev.usestrict.mikrotik-mcp"') &&
|
|
374
|
+
source.includes("macOS only; no sudo.")
|
|
375
|
+
)
|
|
376
|
+
await save(legacy, await readFile(join(bin, "mikrotik-mcp-upgrade"), "utf8"), 0o755);
|
|
377
|
+
}
|
|
378
|
+
console.warn(
|
|
379
|
+
`Commands installed in ${bin}. If your terminal cannot find them, add this directory to PATH.`,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** Verify the CLI and the live MCP version after service activation. */
|
|
384
|
+
async function waitReady(state: ServiceState): Promise<void> {
|
|
385
|
+
const version = await command([state.bun, state.cli, "--version"]);
|
|
386
|
+
await upgrade({
|
|
387
|
+
install: async () => {},
|
|
388
|
+
installedVersion: async () => version,
|
|
389
|
+
restart: async () => {},
|
|
390
|
+
ready: (v) => ready(`http://127.0.0.1:${state.port}/mcp`, v),
|
|
391
|
+
wait: () => sleep(1000),
|
|
392
|
+
});
|
|
393
|
+
console.warn(
|
|
394
|
+
`MikroTik MCP ${version} is ready.\nDashboard: http://127.0.0.1:${state.dashboardPort}\nMCP: http://127.0.0.1:${state.port}/mcp`,
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Parse a deliberately small CLI with strict options and explicit install-only flags. */
|
|
399
|
+
export function serviceOptions(argv: string[]): {
|
|
400
|
+
action: string;
|
|
401
|
+
config?: string;
|
|
402
|
+
port: number;
|
|
403
|
+
dashboardPort: number;
|
|
404
|
+
explicitPorts: boolean;
|
|
405
|
+
} {
|
|
406
|
+
const { values, positionals } = parseArgs({
|
|
407
|
+
args: argv,
|
|
408
|
+
allowPositionals: true,
|
|
409
|
+
strict: true,
|
|
410
|
+
options: {
|
|
411
|
+
config: { type: "string" },
|
|
412
|
+
"mcp-port": { type: "string" },
|
|
413
|
+
"dashboard-port": { type: "string" },
|
|
414
|
+
help: { type: "boolean" },
|
|
415
|
+
},
|
|
416
|
+
});
|
|
417
|
+
const action = values.help ? "help" : (positionals[0] ?? "help");
|
|
418
|
+
if (
|
|
419
|
+
positionals.length > 1 ||
|
|
420
|
+
!["help", "install", "upgrade", "restart", "status", "uninstall"].includes(action)
|
|
421
|
+
)
|
|
422
|
+
throw new Error("Use install, upgrade, restart, status or uninstall. See --help.");
|
|
423
|
+
const explicitPorts = values["mcp-port"] !== undefined || values["dashboard-port"] !== undefined;
|
|
424
|
+
if (action !== "install" && (values.config || explicitPorts))
|
|
425
|
+
throw new Error("Config and port options are only supported by install.");
|
|
426
|
+
const port = Number(values["mcp-port"] ?? 8000);
|
|
427
|
+
const dashboardPort = Number(values["dashboard-port"] ?? 9090);
|
|
428
|
+
validatePorts(port, dashboardPort);
|
|
429
|
+
return { action, config: values.config, port, dashboardPort, explicitPorts };
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Set up, upgrade or remove a local shared server without editing AI client settings. */
|
|
433
|
+
export async function main(argv = process.argv.slice(2)): Promise<void> {
|
|
434
|
+
const options = serviceOptions(argv);
|
|
435
|
+
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
|
+
);
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
if (!["darwin", "linux", "win32"].includes(process.platform))
|
|
442
|
+
throw new Error("Supported platforms: Windows, macOS, Linux with systemd.");
|
|
443
|
+
if (process.getuid?.() === 0) throw new Error("Run as your regular login user, without sudo.");
|
|
444
|
+
const platform = process.platform as Platform;
|
|
445
|
+
const directory = join(homedir(), ".mikrotik-mcp", "service");
|
|
446
|
+
const metadata = join(directory, "service.json");
|
|
447
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
448
|
+
const lock = join(directory, "operation.lock");
|
|
449
|
+
try {
|
|
450
|
+
await mkdir(lock, { mode: 0o700 });
|
|
451
|
+
} catch {
|
|
452
|
+
throw new Error(
|
|
453
|
+
`Another service operation may be running. If a previous command was killed, remove this empty directory: ${lock}`,
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
try {
|
|
457
|
+
const raw = await optionalFile(metadata);
|
|
458
|
+
let state: ServiceState | undefined = raw ? JSON.parse(raw) : undefined;
|
|
459
|
+
if (state && (state.format !== 1 || state.platform !== platform))
|
|
460
|
+
throw new Error("Incompatible service metadata; nothing changed.");
|
|
461
|
+
if (!state && platform === "darwin") state = await adoptMac();
|
|
462
|
+
if (options.action === "install") {
|
|
463
|
+
if (state) {
|
|
464
|
+
if (
|
|
465
|
+
(options.config && resolve(options.config) !== state.config) ||
|
|
466
|
+
(options.explicitPorts &&
|
|
467
|
+
(options.port !== state.port || options.dashboardPort !== state.dashboardPort))
|
|
468
|
+
)
|
|
469
|
+
throw new Error(
|
|
470
|
+
"Service already installed with different settings. Uninstall first; config/history will be retained.",
|
|
471
|
+
);
|
|
472
|
+
} else {
|
|
473
|
+
if (platform === "linux") {
|
|
474
|
+
await command(["systemctl", "--user", "show-environment"]);
|
|
475
|
+
if (await optionalFile(nativeFile(platform)))
|
|
476
|
+
throw new Error("An existing systemd unit was found; refusing to overwrite it.");
|
|
477
|
+
}
|
|
478
|
+
if (
|
|
479
|
+
platform === "win32" &&
|
|
480
|
+
(
|
|
481
|
+
await powershell(
|
|
482
|
+
`if(Get-ScheduledTask -TaskName ${psQuote(TASK)} -ErrorAction SilentlyContinue){'exists'}`,
|
|
483
|
+
)
|
|
484
|
+
).includes("exists")
|
|
485
|
+
)
|
|
486
|
+
throw new Error("An existing scheduled task was found; refusing to overwrite it.");
|
|
487
|
+
const config = resolve(options.config ?? join(homedir(), ".mikrotik-mcp", "devices.json"));
|
|
488
|
+
const current = await optionalFile(config);
|
|
489
|
+
if (!current && options.config) throw new Error(`Config file not found: ${config}`);
|
|
490
|
+
if (current) JSON.parse(current);
|
|
491
|
+
else
|
|
492
|
+
await save(
|
|
493
|
+
config,
|
|
494
|
+
JSON.stringify(
|
|
495
|
+
{
|
|
496
|
+
defaultDevice: "router",
|
|
497
|
+
devices: {
|
|
498
|
+
router: { host: "127.0.0.1", port: 1, username: "admin", disabled: true },
|
|
499
|
+
},
|
|
500
|
+
},
|
|
501
|
+
null,
|
|
502
|
+
2,
|
|
503
|
+
),
|
|
504
|
+
);
|
|
505
|
+
// A listener conflict must not silently attach this service to someone else's server.
|
|
506
|
+
for (const port of [options.port, options.dashboardPort]) {
|
|
507
|
+
const { createServer } = await import("node:net");
|
|
508
|
+
await new Promise<void>((ok, fail) => {
|
|
509
|
+
const server = createServer();
|
|
510
|
+
server.once("error", () =>
|
|
511
|
+
fail(new Error(`Port ${port} is already in use. Choose different install ports.`)),
|
|
512
|
+
);
|
|
513
|
+
server.listen(port, "127.0.0.1", () =>
|
|
514
|
+
server.close((error) => (error ? fail(error) : ok())),
|
|
515
|
+
);
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
const bun = process.execPath;
|
|
519
|
+
const bin = await command([bun, "pm", "-g", "bin"]);
|
|
520
|
+
const installRoot = dirname(bin);
|
|
521
|
+
const cli = join(
|
|
522
|
+
installRoot,
|
|
523
|
+
"install",
|
|
524
|
+
"global",
|
|
525
|
+
"node_modules",
|
|
526
|
+
"@usex",
|
|
527
|
+
"mikrotik-mcp",
|
|
528
|
+
"dist",
|
|
529
|
+
"cli.js",
|
|
530
|
+
);
|
|
531
|
+
if (!(await optionalFile(cli)))
|
|
532
|
+
await command([bun, "add", "--global", `${PACKAGE}@latest`], process.env, true);
|
|
533
|
+
await command([bun, cli, "--version"]);
|
|
534
|
+
const args = [
|
|
535
|
+
"serve",
|
|
536
|
+
"--config",
|
|
537
|
+
config,
|
|
538
|
+
"--transport",
|
|
539
|
+
"streamable-http",
|
|
540
|
+
"--mcp-host",
|
|
541
|
+
"127.0.0.1",
|
|
542
|
+
"--mcp-port",
|
|
543
|
+
String(options.port),
|
|
544
|
+
"--mcp-allowed-hosts",
|
|
545
|
+
`127.0.0.1:${options.port},localhost:${options.port}`,
|
|
546
|
+
"--mcp-allowed-origins",
|
|
547
|
+
`http://127.0.0.1:${options.port},http://localhost:${options.port}`,
|
|
548
|
+
"--dashboard",
|
|
549
|
+
"--dashboard-host",
|
|
550
|
+
"127.0.0.1",
|
|
551
|
+
"--dashboard-port",
|
|
552
|
+
String(options.dashboardPort),
|
|
553
|
+
];
|
|
554
|
+
state = {
|
|
555
|
+
format: 1,
|
|
556
|
+
platform,
|
|
557
|
+
bun,
|
|
558
|
+
cli,
|
|
559
|
+
installRoot,
|
|
560
|
+
config,
|
|
561
|
+
cwd: join(homedir(), ".mikrotik-mcp"),
|
|
562
|
+
args,
|
|
563
|
+
port: options.port,
|
|
564
|
+
dashboardPort: options.dashboardPort,
|
|
565
|
+
};
|
|
566
|
+
await save(metadata, JSON.stringify(state, null, 2));
|
|
567
|
+
}
|
|
568
|
+
await save(metadata, JSON.stringify(state, null, 2));
|
|
569
|
+
await installCommands(directory, state.bun);
|
|
570
|
+
await ensureStarted(state);
|
|
571
|
+
await waitReady(state);
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
if (!state)
|
|
575
|
+
throw new Error("Service is not installed. Run mikrotik-mcp-service install first.");
|
|
576
|
+
if (options.action === "uninstall") {
|
|
577
|
+
await control(state, "remove");
|
|
578
|
+
if (platform !== "win32") await unlink(nativeFile(platform));
|
|
579
|
+
if (platform === "linux") await command(["systemctl", "--user", "daemon-reload"]);
|
|
580
|
+
await unlink(metadata).catch((error) => {
|
|
581
|
+
if (error.code !== "ENOENT") throw error;
|
|
582
|
+
});
|
|
583
|
+
console.warn(
|
|
584
|
+
"Service removed. Config, SSH keys and history were kept. Run install to enable it again.",
|
|
585
|
+
);
|
|
586
|
+
} else if (options.action === "upgrade") {
|
|
587
|
+
const version = await upgrade({
|
|
588
|
+
install: async () => {
|
|
589
|
+
await command(
|
|
590
|
+
[state.bun, "add", "--global", "--no-cache", `${PACKAGE}@latest`],
|
|
591
|
+
{ ...process.env, BUN_INSTALL: state.installRoot },
|
|
592
|
+
true,
|
|
593
|
+
);
|
|
594
|
+
},
|
|
595
|
+
installedVersion: () => command([state.bun, state.cli, "--version"]),
|
|
596
|
+
restart: () => control(state, "restart"),
|
|
597
|
+
ready: (version) => ready(`http://127.0.0.1:${state.port}/mcp`, version),
|
|
598
|
+
wait: () => sleep(1000),
|
|
599
|
+
});
|
|
600
|
+
console.warn(`MikroTik MCP ${version} is ready. Client URLs and config are unchanged.`);
|
|
601
|
+
} else {
|
|
602
|
+
await control(state, options.action as "status" | "restart");
|
|
603
|
+
if (options.action === "restart") await waitReady(state);
|
|
604
|
+
else
|
|
605
|
+
console.warn(
|
|
606
|
+
`Config: ${state.config}\nMCP: http://127.0.0.1:${state.port}/mcp\nLogs: ${platform === "linux" ? `journalctl --user -u ${UNIT}` : platform === "win32" ? "Windows Task Scheduler: MikroTik MCP / Last Run Result" : "LaunchAgent StandardErrorPath / StandardOutPath"}`,
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
} finally {
|
|
610
|
+
await rmdir(lock);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
if (import.meta.main)
|
|
615
|
+
main().catch((error) => {
|
|
616
|
+
console.error(error.message);
|
|
617
|
+
process.exitCode = 1;
|
|
618
|
+
});
|