@usex/mikrotik-mcp 5.18.0 → 5.20.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.
Files changed (76) hide show
  1. package/README.md +213 -5
  2. package/dist/cli.js +3242 -835
  3. package/dist/index.js +169 -28
  4. package/dist/shared/{cli-97csvm6f.js → cli-426pkqe9.js} +8 -0
  5. package/dist/shared/{library-552hdvw2.js → library-73y8qdjr.js} +2619 -537
  6. package/dist/shared/{library-xbg1d52n.js → library-76naf20r.js} +1 -1
  7. package/dist/shared/{library-w5tyng4c.js → library-81amv3az.js} +1 -1
  8. package/dist/shared/{library-08g0pwc9.js → library-krajvnj9.js} +1 -1
  9. package/dist/shared/{library-gmx9pzx3.js → library-y9tt30y1.js} +11 -1
  10. package/dist/ui/aaa.html +8 -8
  11. package/dist/ui/connected-devices.html +8 -8
  12. package/dist/ui/dashboard.html +16 -16
  13. package/dist/ui/fabric.html +11 -11
  14. package/dist/ui/firewall-audit.html +8 -8
  15. package/dist/ui/firewall.html +9 -9
  16. package/dist/ui/interfaces.html +8 -8
  17. package/dist/ui/investigations.html +11 -11
  18. package/dist/ui/observability.html +77 -75
  19. package/dist/ui/operations.html +11 -11
  20. package/dist/ui/records.html +12 -12
  21. package/dist/ui/reports.html +11 -11
  22. package/dist/ui/round-trip.html +11 -11
  23. package/dist/ui/service-health.html +11 -11
  24. package/package.json +22 -22
  25. package/prompts/audit-routeros-containers.md +27 -0
  26. package/prompts/audit-vlan-segmentation.md +31 -0
  27. package/prompts/setup-guest-wifi.md +23 -24
  28. package/prompts/setup-routeros-container.md +36 -0
  29. package/prompts/setup-v2ray-container-proxy.md +68 -194
  30. package/prompts/setup-vlan-network.md +27 -33
  31. package/schemas/README.md +1 -1
  32. package/schemas/devtools-manifest.json +358 -16
  33. package/schemas/tool-catalog.json +1133 -144
  34. package/schemas/tools/add_container.json +42 -30
  35. package/schemas/tools/add_container_env.json +3 -4
  36. package/schemas/tools/add_container_mount.json +10 -4
  37. package/schemas/tools/apply_service_routing.json +23 -0
  38. package/schemas/tools/arm_service_routing.json +23 -0
  39. package/schemas/tools/configure_flight_recorder.json +30 -0
  40. package/schemas/tools/confirm_mcp_settings.json +19 -0
  41. package/schemas/tools/create_service_routing.json +78 -0
  42. package/schemas/tools/design_network_segment.json +22 -6
  43. package/schemas/tools/destroy_recovery_lab.json +18 -0
  44. package/schemas/tools/export_network_incident.json +14 -0
  45. package/schemas/tools/freeze_network_incident.json +14 -0
  46. package/schemas/tools/get_container.json +11 -4
  47. package/schemas/tools/get_flight_recorder.json +7 -0
  48. package/schemas/tools/get_mcp_settings.json +7 -0
  49. package/schemas/tools/get_mcp_settings_schema.json +7 -0
  50. package/schemas/tools/get_recovery_lab.json +7 -0
  51. package/schemas/tools/get_routeros_container_guide.json +22 -0
  52. package/schemas/tools/get_vlan_segmentation_guide.json +14 -0
  53. package/schemas/tools/list_container_envs.json +1 -1
  54. package/schemas/tools/list_container_mounts.json +7 -2
  55. package/schemas/tools/list_containers.json +2 -4
  56. package/schemas/tools/list_service_routing.json +7 -0
  57. package/schemas/tools/poll_recovery_lab.json +14 -0
  58. package/schemas/tools/prepare_recovery_lab.json +23 -0
  59. package/schemas/tools/preview_mcp_settings.json +94 -0
  60. package/schemas/tools/preview_service_routing.json +23 -0
  61. package/schemas/tools/probe_service_routing.json +14 -0
  62. package/schemas/tools/recovery_lab_inventory.json +7 -0
  63. package/schemas/tools/remove_container.json +11 -4
  64. package/schemas/tools/remove_container_env.json +7 -3
  65. package/schemas/tools/remove_container_mount.json +18 -2
  66. package/schemas/tools/rollback_mcp_settings.json +19 -0
  67. package/schemas/tools/service_routing_inventory.json +7 -0
  68. package/schemas/tools/set_container_config.json +4 -6
  69. package/schemas/tools/start_container.json +11 -4
  70. package/schemas/tools/start_recovery_lab.json +18 -0
  71. package/schemas/tools/stop_container.json +11 -4
  72. package/schemas/tools/update_container.json +46 -6
  73. package/schemas/tools/update_mcp_settings.json +110 -0
  74. /package/dist/shared/{cli-3zrj182m.js → cli-6wdstvdq.js} +0 -0
  75. /package/dist/shared/{cli-s423xk9v.js → cli-cvt06346.js} +0 -0
  76. /package/dist/shared/{cli-ff6yww2e.js → cli-z1kavk0z.js} +0 -0
@@ -8446,7 +8446,7 @@ var DEFAULT_BACKUP_DIR2 = join(homedir(), ".mikrotik-mcp", "backups");
8446
8446
  var DEFAULT_CONFIG_HISTORY_DIR = join(homedir(), ".mikrotik-mcp", "config-history");
8447
8447
  var DEFAULT_CONFIG_FILE = join(homedir(), ".mikrotik-mcp", "config.json");
8448
8448
  var TransportSchema = _enum(["stdio", "sse", "streamable-http"]);
8449
- var McpServerSettingsSchema = object({
8449
+ var McpServerSettingsSchema2 = object({
8450
8450
  transport: TransportSchema.default("stdio"),
8451
8451
  host: string().default("0.0.0.0"),
8452
8452
  port: exports_coerce.number().int().positive().default(8000),
@@ -8578,7 +8578,7 @@ var SchedulesConfigSchema = object({
8578
8578
  tickSeconds: exports_coerce.number().int().positive().default(30),
8579
8579
  retainDays: exports_coerce.number().int().positive().default(90)
8580
8580
  });
8581
- var DashboardConfigSchema = object({
8581
+ var DashboardConfigSchema2 = object({
8582
8582
  enabled: boolean().default(false),
8583
8583
  host: string().default("0.0.0.0"),
8584
8584
  port: exports_coerce.number().int().positive().default(9090),
@@ -8590,11 +8590,11 @@ var DashboardConfigSchema = object({
8590
8590
  token: string().optional(),
8591
8591
  feedLimit: exports_coerce.number().int().positive().max(1e4).default(200)
8592
8592
  });
8593
- var MemoryConfigSchema = object({
8593
+ var MemoryConfigSchema2 = object({
8594
8594
  enabled: boolean().default(true),
8595
8595
  dbPath: string().default(DEFAULT_MEMORY_DB)
8596
8596
  });
8597
- var SSHConfigSchema = object({
8597
+ var SSHConfigSchema2 = object({
8598
8598
  keepAlive: boolean().default(true),
8599
8599
  keepAliveInterval: exports_coerce.number().int().nonnegative().default(1e4),
8600
8600
  idleTimeout: exports_coerce.number().int().positive().default(30000)
@@ -8618,19 +8618,19 @@ var MikrotikConfigSchema2 = object({
8618
8618
  serviceProbes: ServiceProbeConfigSchema.default(() => ServiceProbeConfigSchema.parse({})),
8619
8619
  devices: record(string(), DeviceConfigSchema2).default(() => ({ default: DeviceConfigSchema2.parse({}) })),
8620
8620
  defaultDevice: string().default("default"),
8621
- mcp: McpServerSettingsSchema.default(() => McpServerSettingsSchema.parse({})),
8621
+ mcp: McpServerSettingsSchema2.default(() => McpServerSettingsSchema2.parse({})),
8622
8622
  s3: S3ConfigSchema.optional(),
8623
- dashboard: DashboardConfigSchema.default(() => DashboardConfigSchema.parse({})),
8623
+ dashboard: DashboardConfigSchema2.default(() => DashboardConfigSchema2.parse({})),
8624
8624
  alerts: AlertsConfigSchema.optional(),
8625
8625
  flows: FlowsConfigSchema.default(() => FlowsConfigSchema.parse({})),
8626
8626
  policy: PolicyConfigSchema.default(() => PolicyConfigSchema.parse({})),
8627
8627
  schedules: SchedulesConfigSchema.default(() => SchedulesConfigSchema.parse({})),
8628
8628
  attacks: AttacksConfigSchema.default(() => AttacksConfigSchema.parse({})),
8629
- ssh: SSHConfigSchema.default(() => SSHConfigSchema.parse({})),
8629
+ ssh: SSHConfigSchema2.default(() => SSHConfigSchema2.parse({})),
8630
8630
  readOnly: boolean().default(false),
8631
8631
  access: AccessConfigSchema.default(() => AccessConfigSchema.parse({})),
8632
8632
  tools: ToolFilterSchema.default(() => ToolFilterSchema.parse({})),
8633
- memory: MemoryConfigSchema.default(() => MemoryConfigSchema.parse({})),
8633
+ memory: MemoryConfigSchema2.default(() => MemoryConfigSchema2.parse({})),
8634
8634
  backupDir: string().optional(),
8635
8635
  disableUpdateCheck: boolean().default(false)
8636
8636
  });
@@ -8715,6 +8715,9 @@ function parseDevicesSource(raw, fromFile) {
8715
8715
  };
8716
8716
  }
8717
8717
  var configSource = { path: DEFAULT_CONFIG_FILE, fromFile: false };
8718
+ function getConfigSource2() {
8719
+ return configSource;
8720
+ }
8718
8721
  function loadConfig2(argv = process.argv.slice(2)) {
8719
8722
  const flags = parseFlags(argv);
8720
8723
  const pick = (flag, ...envNames) => flags[flag] ?? env(...envNames);
@@ -9063,6 +9066,27 @@ async function openSnapshotStore2(path) {
9063
9066
 
9064
9067
  // src/logger.ts
9065
9068
  import { stderr } from "process";
9069
+
9070
+ // src/utils/container-redaction.ts
9071
+ function redactContainerText(text) {
9072
+ return text.replace(/^(\s*(?:env(?:-current)?|password|(?:default-)?(?:cmd|entrypoint|shell|healthcheck-cmd)|config-json):)[ \t]*[^\r\n]*/gm, "$1 ***").replace(/(^|\s)(env(?:-current)?|value|password|(?:default-)?(?:cmd|entrypoint|shell|healthcheck-cmd)|config-json)=("(?:\\.|[^"\\])*(?:"|$)|[^\s]*)/g, '$1$2="***"');
9073
+ }
9074
+ function containerCommandForLog(command) {
9075
+ if (!/\/container(?:[\s/]|$)/.test(command))
9076
+ return command;
9077
+ const prefix = command.match(/^\[[^\]\r\n]+\] Executing (?:MikroTik command|\(safe mode\)): /)?.[0] ?? "";
9078
+ return `${prefix}${command.match(/\/container(?:[ /](?:config|envs|mounts))?[ /](?:[a-z-]+)/)?.[0] ?? "/container"} [arguments omitted]`;
9079
+ }
9080
+ function redactContainerInput(tool, args) {
9081
+ if (!/(?:^|_)container(?:_|$)/.test(tool) || !args || typeof args !== "object" || Array.isArray(args))
9082
+ return args;
9083
+ return Object.fromEntries(Object.entries(args).map(([key, value]) => [
9084
+ key,
9085
+ ["env", "value", "cmd", "entrypoint", "password"].includes(key) && value != null && value !== "" ? "\xABredacted\xBB" : value
9086
+ ]));
9087
+ }
9088
+
9089
+ // src/logger.ts
9066
9090
  var LEVELS = {
9067
9091
  debug: 10,
9068
9092
  info: 20,
@@ -9080,7 +9104,7 @@ var COLORS = {
9080
9104
  var RESET = "\x1B[0m";
9081
9105
  var useColor = stderr.isTTY ?? false;
9082
9106
  function formatLogMessage(message) {
9083
- const compact = message.replace(/\bfrom=\*[\da-f]+(?:,\*[\da-f]+)+/gi, (list) => `from=<${list.split(",").length} IDs omitted>`);
9107
+ const compact = containerCommandForLog(message).replace(/\bfrom=\*[\da-f]+(?:,\*[\da-f]+)+/gi, (list) => `from=<${list.split(",").length} IDs omitted>`);
9084
9108
  const maxLength = 1024;
9085
9109
  return compact.length <= maxLength ? compact : `${compact.slice(0, maxLength)}\u2026 [${compact.length - maxLength} chars omitted]`;
9086
9110
  }
@@ -11300,7 +11324,7 @@ function buildPrint(path, rest) {
11300
11324
  const [k, v] = pair;
11301
11325
  if (/[~<>!]/.test(k))
11302
11326
  return null;
11303
- query[k] = v;
11327
+ query[k === "proplist" ? ".proplist" : k] = v;
11304
11328
  }
11305
11329
  return { method: "GET", path, query, countOnly };
11306
11330
  }
@@ -11372,10 +11396,10 @@ function toConsoleText(json, req) {
11372
11396
  const entries = Object.entries(json);
11373
11397
  if (entries.length === 0)
11374
11398
  return "";
11375
- return entries.map(([k, v]) => ` ${k}: ${typeof v === "string" ? v : String(v)}`).join(`
11399
+ return entries.map(([k, v]) => ` ${k}: ${typeof v === "string" ? v : JSON.stringify(v) ?? ""}`).join(`
11376
11400
  `);
11377
11401
  }
11378
- return String(json);
11402
+ return typeof json === "string" ? json : JSON.stringify(json) ?? "";
11379
11403
  }
11380
11404
 
11381
11405
  // src/rest/client.ts
@@ -12103,11 +12127,11 @@ async function executeMikrotikCommand2(command, ctx, opts) {
12103
12127
  const deviceName = resolveDeviceName2(ctx.device);
12104
12128
  const safe = getSafeModeManager2(deviceName);
12105
12129
  if (safe.isActive) {
12106
- ctx.info(`[${deviceName}] Executing (safe mode): ${command}`);
12130
+ ctx.info(`[${deviceName}] Executing (safe mode): ${containerCommandForLog(command)}`);
12107
12131
  ctx.transport = "ssh";
12108
12132
  return safe.execute(command);
12109
12133
  }
12110
- ctx.info(`[${deviceName}] Executing MikroTik command: ${command}`);
12134
+ ctx.info(`[${deviceName}] Executing MikroTik command: ${containerCommandForLog(command)}`);
12111
12135
  return runOnce(command, ctx.device, opts, ctx);
12112
12136
  }
12113
12137
  async function uploadFileToDevice(deviceName, remotePath, data) {
@@ -12227,7 +12251,7 @@ async function tryProbe(command, ctx) {
12227
12251
  return null;
12228
12252
  return out;
12229
12253
  } catch (e) {
12230
- logger.debug(`[capability] probe '${command}' failed: ${e instanceof Error ? e.message : e}`);
12254
+ logger.debug(`[capability] probe '${command}' failed: ${e instanceof Error ? e.message : String(e)}`);
12231
12255
  return null;
12232
12256
  }
12233
12257
  }
@@ -12335,7 +12359,7 @@ function buildEvent(raw, id, opts) {
12335
12359
  let output = "";
12336
12360
  let truncated = false;
12337
12361
  if (opts.captureBody) {
12338
- const args = opts.redactInput === false ? raw.args : redact(raw.args);
12362
+ const args = opts.redactInput === false ? raw.args : redact(redactContainerInput(raw.tool, raw.args));
12339
12363
  const rin = truncate(JSON.stringify(args ?? {}), opts.maxBodyBytes);
12340
12364
  const rout = truncate(raw.tool === "create_client_check" ? "Client check created. Private invitation omitted from activity history." : raw.output, opts.maxBodyBytes);
12341
12365
  input = rin.text;
@@ -14821,13 +14845,13 @@ async function undoMigration(id, confirm, selected) {
14821
14845
  throw new Error("Undo lost Safe Mode or exceeded its time budget.");
14822
14846
  await checkedRead(item.undo, createContext(undefined, device));
14823
14847
  }
14824
- const beforeTarget = (await import("./library-w5tyng4c.js")).openSnapshotStore;
14825
- const db = await beforeTarget((await import("./library-gmx9pzx3.js")).DEFAULT_SNAPSHOT_DB);
14848
+ const beforeTarget = (await import("./library-81amv3az.js")).openSnapshotStore;
14849
+ const db = await beforeTarget((await import("./library-y9tt30y1.js")).DEFAULT_SNAPSHOT_DB);
14826
14850
  try {
14827
14851
  const original = db.get(p.snapshots.target);
14828
14852
  if (!original)
14829
14853
  throw new Error("Original target snapshot unavailable.");
14830
- const { normalizeExport } = await import("./library-xbg1d52n.js");
14854
+ const { normalizeExport } = await import("./library-76naf20r.js");
14831
14855
  if (normalizeExport((await migrationInventory(device)).export) !== normalizeExport(original.body))
14832
14856
  throw new Error("Target differs from its backup. Undo verification failed.");
14833
14857
  } finally {
@@ -19608,6 +19632,1162 @@ var serviceContractTools = [
19608
19632
  })
19609
19633
  ];
19610
19634
 
19635
+ // src/service-routing/model.ts
19636
+ import ipaddr2 from "ipaddr.js";
19637
+ import { createHash as createHash5 } from "crypto";
19638
+ var name2 = string().trim().min(1).max(64).regex(/^[a-zA-Z0-9_.-]+$/);
19639
+ var routingInput = object({
19640
+ name: string().trim().min(1).max(80),
19641
+ target: name2.describe("Approved HTTPS alias in serviceProbes.targets; its exact hostname is routed"),
19642
+ family: _enum(["ipv4", "ipv6"]),
19643
+ sources: array(string().refine((v) => ipaddr2.isValidCIDR(v), "Use an explicit client subnet CIDR")).min(1).max(8),
19644
+ tables: array(name2).min(1).max(3),
19645
+ primary: name2,
19646
+ maxLatencyMs: number().int().min(100).max(15000).default(5000),
19647
+ failuresBeforeSwitch: number().int().min(2).max(10).default(3),
19648
+ cooldownSeconds: number().int().min(120).max(3600).default(300)
19649
+ }).superRefine((v, ctx) => {
19650
+ if (!v.tables.includes(v.primary) || new Set(v.tables).size !== v.tables.length)
19651
+ ctx.addIssue({ code: "custom", message: "Choose one unique candidate table as primary" });
19652
+ for (const s of v.sources) {
19653
+ const [ip, bits] = ipaddr2.parseCIDR(s);
19654
+ if (ip.kind() !== v.family || bits === 0)
19655
+ ctx.addIssue({
19656
+ code: "custom",
19657
+ message: "Sources must match the selected IP family and cannot be a default route"
19658
+ });
19659
+ }
19660
+ });
19661
+ var enabled3 = (r) => !["yes", "true"].includes(r.disabled) && !(r.flags ?? "").includes("X");
19662
+ var ownerTag = (id) => `mcp-sr-${id}`;
19663
+ var selector = (tag) => `[find where comment=${quoteValue(tag)}]`;
19664
+ var routingPath = (family) => family === "ipv4" ? "/ip firewall" : "/ipv6 firewall";
19665
+ function fingerprint(facts) {
19666
+ return createHash5("sha256").update(JSON.stringify(facts, (key, value) => ["#", ".id", "bytes", "packets", "last-handshake", "expires-after"].includes(key) ? undefined : value)).digest("hex");
19667
+ }
19668
+ function planCommands(policy, table, facts, remove = false) {
19669
+ const path = routingPath(policy.family), tag = ownerTag(policy.id), chain = `sr-${policy.id.slice(0, 12)}`;
19670
+ if (policy.state === "uncertain")
19671
+ throw new Error("Reconcile uncertain router state before another change.");
19672
+ const owned = facts.mangle.filter((r) => r.comment === tag);
19673
+ if (facts.mangle.some((r) => r.chain === chain && r.comment !== tag))
19674
+ throw new Error("Private chain contains foreign rules; review it first.");
19675
+ if (owned.some((r) => r.chain !== chain && r.chain !== "prerouting"))
19676
+ throw new Error("Owned rules were edited externally; review them first.");
19677
+ if (remove)
19678
+ return [
19679
+ new Cmd(`${path} mangle remove ${selector(tag)}`).build(),
19680
+ new Cmd(`${path} address-list remove ${selector(tag)}`).build()
19681
+ ];
19682
+ const listRows = facts.addresses.filter((r) => [`${tag}-src`, `${tag}-dst`].includes(r.list));
19683
+ const staticRows = listRows.filter((r) => !["yes", "true"].includes(r.dynamic) && !(r.flags ?? "").includes("D"));
19684
+ if (owned.length) {
19685
+ const expectedLists = [
19686
+ ...policy.sources.map((address) => ({ list: `${tag}-src`, address })),
19687
+ { list: `${tag}-dst`, address: policy.host }
19688
+ ];
19689
+ if (staticRows.length !== expectedLists.length || expectedLists.some((e) => !staticRows.some((r) => r.list === e.list && r.address === e.address && r.comment === tag && enabled3(r))))
19690
+ throw new Error("Owned address-list scope changed externally.");
19691
+ if (listRows.some((r) => r.list === `${tag}-src` && !staticRows.includes(r)))
19692
+ throw new Error("Unexpected dynamic source scope.");
19693
+ } else if (policy.state === "active" || listRows.length) {
19694
+ throw new Error("Owned policy is missing or partially present; reconcile first.");
19695
+ }
19696
+ if (!policy.tables.includes(table))
19697
+ throw new Error("This exit is not approved by the policy.");
19698
+ if (!facts.tables.some((r) => r.name === table && enabled3(r) && ["yes", "true"].includes(r.fib)))
19699
+ throw new Error("Exit needs an existing enabled FIB table.");
19700
+ const dst = policy.family === "ipv4" ? "0.0.0.0/0" : "::/0";
19701
+ if (!facts.routes.some((r) => r["routing-table"] === table && r["dst-address"] === dst && enabled3(r) && (["yes", "true"].includes(r.active) || (r.flags ?? "").includes("A"))))
19702
+ throw new Error("Exit has no observed active default route for this family.");
19703
+ if (facts.filters.some((r) => enabled3(r) && r.action === "fasttrack-connection"))
19704
+ throw new Error("FastTrack may bypass this policy. Configure an explicit exclusion before applying.");
19705
+ if (facts.mangle.some((r) => enabled3(r) && r.comment !== tag && ["mark-routing", "jump", "route"].includes(r.action)))
19706
+ throw new Error("Existing routing/jump rules need an administrator conflict review. They will not be overridden.");
19707
+ const result = [];
19708
+ if (owned.length) {
19709
+ if (policy.state !== "active" || !policy.activeTable)
19710
+ throw new Error("Unexpected owned rules exist. Reconcile the router before applying a draft.");
19711
+ const expected = planCommands({ ...policy, state: "draft" }, policy.activeTable, {
19712
+ ...facts,
19713
+ mangle: facts.mangle.filter((r) => r.comment !== tag),
19714
+ addresses: facts.addresses.filter((r) => ![`${tag}-src`, `${tag}-dst`].includes(r.list))
19715
+ }).filter((command) => command.startsWith(`${path} mangle add`)).map((command) => parseRecords(`0 ${command}`).rows[0]);
19716
+ if (owned.length !== expected.length || expected.some((e) => !e || !owned.some((r) => Object.entries(e).filter(([key]) => !["place-before", "#"].includes(key)).every(([key, value]) => r[key] === value) && enabled3(r))))
19717
+ throw new Error("Owned rule scope changed externally. Automatic edits are blocked.");
19718
+ if (owned.filter((r) => r.action === "mark-routing").length !== 1)
19719
+ throw new Error("Owned routing mark is missing or ambiguous.");
19720
+ result.push(new Cmd(`${path} mangle set [find where comment=${quoteValue(tag)} action=mark-routing]`).set("new-routing-mark", table).build());
19721
+ return result;
19722
+ }
19723
+ for (const address of policy.sources)
19724
+ result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-src`).set("address", address).set("comment", tag).build());
19725
+ result.push(new Cmd(`${path} address-list add`).set("list", `${tag}-dst`).set("address", policy.host).set("comment", tag).build());
19726
+ const exclude = policy.family === "ipv4" ? [
19727
+ "0.0.0.0/8",
19728
+ "10.0.0.0/8",
19729
+ "100.64.0.0/10",
19730
+ "127.0.0.0/8",
19731
+ "169.254.0.0/16",
19732
+ "172.16.0.0/12",
19733
+ "192.168.0.0/16",
19734
+ "224.0.0.0/3"
19735
+ ] : ["::/128", "::1/128", "::ffff:0:0/96", "fc00::/7", "fe80::/10", "ff00::/8"];
19736
+ for (const subnet of exclude)
19737
+ result.push(new Cmd(`${path} mangle add`).set("chain", chain).set("dst-address", subnet).set("action", "return").set("comment", tag).build());
19738
+ result.push(new Cmd(`${path} mangle add`).set("chain", chain).set("action", "mark-routing").set("new-routing-mark", table).bool("passthrough", false).set("comment", tag).build());
19739
+ result.push(new Cmd(`${path} mangle add`).set("chain", "prerouting").set("src-address-list", `${tag}-src`).set("dst-address-list", `${tag}-dst`).set("dst-address-type", "!local").set("action", "jump").set("jump-target", chain).set("comment", tag).raw(facts.mangle.length ? "place-before=0" : "").build());
19740
+ return result;
19741
+ }
19742
+
19743
+ // src/service-routing/service.ts
19744
+ import { randomUUID as randomUUID8 } from "crypto";
19745
+ import { isIP as isIP2 } from "net";
19746
+
19747
+ // src/operations/store.ts
19748
+ import { mkdirSync as mkdirSync9, chmodSync } from "fs";
19749
+ import { dirname as dirname9, join as join2 } from "path";
19750
+ class OperationsStore {
19751
+ db;
19752
+ constructor(db) {
19753
+ this.db = db;
19754
+ db.run("PRAGMA busy_timeout = 3000");
19755
+ db.run("CREATE TABLE IF NOT EXISTS workspace_records (kind TEXT, id TEXT, device TEXT, updated INTEGER, body TEXT, PRIMARY KEY(kind,id))");
19756
+ db.run("CREATE INDEX IF NOT EXISTS workspace_device ON workspace_records(kind,device,updated DESC)");
19757
+ db.run("CREATE TABLE IF NOT EXISTS workspace_locks (device TEXT PRIMARY KEY, owner TEXT NOT NULL)");
19758
+ }
19759
+ get(kind, id, device) {
19760
+ const row = this.db.query("SELECT body FROM workspace_records WHERE kind=? AND id=? AND device=?").get(kind, id, device);
19761
+ return row ? JSON.parse(row.body) : undefined;
19762
+ }
19763
+ list(kind, device, limit = 100) {
19764
+ return this.db.query("SELECT body FROM workspace_records WHERE kind=? AND device=? ORDER BY updated DESC LIMIT ?").all(kind, device, Math.min(500, limit)).map((r) => JSON.parse(r.body));
19765
+ }
19766
+ put(kind, record) {
19767
+ this.db.query("INSERT INTO workspace_records VALUES (?,?,?,?,?) ON CONFLICT(kind,id) DO UPDATE SET updated=excluded.updated,body=excluded.body WHERE device=excluded.device").run(kind, record.id, record.device, record.updatedAt, JSON.stringify(record));
19768
+ }
19769
+ delete(kind, id, device) {
19770
+ this.db.query("DELETE FROM workspace_records WHERE kind=? AND id=? AND device=?").run(kind, id, device);
19771
+ }
19772
+ prune(kind, device, before) {
19773
+ this.db.query("DELETE FROM workspace_records WHERE kind=? AND device=? AND updated<?").run(kind, device, before);
19774
+ }
19775
+ lock(device, owner) {
19776
+ const result = this.db.query("INSERT OR IGNORE INTO workspace_locks VALUES (?,?)").run(device, owner);
19777
+ if (!result.changes)
19778
+ throw new Error("Another workspace operation holds this router. An interrupted operation requires reconciliation before retrying.");
19779
+ }
19780
+ unlock(device, owner) {
19781
+ this.db.query("DELETE FROM workspace_locks WHERE device=? AND owner=?").run(device, owner);
19782
+ }
19783
+ }
19784
+ var pending5;
19785
+ function operationsStore() {
19786
+ pending5 ??= (async () => {
19787
+ const path = join2(dirname9(DEFAULT_SNAPSHOT_DB2), "operations.db");
19788
+ mkdirSync9(dirname9(path), { recursive: true, mode: 448 });
19789
+ const { Database } = await import("bun:sqlite");
19790
+ const db = new Database(path, { create: true });
19791
+ chmodSync(path, 384);
19792
+ db.run("PRAGMA journal_mode = WAL");
19793
+ return new OperationsStore(db);
19794
+ })().catch((error) => {
19795
+ pending5 = undefined;
19796
+ throw error;
19797
+ });
19798
+ return pending5;
19799
+ }
19800
+
19801
+ // src/service-routing/service.ts
19802
+ var kind = "service-routing";
19803
+ function access(ctx, tool, write = false) {
19804
+ const device = resolveDeviceName2(ctx.device);
19805
+ assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
19806
+ return device;
19807
+ }
19808
+ async function locked(device, work) {
19809
+ const store = await operationsStore(), owner = randomUUID8();
19810
+ store.lock(device, owner);
19811
+ try {
19812
+ return await work();
19813
+ } finally {
19814
+ store.unlock(device, owner);
19815
+ }
19816
+ }
19817
+ async function routingPolicy(id, device) {
19818
+ const policy = (await operationsStore()).get(kind, id, device);
19819
+ if (!policy)
19820
+ throw new Error("Policy not found on the selected router.");
19821
+ return policy;
19822
+ }
19823
+ function save(policy, message) {
19824
+ policy.updatedAt = Date.now();
19825
+ if (message)
19826
+ policy.history = [{ at: policy.updatedAt, message }, ...policy.history].slice(0, 100);
19827
+ return operationsStore().then((store) => store.put(kind, policy));
19828
+ }
19829
+ async function routingInventory(ctx) {
19830
+ access(ctx, "service_routing_inventory");
19831
+ const tables = await rows("/routing table", "name,fib,disabled", ctx);
19832
+ return {
19833
+ tables: tables.filter((r) => enabled3(r) && ["yes", "true"].includes(r.fib)).map((r) => r.name),
19834
+ targets: Object.entries(getConfig2().serviceProbes.targets).filter(([, t]) => t.kind === "https").map(([alias, t]) => ({ alias, host: t.host }))
19835
+ };
19836
+ }
19837
+ async function listRouting(ctx) {
19838
+ const device = access(ctx, "list_service_routing");
19839
+ return { policies: (await operationsStore()).list(kind, device) };
19840
+ }
19841
+ async function createRouting(input, ctx) {
19842
+ const device = access(ctx, "create_service_routing", true), a = routingInput.parse(input);
19843
+ const target = getConfig2().serviceProbes.targets[a.target];
19844
+ if (!target || target.kind !== "https")
19845
+ throw new Error("Select an administrator-approved HTTPS probe alias first.");
19846
+ const store = await operationsStore();
19847
+ if (store.list(kind, device).length >= 100)
19848
+ throw new Error("Router policy limit reached (100).");
19849
+ const policy = {
19850
+ ...a,
19851
+ id: randomUUID8(),
19852
+ device,
19853
+ host: target.host,
19854
+ updatedAt: Date.now(),
19855
+ state: "draft",
19856
+ samples: [],
19857
+ history: []
19858
+ };
19859
+ await save(policy, "Draft saved. No router changes or probes yet.");
19860
+ return policy;
19861
+ }
19862
+ async function facts(policy, ctx) {
19863
+ const base = routingPath(policy.family);
19864
+ const tables = await rows("/routing table", "name,fib,disabled", ctx);
19865
+ const routes = await rows(policy.family === "ipv4" ? "/ip route" : "/ipv6 route", "routing-table,dst-address,gateway,active,disabled", ctx);
19866
+ const mangle = await rows(`${base} mangle`, "chain,action,new-routing-mark,jump-target,src-address-list,dst-address-list,dst-address-type,dst-address,passthrough,disabled,comment", ctx);
19867
+ const filters = await rows(`${base} filter`, "action,disabled", ctx);
19868
+ if (policy.family === "ipv4") {
19869
+ const active = (await checkedRead("/ip firewall connection print count-only where fasttrack=yes", ctx)).trim();
19870
+ if (!/^\d+$/.test(active) || Number(active) > 0)
19871
+ throw new Error("Active FastTrack connections must drain before routing can be changed.");
19872
+ }
19873
+ const vrfs = await rows("/ip vrf", "name,interfaces,disabled", ctx);
19874
+ const addresses = await rows(`${base} address-list`, "list,address,comment,dynamic,disabled", ctx);
19875
+ return { tables, routes, mangle, filters, vrfs, addresses };
19876
+ }
19877
+ function fetchCommand(address, table, host, path, port) {
19878
+ return `:put [:serialize to=json value=[${new Cmd("/tool fetch").set("address", `${address}@${table}`).set("host", host).set("mode", "https").set("src-path", path).set("port", port).set("http-method", "head").set("check-certificate", "yes").set("http-max-redirect-count", 0).set("idle-timeout", "5s").set("output", "none").flag("as-value", true).build()}]]`;
19879
+ }
19880
+ async function probe(policy, ctx) {
19881
+ const target = getConfig2().serviceProbes.targets[policy.target];
19882
+ if (!target || target.kind !== "https" || target.host !== policy.host)
19883
+ throw new Error("Probe approval changed. Create a new policy.");
19884
+ const vrfs = await rows("/ip vrf", "name,disabled", ctx);
19885
+ let addresses = [];
19886
+ try {
19887
+ addresses = await nativeProbeIO.resolve(target.host, 3000);
19888
+ if (addresses.some((a) => !addressAllowed(a, target.addresses)))
19889
+ addresses = [];
19890
+ } catch {}
19891
+ const address = addresses.find((a) => isIP2(a) === (policy.family === "ipv4" ? 4 : 6));
19892
+ for (const table of policy.tables) {
19893
+ const sample = {
19894
+ table,
19895
+ at: Date.now(),
19896
+ state: "unknown",
19897
+ detail: "No approved DNS answer for this IP family."
19898
+ };
19899
+ if (address) {
19900
+ sample.address = address;
19901
+ sample.detail = "This routing table is not a VRF. A table-only HTTPS path cannot be proved by fetch.";
19902
+ if (vrfs.some((v) => v.name === table && enabled3(v))) {
19903
+ const start = Date.now();
19904
+ try {
19905
+ const raw = await executeMikrotikCommand2(fetchCommand(address, table, target.host, target.path, target.port), ctx, { maxMs: 8000 });
19906
+ sample.elapsedMs = Date.now() - start;
19907
+ if (looksLikeError(raw)) {
19908
+ if (/failure:.*(?:fetch|SSL|connection|timeout|resolving|status)/i.test(raw)) {
19909
+ sample.state = "fail";
19910
+ sample.detail = "Router fetch reported an HTTP, TLS or connection failure.";
19911
+ } else
19912
+ sample.detail = "Router fetch was rejected or unsupported; path health is unknown.";
19913
+ } else {
19914
+ const result = JSON.parse(raw.trim());
19915
+ if (result.status === "finished" && (result.code === undefined || Number(result.code) >= 200 && Number(result.code) < 300)) {
19916
+ sample.state = sample.elapsedMs <= policy.maxLatencyMs ? "pass" : "fail";
19917
+ sample.detail = `HTTPS HEAD completed via VRF ${table}; elapsed includes SSH overhead. Not a client-path or throughput test.`;
19918
+ }
19919
+ }
19920
+ } catch {
19921
+ sample.detail = "Router query did not produce verified fetch evidence. Connection or capability may be unavailable.";
19922
+ }
19923
+ }
19924
+ }
19925
+ policy.samples.push(sample);
19926
+ }
19927
+ policy.samples = policy.samples.slice(-180);
19928
+ await save(policy);
19929
+ }
19930
+ async function probeRouting(id, ctx) {
19931
+ const device = access(ctx, "probe_service_routing");
19932
+ return locked(device, async () => {
19933
+ const policy = await routingPolicy(id, device);
19934
+ await probe(policy, ctx);
19935
+ return policy;
19936
+ });
19937
+ }
19938
+ async function preview(policy, table, remove, ctx) {
19939
+ const snapshot = await facts(policy, ctx);
19940
+ policy.plan = {
19941
+ id: randomUUID8(),
19942
+ table,
19943
+ remove,
19944
+ expiresAt: Date.now() + 120000,
19945
+ fingerprint: fingerprint(snapshot),
19946
+ commands: planCommands(policy, table, snapshot, remove)
19947
+ };
19948
+ await save(policy, "Preview created. Review scope and commands; valid for two minutes.");
19949
+ return policy;
19950
+ }
19951
+ async function previewRouting(id, table, remove, ctx) {
19952
+ const device = access(ctx, "preview_service_routing");
19953
+ return locked(device, async () => preview(await routingPolicy(id, device), table, remove, ctx));
19954
+ }
19955
+ async function apply(policy, planId, ctx) {
19956
+ const plan = policy.plan;
19957
+ if (!plan || plan.id !== planId || plan.expiresAt < Date.now())
19958
+ throw new Error("Preview expired or changed. Preview again before confirming.");
19959
+ access(ctx, "apply_service_routing", true);
19960
+ if (fingerprint(await facts(policy, ctx)) !== plan.fingerprint)
19961
+ throw new Error("Router configuration changed after preview.");
19962
+ const safe = getSafeModeManager2(policy.device);
19963
+ if (safe.isActive)
19964
+ throw new Error("Finish the existing Safe Mode session first.");
19965
+ policy.snapshot = await captureSnapshot(ctx, `Before service route ${policy.name}`, true);
19966
+ policy.state = "uncertain";
19967
+ policy.armedUntil = undefined;
19968
+ await save(policy, "Apply started; outcome must be read back before being considered active.");
19969
+ let owned = false, commitAttempted = false;
19970
+ try {
19971
+ if (!(await safe.enable()).startsWith("Safe mode ENABLED"))
19972
+ throw new Error("Could not acquire Safe Mode.");
19973
+ owned = true;
19974
+ if (fingerprint(await facts(policy, ctx)) !== plan.fingerprint)
19975
+ throw new Error("Router changed while entering Safe Mode.");
19976
+ for (const command of plan.commands)
19977
+ await checkedRead(command, ctx);
19978
+ const after = await facts(policy, ctx);
19979
+ const matched = after.mangle.filter((r) => r.comment === ownerTag(policy.id));
19980
+ if (plan.remove ? matched.length !== 0 : matched.filter((r) => r.action === "mark-routing" && r["new-routing-mark"] === plan.table && enabled3(r)).length !== 1)
19981
+ throw new Error("Router read-back did not match this preview.");
19982
+ if (plan.remove) {
19983
+ if (after.addresses.some((r) => r.comment === ownerTag(policy.id)))
19984
+ throw new Error("Owned address-list removal not confirmed.");
19985
+ } else {
19986
+ planCommands({ ...policy, state: "active", activeTable: plan.table }, plan.table, after);
19987
+ }
19988
+ await checkedRead("/system identity print", ctx);
19989
+ commitAttempted = true;
19990
+ if (!(await safe.commit()).ok)
19991
+ throw new Error("Commit outcome uncertain. Do not replay the change.");
19992
+ owned = false;
19993
+ policy.state = plan.remove ? "removed" : "active";
19994
+ policy.activeTable = plan.remove ? undefined : plan.table;
19995
+ policy.lastSwitchAt = Date.now();
19996
+ policy.plan = undefined;
19997
+ policy.error = undefined;
19998
+ await save(policy, plan.remove ? "Owned routing policy removed." : `Routing read-back verified: ${plan.table}. Client delivery still requires a client check.`);
19999
+ } catch (error) {
20000
+ if (owned && !commitAttempted)
20001
+ await safe.rollback().catch(() => {});
20002
+ policy.error = error instanceof Error ? error.message : "Apply failed";
20003
+ await save(policy, "Apply not confirmed; automation stopped. Inspect the saved backup and router state.");
20004
+ throw error;
20005
+ }
20006
+ return policy;
20007
+ }
20008
+ async function applyRouting(id, planId, confirm, ctx) {
20009
+ const device = access(ctx, "apply_service_routing", true);
20010
+ if (!confirm)
20011
+ throw new Error("Explicit confirmation of the exact preview is required.");
20012
+ return locked(device, async () => apply(await routingPolicy(id, device), planId, ctx));
20013
+ }
20014
+ async function armRouting(id, minutes, confirm, ctx) {
20015
+ const device = access(ctx, "arm_service_routing", true);
20016
+ if (!confirm)
20017
+ throw new Error("Confirm the time-limited automatic failover authorization.");
20018
+ if (!Number.isInteger(minutes) || minutes < 0 || minutes > 60)
20019
+ throw new Error("Authorization must be 0\u201360 minutes.");
20020
+ return locked(device, async () => {
20021
+ const policy = await routingPolicy(id, device);
20022
+ if (minutes) {
20023
+ const other = (await operationsStore()).list(kind, device).some((p) => p.id !== id && (p.armedUntil ?? 0) > Date.now());
20024
+ if (other)
20025
+ throw new Error("Only one automatic service policy per router can be armed at a time.");
20026
+ if (policy.state !== "active" || policy.tables.length < 2)
20027
+ throw new Error("Apply a policy with at least two exits first.");
20028
+ const now = Date.now();
20029
+ if (policy.tables.some((t) => !policy.samples.some((s) => s.table === t && s.state === "pass" && now - s.at < 120000)))
20030
+ throw new Error("Every authorized exit needs a fresh passing VRF probe before arming.");
20031
+ }
20032
+ policy.armedUntil = minutes ? Date.now() + minutes * 60000 : undefined;
20033
+ await save(policy, minutes ? `Automatic failover authorized for ${minutes} minutes, only between the saved exits.` : "Automatic failover paused; the current route stays in place.");
20034
+ return policy;
20035
+ });
20036
+ }
20037
+
20038
+ // src/tools/service-routing.ts
20039
+ var serviceRoutingTools = [
20040
+ defineTool2({
20041
+ name: "list_service_routing",
20042
+ title: "List Service Routing Policies",
20043
+ annotations: READ,
20044
+ description: "Read persistent domain routing policies, path evidence, primary exit, history and authorization expiry for this router. No probes or router changes.",
20045
+ inputSchema: {},
20046
+ async handler(_, ctx) {
20047
+ return JSON.stringify(await listRouting(ctx));
20048
+ }
20049
+ }),
20050
+ defineTool2({
20051
+ name: "service_routing_inventory",
20052
+ title: "Discover Service Routing Exits",
20053
+ annotations: READ,
20054
+ description: "Read enabled FIB tables and administrator-approved HTTPS target aliases. A table is not proof of a working path; HTTPS per-exit probes require a matching VRF.",
20055
+ inputSchema: {},
20056
+ async handler(_, ctx) {
20057
+ return JSON.stringify(await routingInventory(ctx));
20058
+ }
20059
+ }),
20060
+ defineTool2({
20061
+ name: "create_service_routing",
20062
+ title: "Create Service Routing Draft",
20063
+ annotations: WRITE,
20064
+ description: "Save a single-family policy for one approved exact hostname and explicit client subnets. No router changes. Create separate IPv4/IPv6 policies. Shared CDN IPs can affect other services. Preview, then explicitly confirm apply; never infer authorization from a draft.",
20065
+ inputSchema: routingInput.shape,
20066
+ async handler(a, ctx) {
20067
+ return JSON.stringify(await createRouting(a, ctx));
20068
+ }
20069
+ }),
20070
+ defineTool2({
20071
+ name: "probe_service_routing",
20072
+ title: "Probe Service Exits",
20073
+ annotations: READ,
20074
+ description: "Run bounded, IP-approved HTTPS HEAD fetches from the router through matching VRFs, certificate validation on, redirects off. No files/bodies stored. Table-only exits remain UNKNOWN. SSH overhead is included; not end-client reachability or throughput proof.",
20075
+ inputSchema: { id: uuid2() },
20076
+ async handler(a, ctx) {
20077
+ return JSON.stringify(await probeRouting(a.id, ctx));
20078
+ }
20079
+ }),
20080
+ defineTool2({
20081
+ name: "preview_service_routing",
20082
+ title: "Preview Service Routing Change",
20083
+ annotations: READ,
20084
+ description: "Read router state and save a two-minute, state-bound preview for applying/switching or removing only owned rules. Reject FastTrack and foreign policy-routing conflicts. Does not create exits, NAT, DNS interception or change router configuration.",
20085
+ inputSchema: {
20086
+ id: uuid2(),
20087
+ table: string().min(1).max(64),
20088
+ remove: boolean().default(false)
20089
+ },
20090
+ async handler(a, ctx) {
20091
+ return JSON.stringify(await previewRouting(a.id, a.table, a.remove, ctx));
20092
+ }
20093
+ }),
20094
+ defineTool2({
20095
+ name: "apply_service_routing",
20096
+ title: "Apply Approved Service Routing Preview",
20097
+ annotations: WRITE,
20098
+ description: "After explicit user confirmation, apply the exact fresh preview with a backup, exclusive Safe Mode and read-back. Router DNS maintains the owned destination list. Does not touch output/input chains. An ambiguous write is never retried; inspect router state. An apply pauses automatic failover.",
20099
+ inputSchema: { id: uuid2(), planId: uuid2(), confirm: boolean().default(false) },
20100
+ async handler(a, ctx) {
20101
+ return JSON.stringify(await applyRouting(a.id, a.planId, a.confirm, ctx));
20102
+ }
20103
+ }),
20104
+ defineTool2({
20105
+ name: "arm_service_routing",
20106
+ title: "Authorize Time-Limited Service Failover",
20107
+ annotations: WRITE,
20108
+ description: "Explicitly authorize automatic switching between saved exits for 1-60 minutes, or pause with 0. Requires fresh passing VRF evidence for every exit, consecutive definite failures and cooldown; UNKNOWN never triggers a switch. Expiry stops automation but retains the current route. No new exits or global policy rewrites.",
20109
+ inputSchema: {
20110
+ id: uuid2(),
20111
+ minutes: number().int().min(0).max(60),
20112
+ confirm: boolean().default(false)
20113
+ },
20114
+ async handler(a, ctx) {
20115
+ return JSON.stringify(await armRouting(a.id, a.minutes, a.confirm, ctx));
20116
+ }
20117
+ })
20118
+ ];
20119
+
20120
+ // src/flight-recorder/model.ts
20121
+ var recorderInput = object({
20122
+ enabled: boolean(),
20123
+ intervalSeconds: number().int().min(30).max(300).default(60),
20124
+ windowMinutes: number().int().min(15).max(360).default(60),
20125
+ retentionDays: number().int().min(1).max(30).default(7)
20126
+ });
20127
+ function blankFlight(device, now) {
20128
+ return {
20129
+ id: device,
20130
+ device,
20131
+ updatedAt: now,
20132
+ enabled: false,
20133
+ intervalSeconds: 60,
20134
+ windowMinutes: 60,
20135
+ retentionDays: 7,
20136
+ samples: [],
20137
+ events: [],
20138
+ incidents: [],
20139
+ seenLogs: []
20140
+ };
20141
+ }
20142
+ function trimFlight(record, now) {
20143
+ const since = now - record.windowMinutes * 60000;
20144
+ record.samples = record.samples.filter((s) => s.at >= since).slice(-720);
20145
+ record.events = record.events.filter((s) => s.at >= since).slice(-500);
20146
+ record.seenLogs = record.seenLogs.slice(-500);
20147
+ record.incidents = record.incidents.filter((i) => i.at >= now - record.retentionDays * 86400000).slice(-30);
20148
+ for (const i of record.incidents) {
20149
+ i.samples = i.samples.slice(-720);
20150
+ i.events = i.events.slice(-500);
20151
+ i.complete = now >= i.until || !record.enabled;
20152
+ }
20153
+ record.updatedAt = now;
20154
+ return record;
20155
+ }
20156
+ function freezeFlight(record, title, trigger, now) {
20157
+ const incident = {
20158
+ id: crypto.randomUUID(),
20159
+ at: now,
20160
+ until: record.enabled ? now + 120000 : now,
20161
+ title,
20162
+ trigger,
20163
+ samples: structuredClone(record.samples),
20164
+ events: structuredClone(record.events),
20165
+ complete: !record.enabled
20166
+ };
20167
+ record.incidents.push(incident);
20168
+ return incident;
20169
+ }
20170
+
20171
+ // src/flight-recorder/service.ts
20172
+ var kind2 = "flight-recorder";
20173
+ var queues = new Map;
20174
+ function access2(ctx, tool, write = false) {
20175
+ const device = resolveDeviceName2(ctx.device);
20176
+ assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
20177
+ return device;
20178
+ }
20179
+ async function record2(device) {
20180
+ return (await operationsStore()).get(kind2, device, device) ?? blankFlight(device, Date.now());
20181
+ }
20182
+ async function edit(device, work) {
20183
+ const task = (queues.get(device) ?? Promise.resolve()).catch(() => {}).then(async () => {
20184
+ const store = await operationsStore(), owner = crypto.randomUUID(), key = `flight:${device}`;
20185
+ store.lock(key, owner);
20186
+ try {
20187
+ const r = await record2(device), result = await work(r);
20188
+ store.put(kind2, trimFlight(r, Date.now()));
20189
+ return result;
20190
+ } finally {
20191
+ store.unlock(key, owner);
20192
+ }
20193
+ });
20194
+ queues.set(device, task);
20195
+ try {
20196
+ return await task;
20197
+ } finally {
20198
+ if (queues.get(device) === task)
20199
+ queues.delete(device);
20200
+ }
20201
+ }
20202
+ async function getFlight(ctx) {
20203
+ const device = access2(ctx, "get_flight_recorder");
20204
+ return {
20205
+ recorder: trimFlight(await record2(device), Date.now()),
20206
+ toolEventsAvailable: isRecording(),
20207
+ limitations: [
20208
+ "SSH-polled log metadata, not a lossless syslog receiver.",
20209
+ "Receive-time correlation is not proof of cause or actor identity.",
20210
+ "No capture while MCP is stopped; missing observations are not healthy samples."
20211
+ ]
20212
+ };
20213
+ }
20214
+ async function configureFlight(input, ctx) {
20215
+ const device = access2(ctx, "configure_flight_recorder", true), a = recorderInput.parse(input);
20216
+ await edit(device, async (r) => {
20217
+ Object.assign(r, a);
20218
+ r.error = undefined;
20219
+ });
20220
+ return getFlight(ctx);
20221
+ }
20222
+ async function freezeIncident(title, ctx) {
20223
+ const device = access2(ctx, "freeze_network_incident", true);
20224
+ if (!title.trim() || title.length > 120)
20225
+ throw new Error("Use a 1\u2013120 character incident title.");
20226
+ await edit(device, async (r) => {
20227
+ freezeFlight(r, title.trim(), "manual", Date.now());
20228
+ });
20229
+ return getFlight(ctx);
20230
+ }
20231
+ async function exportIncident(id, ctx) {
20232
+ const device = access2(ctx, "export_network_incident"), r = await record2(device);
20233
+ const incident = trimFlight(r, Date.now()).incidents.find((i) => i.id === id);
20234
+ if (!incident)
20235
+ throw new Error("Incident not found on the selected router or retention expired.");
20236
+ return {
20237
+ format: "mikrotik-flight-recorder/v1",
20238
+ device,
20239
+ exportedAt: Date.now(),
20240
+ incident,
20241
+ privacy: "Review device/interface names before sharing. Raw logs, commands, arguments and credentials are excluded.",
20242
+ interpretation: "Chronology is receipt time on the MCP host. Correlation is not causation; routerTime is untrusted, uncorrected router text."
20243
+ };
20244
+ }
20245
+
20246
+ // src/tools/flight-recorder.ts
20247
+ var flightRecorderTools = [
20248
+ defineTool2({
20249
+ name: "get_flight_recorder",
20250
+ title: "Read Network Flight Recorder",
20251
+ annotations: READ,
20252
+ description: "Read bounded persistent telemetry, off-router log metadata, capture gaps and frozen incidents for this router. No active probes. Times are host receipt times; correlation never proves cause, identity or a network outage.",
20253
+ inputSchema: {},
20254
+ async handler(_, ctx) {
20255
+ return JSON.stringify(await getFlight(ctx));
20256
+ }
20257
+ }),
20258
+ defineTool2({
20259
+ name: "configure_flight_recorder",
20260
+ title: "Configure Network Flight Recorder",
20261
+ annotations: WRITE,
20262
+ description: "Explicitly enable/disable periodic read-only router collection and local retention. No router configuration writes. Stores bounded resources, interface state, classified log metadata and MCP write/failure metadata; no raw messages or credentials. Requires the MCP process to stay running. SSH polling can miss logs; not a lossless syslog service.",
20263
+ inputSchema: recorderInput.shape,
20264
+ async handler(a, ctx) {
20265
+ return JSON.stringify(await configureFlight(a, ctx));
20266
+ }
20267
+ }),
20268
+ defineTool2({
20269
+ name: "freeze_network_incident",
20270
+ title: "Freeze Network Incident Evidence",
20271
+ annotations: WRITE,
20272
+ description: "Preserve this router's available rolling evidence plus two minutes of future samples when recording is enabled. Local operation only. Empty history stays empty; cannot recover past logs. Maximum 30 incidents, configured age retention.",
20273
+ inputSchema: { title: string().trim().min(1).max(120) },
20274
+ async handler(a, ctx) {
20275
+ return JSON.stringify(await freezeIncident(a.title, ctx));
20276
+ }
20277
+ }),
20278
+ defineTool2({
20279
+ name: "export_network_incident",
20280
+ title: "Export Network Incident Evidence",
20281
+ annotations: READ,
20282
+ description: "Export a device-scoped frozen incident with coverage gaps and separate router/receive timestamps. No raw logs or command bodies. Review device/interface names before sharing. Do not attribute an attack to a user based only on these observations.",
20283
+ inputSchema: { id: uuid2() },
20284
+ async handler(a, ctx) {
20285
+ return JSON.stringify(await exportIncident(a.id, ctx));
20286
+ }
20287
+ })
20288
+ ];
20289
+
20290
+ // src/recovery-lab/model.ts
20291
+ import { createHash as createHash6 } from "crypto";
20292
+ var rosVersion = string().regex(/^7\.\d+(?:\.\d+)?(?:beta\d+|rc\d+)?$/);
20293
+ var recoveryInput = object({
20294
+ snapshotId: string().min(1).max(100),
20295
+ version: rosVersion,
20296
+ mode: _enum(["restore", "upgrade"]).default("restore")
20297
+ });
20298
+ var REQUIRED_CHECKS = [
20299
+ "authenticated-boot",
20300
+ "import",
20301
+ "configuration-readback",
20302
+ "reboot-persistence",
20303
+ "isolation"
20304
+ ];
20305
+ var capabilitiesSchema = object({
20306
+ protocol: literal("mikrotik-recovery/v1"),
20307
+ runnerId: string().regex(/^[a-zA-Z0-9_.-]{1,80}$/),
20308
+ isolated: literal(true),
20309
+ productionNetworkAccess: literal(false),
20310
+ disposable: literal(true),
20311
+ enforcesTtl: literal(true),
20312
+ versions: array(object({
20313
+ version: rosVersion,
20314
+ imageSha256: string().regex(/^[a-f0-9]{64}$/),
20315
+ architecture: _enum(["x86_64", "aarch64"])
20316
+ })).min(1).max(30).refine((versions) => new Set(versions.map((v) => v.version)).size === versions.length, {
20317
+ message: "Each RouterOS version must identify one unambiguous pinned image."
20318
+ })
20319
+ });
20320
+ var resultSchema = object({
20321
+ protocol: literal("mikrotik-recovery/v1"),
20322
+ id: uuid2(),
20323
+ requestSha256: string().regex(/^[a-f0-9]{64}$/),
20324
+ runnerId: string().min(1).max(80),
20325
+ version: rosVersion,
20326
+ state: _enum(["running", "completed", "failed", "destroyed"]),
20327
+ isolated: literal(true),
20328
+ productionNetworkAccess: literal(false),
20329
+ checks: array(object({
20330
+ name: _enum(REQUIRED_CHECKS),
20331
+ state: _enum(["pass", "fail", "unsupported", "pending"]),
20332
+ detail: string().max(500)
20333
+ })).max(5),
20334
+ elapsedMs: number().int().min(0).max(3600000).optional(),
20335
+ cleanup: _enum(["pending", "destroyed", "failed"])
20336
+ });
20337
+ var sha256 = (value) => createHash6("sha256").update(value).digest("hex");
20338
+ var FIELDS = {
20339
+ "/interface/bridge": ["name", "protocol-mode", "vlan-filtering", "pvid", "disabled"],
20340
+ "/interface/vlan": ["name", "interface", "vlan-id", "disabled"],
20341
+ "/interface/bridge/port": [
20342
+ "bridge",
20343
+ "interface",
20344
+ "pvid",
20345
+ "ingress-filtering",
20346
+ "frame-types",
20347
+ "disabled"
20348
+ ],
20349
+ "/interface/bridge/vlan": ["bridge", "tagged", "untagged", "vlan-ids", "disabled"],
20350
+ "/interface/list": ["name", "include", "exclude"],
20351
+ "/interface/list/member": ["list", "interface", "disabled"],
20352
+ "/ip/address": ["address", "interface", "network", "disabled"],
20353
+ "/ipv6/address": ["address", "interface", "advertise", "disabled"],
20354
+ "/ip/route": [
20355
+ "dst-address",
20356
+ "gateway",
20357
+ "distance",
20358
+ "routing-table",
20359
+ "scope",
20360
+ "target-scope",
20361
+ "disabled",
20362
+ "blackhole"
20363
+ ],
20364
+ "/ipv6/route": [
20365
+ "dst-address",
20366
+ "gateway",
20367
+ "distance",
20368
+ "routing-table",
20369
+ "scope",
20370
+ "target-scope",
20371
+ "disabled",
20372
+ "blackhole"
20373
+ ],
20374
+ "/routing/table": ["name", "fib", "disabled"],
20375
+ "/ip/firewall/filter": [
20376
+ "chain",
20377
+ "action",
20378
+ "protocol",
20379
+ "src-address",
20380
+ "dst-address",
20381
+ "src-port",
20382
+ "dst-port",
20383
+ "connection-state",
20384
+ "in-interface",
20385
+ "out-interface",
20386
+ "in-interface-list",
20387
+ "out-interface-list",
20388
+ "disabled"
20389
+ ],
20390
+ "/ipv6/firewall/filter": [
20391
+ "chain",
20392
+ "action",
20393
+ "protocol",
20394
+ "src-address",
20395
+ "dst-address",
20396
+ "src-port",
20397
+ "dst-port",
20398
+ "connection-state",
20399
+ "in-interface",
20400
+ "out-interface",
20401
+ "in-interface-list",
20402
+ "out-interface-list",
20403
+ "disabled"
20404
+ ]
20405
+ };
20406
+ function buildRecoverySubset(body) {
20407
+ if (body.length > 512000)
20408
+ throw new Error("Snapshot exceeds the 512 KB rehearsal limit.");
20409
+ const model = parseExport(body), commands = [], coverage = [];
20410
+ for (const section of model.sections) {
20411
+ const allowed = FIELDS[section.path];
20412
+ let included = 0, excluded = 0;
20413
+ for (const row of section.records) {
20414
+ const fields = Object.entries(row.fields).filter(([key]) => key !== "comment");
20415
+ if (!allowed || row.op !== "add" || /[$[\]{};\\\r\n]/.test(row.raw) || fields.some(([key, value]) => !allowed.includes(key) || value.length > 200) || fields.length === 0 || row.flags.length > 0) {
20416
+ excluded++;
20417
+ continue;
20418
+ }
20419
+ let cmd = new Cmd(`${section.path.replaceAll("/", " ").trimStart().replace(/^/, "/")} add`);
20420
+ for (const [key, value] of fields)
20421
+ cmd = cmd.set(key, value);
20422
+ commands.push(cmd.build());
20423
+ included++;
20424
+ }
20425
+ coverage.push({
20426
+ scope: section.path,
20427
+ included,
20428
+ excluded,
20429
+ reason: excluded ? "Unsupported scope, operation, field or expression: not sent to the lab." : undefined
20430
+ });
20431
+ }
20432
+ if (model.unparsed.length)
20433
+ coverage.push({
20434
+ scope: "unparsed lines",
20435
+ included: 0,
20436
+ excluded: model.unparsed.length,
20437
+ reason: "Unparsed text is never executed."
20438
+ });
20439
+ if (commands.length > 300)
20440
+ throw new Error("More than 300 portable records. Prepare a smaller reviewed snapshot.");
20441
+ return { commands, coverage };
20442
+ }
20443
+ function validateRunnerResult(input, run) {
20444
+ const result = resultSchema.parse(input);
20445
+ if (result.id !== run.id || result.runnerId !== run.runnerId || result.requestSha256 !== run.requestSha256 || result.version !== run.version)
20446
+ throw new Error("Runner evidence does not match this immutable rehearsal.");
20447
+ if (new Set(result.checks.map((c) => c.name)).size !== result.checks.length)
20448
+ throw new Error("Duplicate runner checks are not valid evidence.");
20449
+ if (result.state === "destroyed" && result.cleanup !== "destroyed")
20450
+ throw new Error("Destruction is not confirmed.");
20451
+ return result;
20452
+ }
20453
+ function resultState(result) {
20454
+ if (result.state === "destroyed")
20455
+ return "destroyed";
20456
+ if (result.state === "failed" || result.checks.some((c) => c.state === "fail"))
20457
+ return "failed";
20458
+ if (result.state === "running")
20459
+ return "running";
20460
+ return REQUIRED_CHECKS.every((name) => result.checks.some((c) => c.name === name && c.state === "pass")) ? "passed" : "uncertain";
20461
+ }
20462
+
20463
+ // src/recovery-lab/runner.ts
20464
+ function runnerConfig() {
20465
+ const value = process.env.MIKROTIK_RECOVERY_RUNNER_URL;
20466
+ const token = process.env.MIKROTIK_RECOVERY_RUNNER_TOKEN;
20467
+ if (!value && !token)
20468
+ return;
20469
+ if (!value || !token || token.length < 24 || /[\r\n]/.test(token))
20470
+ throw new Error("Recovery runner URL and a token of at least 24 characters must be configured by the administrator.");
20471
+ const url = new URL(value);
20472
+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/" || !(url.protocol === "https:" || url.protocol === "http:" && ["127.0.0.1", "[::1]"].includes(url.hostname)))
20473
+ throw new Error("Recovery runner needs an HTTPS origin (or explicit loopback HTTP), without path, query or URL credentials.");
20474
+ return { base: url.origin, token, binding: sha256(`${url.origin}
20475
+ ${token}`) };
20476
+ }
20477
+ async function callRunner(method, path, body) {
20478
+ const cfg = runnerConfig();
20479
+ if (!cfg)
20480
+ throw new Error("No isolated recovery runner configured. Prepare and inspect locally; execution is unavailable.");
20481
+ if (!/^\/v1\/(capabilities|runs\/[a-f0-9-]{36})$/.test(path))
20482
+ throw new Error("Invalid runner operation.");
20483
+ if (method === "GET" && body !== undefined)
20484
+ throw new Error("Read-only runner operations cannot contain a request body.");
20485
+ const options = {
20486
+ method,
20487
+ headers: { authorization: `Bearer ${cfg.token}`, "content-type": "application/json" },
20488
+ redirect: "error",
20489
+ signal: AbortSignal.timeout(1e4)
20490
+ };
20491
+ if (method !== "GET" && body !== undefined)
20492
+ options.body = JSON.stringify(body);
20493
+ const response = await fetch(`${cfg.base}${path}`, options);
20494
+ if (!response.ok) {
20495
+ await response.body?.cancel();
20496
+ throw new Error(`Recovery runner returned HTTP ${response.status}; no automatic write retry.`);
20497
+ }
20498
+ const reader = response.body?.getReader();
20499
+ if (!reader)
20500
+ throw new Error("Runner returned no evidence.");
20501
+ const chunks = [];
20502
+ let size = 0;
20503
+ try {
20504
+ while (true) {
20505
+ const part = await reader.read();
20506
+ if (part.done)
20507
+ break;
20508
+ size += part.value.length;
20509
+ if (size > 65536)
20510
+ throw new Error("Runner evidence exceeds the 64 KB limit.");
20511
+ chunks.push(part.value);
20512
+ }
20513
+ } finally {
20514
+ await reader.cancel().catch(() => {});
20515
+ }
20516
+ const data = new Uint8Array(size);
20517
+ let offset = 0;
20518
+ for (const part of chunks) {
20519
+ data.set(part, offset);
20520
+ offset += part.length;
20521
+ }
20522
+ return JSON.parse(new TextDecoder().decode(data));
20523
+ }
20524
+
20525
+ // src/recovery-lab/service.ts
20526
+ var kind3 = "recovery-lab";
20527
+ function access3(ctx, tool, write = false) {
20528
+ const device = resolveDeviceName2(ctx.device);
20529
+ assertDeviceAccess([device], tool, write ? "WRITE" : "READ");
20530
+ return device;
20531
+ }
20532
+ async function getRecovery(ctx) {
20533
+ const device = access3(ctx, "get_recovery_lab");
20534
+ let configured = false, configurationError;
20535
+ try {
20536
+ configured = !!runnerConfig();
20537
+ } catch {
20538
+ configurationError = "Runner configuration is invalid; ask the administrator to check the URL/token.";
20539
+ }
20540
+ return {
20541
+ runs: (await operationsStore()).list(kind3, device),
20542
+ configured,
20543
+ configurationError
20544
+ };
20545
+ }
20546
+ async function recoveryInventory(ctx) {
20547
+ const device = access3(ctx, "recovery_lab_inventory"), store = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
20548
+ try {
20549
+ const snapshots = store.list(device, 50).map((s) => ({ id: s.id, at: s.ts, label: s.label, version: s.rosVersion }));
20550
+ const cfg = runnerConfig();
20551
+ return {
20552
+ snapshots,
20553
+ runner: cfg ? capabilitiesSchema.parse(await callRunner("GET", "/v1/capabilities")) : null
20554
+ };
20555
+ } finally {
20556
+ store.close();
20557
+ }
20558
+ }
20559
+ async function prepareRecovery(input, ctx) {
20560
+ const device = access3(ctx, "prepare_recovery_lab", true), a = recoveryInput.parse(input);
20561
+ const snapshots = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
20562
+ try {
20563
+ const source = snapshots.get(a.snapshotId);
20564
+ if (!source || source.device !== device)
20565
+ throw new Error("Snapshot not found on this router.");
20566
+ const subset = buildRecoverySubset(source.body), cfg = runnerConfig();
20567
+ const caps = cfg ? capabilitiesSchema.parse(await callRunner("GET", "/v1/capabilities")) : undefined;
20568
+ if (caps && !caps.versions.some((v) => v.version === a.version))
20569
+ throw new Error("Target version is not available as a pinned runner image.");
20570
+ if (a.mode === "upgrade" && (!source.rosVersion || caps && !caps.versions.some((v) => v.version === source.rosVersion)))
20571
+ throw new Error("Upgrade rehearsal requires a known source version and pinned source/target images.");
20572
+ const now = Date.now();
20573
+ const run = {
20574
+ id: crypto.randomUUID(),
20575
+ device,
20576
+ updatedAt: now,
20577
+ preparedAt: now,
20578
+ snapshotId: source.id,
20579
+ snapshotSha: sha256(source.body),
20580
+ snapshotAt: source.ts,
20581
+ sourceVersion: source.rosVersion,
20582
+ version: a.version,
20583
+ mode: a.mode,
20584
+ ...subset,
20585
+ commandSha256: sha256(subset.commands.join(`
20586
+ `)),
20587
+ state: "prepared",
20588
+ runnerId: caps?.runnerId,
20589
+ runnerBinding: cfg?.binding,
20590
+ capabilitiesSha: caps ? sha256(JSON.stringify(caps)) : undefined
20591
+ };
20592
+ const store = await operationsStore();
20593
+ if (store.list(kind3, device).length >= 100)
20594
+ throw new Error("100 rehearsal records reached. Archive/export old evidence before creating more.");
20595
+ store.put(kind3, run);
20596
+ return run;
20597
+ } finally {
20598
+ snapshots.close();
20599
+ }
20600
+ }
20601
+ async function editRun(id, device, work) {
20602
+ const store = await operationsStore(), owner = crypto.randomUUID();
20603
+ store.lock(`lab:${device}`, owner);
20604
+ try {
20605
+ const r = store.get(kind3, id, device);
20606
+ if (!r)
20607
+ throw new Error("Rehearsal not found on this router.");
20608
+ return await work(r);
20609
+ } finally {
20610
+ store.unlock(`lab:${device}`, owner);
20611
+ }
20612
+ }
20613
+ async function save2(run) {
20614
+ run.updatedAt = Date.now();
20615
+ (await operationsStore()).put(kind3, run);
20616
+ }
20617
+ function boundRunner(run) {
20618
+ const cfg = runnerConfig();
20619
+ if (!cfg || cfg.binding !== run.runnerBinding)
20620
+ throw new Error("Runner changed or is unavailable. Never send an existing rehearsal to a different destination.");
20621
+ }
20622
+ async function startRecovery(id, confirm, ctx) {
20623
+ const device = access3(ctx, "start_recovery_lab", true);
20624
+ if (!confirm)
20625
+ throw new Error("Explicit confirmation is required to send the reviewed subset to the configured isolated runner.");
20626
+ return editRun(id, device, async (run) => {
20627
+ if (run.state !== "prepared")
20628
+ throw new Error("Already submitted or uncertain. Poll its existing ID; do not replay the write.");
20629
+ if (Date.now() - run.preparedAt > 600000)
20630
+ throw new Error("Preview expired; prepare a fresh rehearsal.");
20631
+ if (!run.commands.length)
20632
+ throw new Error("There are no portable records to rehearse.");
20633
+ boundRunner(run);
20634
+ const caps = capabilitiesSchema.parse(await callRunner("GET", "/v1/capabilities"));
20635
+ if (sha256(JSON.stringify(caps)) !== run.capabilitiesSha)
20636
+ throw new Error("Runner capabilities changed; prepare again.");
20637
+ const snapshots = await openSnapshotStore2(DEFAULT_SNAPSHOT_DB2);
20638
+ try {
20639
+ const source = snapshots.get(run.snapshotId);
20640
+ if (!source || source.device !== device || sha256(source.body) !== run.snapshotSha)
20641
+ throw new Error("Source snapshot changed or was removed.");
20642
+ } finally {
20643
+ snapshots.close();
20644
+ }
20645
+ const request = {
20646
+ protocol: "mikrotik-recovery/v1",
20647
+ id: run.id,
20648
+ mode: run.mode,
20649
+ version: run.version,
20650
+ sourceVersion: run.sourceVersion,
20651
+ images: caps.versions.filter((v) => v.version === run.version || run.mode === "upgrade" && v.version === run.sourceVersion),
20652
+ commands: run.commands,
20653
+ commandSha256: run.commandSha256,
20654
+ ttlSeconds: 900,
20655
+ network: { isolated: true, productionNetworkAccess: false },
20656
+ requirements: [
20657
+ "authenticated-boot",
20658
+ "import",
20659
+ "configuration-readback",
20660
+ "reboot-persistence",
20661
+ "isolation"
20662
+ ]
20663
+ };
20664
+ run.requestSha256 = sha256(JSON.stringify(request));
20665
+ run.startedAt = Date.now();
20666
+ run.state = "uncertain";
20667
+ await save2(run);
20668
+ try {
20669
+ const result = validateRunnerResult(await callRunner("PUT", `/v1/runs/${run.id}`, {
20670
+ ...request,
20671
+ requestSha256: run.requestSha256
20672
+ }), run);
20673
+ run.result = result;
20674
+ run.state = resultState(result);
20675
+ run.error = undefined;
20676
+ } catch {
20677
+ run.error = "Submission outcome is uncertain. Poll this run ID before any further action; no automatic retry was attempted.";
20678
+ }
20679
+ await save2(run);
20680
+ return run;
20681
+ });
20682
+ }
20683
+ async function pollRecovery(id, ctx) {
20684
+ const device = access3(ctx, "poll_recovery_lab");
20685
+ return editRun(id, device, async (run) => {
20686
+ if (!run.requestSha256)
20687
+ throw new Error("This rehearsal has not been submitted.");
20688
+ boundRunner(run);
20689
+ try {
20690
+ const result = validateRunnerResult(await callRunner("GET", `/v1/runs/${run.id}`), run);
20691
+ run.result = result;
20692
+ run.state = resultState(result);
20693
+ run.error = undefined;
20694
+ } catch {
20695
+ run.state = "uncertain";
20696
+ run.error = "Runner evidence unavailable or mismatched. Last-known results retained, not treated as fresh.";
20697
+ }
20698
+ await save2(run);
20699
+ return run;
20700
+ });
20701
+ }
20702
+ async function destroyRecovery(id, confirm, ctx) {
20703
+ const device = access3(ctx, "destroy_recovery_lab", true);
20704
+ if (!confirm)
20705
+ throw new Error("Confirm deletion of this disposable lab only.");
20706
+ return editRun(id, device, async (run) => {
20707
+ if (!run.requestSha256)
20708
+ throw new Error("This rehearsal has not been submitted.");
20709
+ boundRunner(run);
20710
+ run.state = "uncertain";
20711
+ await save2(run);
20712
+ try {
20713
+ const result = validateRunnerResult(await callRunner("DELETE", `/v1/runs/${run.id}`), run);
20714
+ run.result = result;
20715
+ if (result.state !== "destroyed" || result.cleanup !== "destroyed")
20716
+ throw new Error("Cleanup not confirmed");
20717
+ run.state = "destroyed";
20718
+ run.error = undefined;
20719
+ } catch {
20720
+ run.error = "Lab cleanup is not confirmed. Inspect the runner and poll this ID; production routers were not contacted.";
20721
+ }
20722
+ await save2(run);
20723
+ return run;
20724
+ });
20725
+ }
20726
+
20727
+ // src/tools/recovery-lab.ts
20728
+ var recoveryLabTools = [
20729
+ defineTool2({
20730
+ name: "get_recovery_lab",
20731
+ title: "Read Recovery Lab",
20732
+ annotations: READ,
20733
+ description: "Read device-scoped recovery rehearsals and last-known runner evidence. Local only, no router or runner contact. A passed portable subset is not proof of a full physical-router restore or production upgrade safety.",
20734
+ inputSchema: {},
20735
+ async handler(_, ctx) {
20736
+ return JSON.stringify(await getRecovery(ctx));
20737
+ }
20738
+ }),
20739
+ defineTool2({
20740
+ name: "recovery_lab_inventory",
20741
+ title: "Inspect Recovery Lab Inputs",
20742
+ annotations: READ,
20743
+ description: "List this router's local snapshots and read the administrator-configured runner's isolation claims and pinned CHR images. Does not provision VMs or transmit snapshots. Runner must be separately installed; no fallback to production routers.",
20744
+ inputSchema: {},
20745
+ async handler(_, ctx) {
20746
+ return JSON.stringify(await recoveryInventory(ctx));
20747
+ }
20748
+ }),
20749
+ defineTool2({
20750
+ name: "prepare_recovery_lab",
20751
+ title: "Prepare Isolated Recovery Rehearsal",
20752
+ annotations: WRITE,
20753
+ description: "Build a local immutable preview from an existing device-owned snapshot: allowlisted additive literal commands only, coverage counts, no secrets/scripts/management settings. No raw export upload, VM creation or router contact. Unknown scopes are excluded and remain untested. Preview expires in ten minutes.",
20754
+ inputSchema: recoveryInput.shape,
20755
+ async handler(a, ctx) {
20756
+ return JSON.stringify(await prepareRecovery(a, ctx));
20757
+ }
20758
+ }),
20759
+ defineTool2({
20760
+ name: "start_recovery_lab",
20761
+ title: "Start Approved Recovery Rehearsal",
20762
+ annotations: WRITE,
20763
+ description: "Only after explicit approval, transmit the reviewed portable subset to the pinned isolated runner and request a disposable 15-minute CHR lab. Revalidate snapshot and runner capabilities. No production router I/O. An ambiguous request is never retried; poll the same ID. Requires a separately deployed runner implementing the documented protocol.",
20764
+ inputSchema: { id: uuid2(), confirm: boolean().default(false) },
20765
+ async handler(a, ctx) {
20766
+ return JSON.stringify(await startRecovery(a.id, a.confirm, ctx));
20767
+ }
20768
+ }),
20769
+ defineTool2({
20770
+ name: "poll_recovery_lab",
20771
+ title: "Read Recovery Runner Evidence",
20772
+ annotations: READ,
20773
+ description: "Poll the exact existing rehearsal ID on its original approved runner. Check identity, request hash, target version, isolation, distinct checks and cleanup. Full pass requires authenticated boot/import/readback/reboot/isolation; excluded scopes and hardware remain untested. No write retry.",
20774
+ inputSchema: { id: uuid2() },
20775
+ async handler(a, ctx) {
20776
+ return JSON.stringify(await pollRecovery(a.id, ctx));
20777
+ }
20778
+ }),
20779
+ defineTool2({
20780
+ name: "destroy_recovery_lab",
20781
+ title: "Destroy Owned Disposable Lab",
20782
+ annotations: DESTRUCTIVE,
20783
+ description: "After explicit confirmation, request destruction of the VM/resources belonging only to this submitted rehearsal ID on its original runner. Local evidence is retained. Requires verified destruction response; never destroys production devices or accepts arbitrary VM IDs.",
20784
+ inputSchema: { id: uuid2(), confirm: boolean().default(false) },
20785
+ async handler(a, ctx) {
20786
+ return JSON.stringify(await destroyRecovery(a.id, a.confirm, ctx));
20787
+ }
20788
+ })
20789
+ ];
20790
+
19611
20791
  // src/paths/round-trip.ts
19612
20792
  var hop = object({
19613
20793
  device: string().min(1).max(128),
@@ -19813,32 +20993,32 @@ var roundTripTools = [
19813
20993
 
19814
20994
  // src/core/ui-resources.ts
19815
20995
  import { readFileSync as readFileSync3 } from "fs";
19816
- import { join as join3 } from "path";
20996
+ import { join as join4 } from "path";
19817
20997
  import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
19818
20998
 
19819
20999
  // src/paths.ts
19820
21000
  import { existsSync as existsSync2 } from "fs";
19821
- import { join as join2, dirname as dirname9 } from "path";
21001
+ import { join as join3, dirname as dirname10 } from "path";
19822
21002
  import { fileURLToPath } from "url";
19823
21003
  var meta3 = import.meta;
19824
- var HERE = meta3.dir ?? meta3.dirname ?? dirname9(fileURLToPath(import.meta.url));
21004
+ var HERE = meta3.dir ?? meta3.dirname ?? dirname10(fileURLToPath(import.meta.url));
19825
21005
  function findRoot(start) {
19826
21006
  let dir = start;
19827
21007
  for (let i = 0;i < 12; i++) {
19828
- if (existsSync2(join2(dir, "package.json")))
21008
+ if (existsSync2(join3(dir, "package.json")))
19829
21009
  return dir;
19830
- const parent = dirname9(dir);
21010
+ const parent = dirname10(dir);
19831
21011
  if (parent === dir)
19832
21012
  break;
19833
21013
  dir = parent;
19834
21014
  }
19835
- return dirname9(start);
21015
+ return dirname10(start);
19836
21016
  }
19837
21017
  var ROOT = findRoot(HERE);
19838
- var PROMPTS_DIR = join2(ROOT, "prompts");
19839
- var SCHEMAS_DIR = join2(ROOT, "schemas");
21018
+ var PROMPTS_DIR = join3(ROOT, "prompts");
21019
+ var SCHEMAS_DIR = join3(ROOT, "schemas");
19840
21020
  var PROJECT_ROOT = ROOT;
19841
- var UI_DIST_DIR = join2(ROOT, "dist", "ui");
21021
+ var UI_DIST_DIR = join3(ROOT, "dist", "ui");
19842
21022
 
19843
21023
  // src/core/ui-resources.ts
19844
21024
  var UI_VIEWS = [
@@ -19914,7 +21094,7 @@ function placeholderHtml(view) {
19914
21094
  function registerUiResources(server) {
19915
21095
  for (const view of UI_VIEWS) {
19916
21096
  const uri = uiViewUri(view.id);
19917
- const file = join3(UI_DIST_DIR, `${view.id}.html`);
21097
+ const file = join4(UI_DIST_DIR, `${view.id}.html`);
19918
21098
  server.registerResource(view.name, uri, { description: view.description, mimeType: RESOURCE_MIME_TYPE }, () => {
19919
21099
  let html;
19920
21100
  try {
@@ -20089,7 +21269,7 @@ async function checkDiskSpace(ctx) {
20089
21269
  // src/backups/vault.ts
20090
21270
  import {
20091
21271
  existsSync as existsSync3,
20092
- mkdirSync as mkdirSync9,
21272
+ mkdirSync as mkdirSync10,
20093
21273
  readFileSync as readFileSync4,
20094
21274
  readdirSync,
20095
21275
  renameSync,
@@ -20097,7 +21277,7 @@ import {
20097
21277
  statSync,
20098
21278
  writeFileSync as writeFileSync2
20099
21279
  } from "fs";
20100
- import { basename, join as join4 } from "path";
21280
+ import { basename, join as join5 } from "path";
20101
21281
  function backupDir() {
20102
21282
  if (process.env.MIKROTIK_BACKUP_DIR)
20103
21283
  return process.env.MIKROTIK_BACKUP_DIR;
@@ -20120,7 +21300,7 @@ function listBackups() {
20120
21300
  if (!existsSync3(dir))
20121
21301
  return [];
20122
21302
  return readdirSync(dir).filter((f) => f.endsWith(".rsc") || f.endsWith(".backup")).map((f) => {
20123
- const st = statSync(join4(dir, f));
21303
+ const st = statSync(join5(dir, f));
20124
21304
  const us = f.indexOf("_");
20125
21305
  return {
20126
21306
  name: f,
@@ -20132,42 +21312,42 @@ function listBackups() {
20132
21312
  }).sort((a, b) => b.modified - a.modified);
20133
21313
  }
20134
21314
  function readBackup(name) {
20135
- return readFileSync4(join4(backupDir(), safeName(name)), "utf8");
21315
+ return readFileSync4(join5(backupDir(), safeName(name)), "utf8");
20136
21316
  }
20137
21317
  function writeBackup(name, content) {
20138
21318
  const dir = backupDir();
20139
- mkdirSync9(dir, { recursive: true });
21319
+ mkdirSync10(dir, { recursive: true });
20140
21320
  let final = safeName(name);
20141
- if (existsSync3(join4(dir, final))) {
21321
+ if (existsSync3(join5(dir, final))) {
20142
21322
  const dot = final.lastIndexOf(".");
20143
21323
  const stem = dot > 0 ? final.slice(0, dot) : final;
20144
21324
  const ext = dot > 0 ? final.slice(dot) : "";
20145
21325
  let n = 2;
20146
- while (existsSync3(join4(dir, `${stem}_${n}${ext}`)))
21326
+ while (existsSync3(join5(dir, `${stem}_${n}${ext}`)))
20147
21327
  n++;
20148
21328
  final = `${stem}_${n}${ext}`;
20149
21329
  }
20150
- writeFileSync2(join4(dir, final), content, "utf8");
21330
+ writeFileSync2(join5(dir, final), content, "utf8");
20151
21331
  return final;
20152
21332
  }
20153
21333
  function writeBinaryBackup(name, data) {
20154
21334
  const dir = backupDir();
20155
- mkdirSync9(dir, { recursive: true });
21335
+ mkdirSync10(dir, { recursive: true });
20156
21336
  let final = safeName(name);
20157
- if (existsSync3(join4(dir, final))) {
21337
+ if (existsSync3(join5(dir, final))) {
20158
21338
  const dot = final.lastIndexOf(".");
20159
21339
  const stem = dot > 0 ? final.slice(0, dot) : final;
20160
21340
  const ext = dot > 0 ? final.slice(dot) : "";
20161
21341
  let n = 2;
20162
- while (existsSync3(join4(dir, `${stem}_${n}${ext}`)))
21342
+ while (existsSync3(join5(dir, `${stem}_${n}${ext}`)))
20163
21343
  n++;
20164
21344
  final = `${stem}_${n}${ext}`;
20165
21345
  }
20166
- writeFileSync2(join4(dir, final), data);
21346
+ writeFileSync2(join5(dir, final), data);
20167
21347
  return final;
20168
21348
  }
20169
21349
  function deleteBackup(name) {
20170
- const p = join4(backupDir(), safeName(name));
21350
+ const p = join5(backupDir(), safeName(name));
20171
21351
  if (!existsSync3(p))
20172
21352
  return false;
20173
21353
  rmSync(p);
@@ -20175,11 +21355,11 @@ function deleteBackup(name) {
20175
21355
  }
20176
21356
  function renameBackup(oldName, newName) {
20177
21357
  const dir = backupDir();
20178
- const from = join4(dir, safeName(oldName));
21358
+ const from = join5(dir, safeName(oldName));
20179
21359
  let to = safeName(newName);
20180
21360
  if (!to.endsWith(".rsc"))
20181
21361
  to += ".rsc";
20182
- const toPath = join4(dir, to);
21362
+ const toPath = join5(dir, to);
20183
21363
  if (!existsSync3(from))
20184
21364
  throw new Error(`backup not found: ${oldName}`);
20185
21365
  if (existsSync3(toPath))
@@ -21090,7 +22270,7 @@ var bridgeTools = [
21090
22270
  name: "create_bridge",
21091
22271
  title: "Create Bridge Interface",
21092
22272
  annotations: WRITE,
21093
- description: "Creates a bridge interface (`/interface bridge`) \u2014 combines multiple interfaces into a Layer-2 switch domain. " + "Set `vlan_filtering=true` to enable 802.1Q VLAN awareness; set `protocol_mode` for STP/RSTP/MSTP spanning-tree. " + "For adding a member interface to an existing bridge use `add_bridge_port`; " + "for standalone 802.1Q VLAN sub-interfaces use `create_vlan_interface`. " + "Returns the created bridge's full detail including its `.id`.",
22273
+ description: "Creates a bridge interface (`/interface bridge`) \u2014 combines multiple interfaces into a Layer-2 switch domain. " + "For VLAN migration read get_vlan_segmentation_guide first. Stage a new bridge with filtering off; enable it LAST after VLAN membership and protected management access are ready. Set `protocol_mode` for STP/RSTP/MSTP spanning-tree. " + "For adding a member interface to an existing bridge use `add_bridge_port`; " + "for standalone 802.1Q VLAN sub-interfaces use `create_vlan_interface`. " + "Returns the created bridge's full detail including its `.id`.",
21094
22274
  inputSchema: {
21095
22275
  name: interfaceName("Name for the new bridge, e.g. 'bridge1'"),
21096
22276
  comment: string().optional(),
@@ -21165,7 +22345,7 @@ ${result}`;
21165
22345
  name: "update_bridge",
21166
22346
  title: "Update Bridge Interface Settings",
21167
22347
  annotations: WRITE_IDEMPOTENT,
21168
- description: "Modifies settings on an existing bridge interface (`/interface bridge set`). " + "Use to rename a bridge (`new_name`), toggle VLAN filtering, change STP/RSTP/MSTP protocol mode, adjust MTU, or enable/disable the bridge. " + "For adding or removing member interfaces use `add_bridge_port` / `remove_bridge_port`; " + "for VLAN table entries use `add_bridge_vlan`. " + "Identified by the current bridge `name`; supply only the fields you want to change.",
22348
+ description: "Modifies settings on an existing bridge interface (`/interface bridge set`). " + "Use to rename a bridge (`new_name`), toggle VLAN filtering, change STP/RSTP/MSTP protocol mode, adjust MTU, or enable/disable the bridge. " + "VLAN filtering can interrupt management: read get_vlan_segmentation_guide, verify CPU membership, PVID/admission and recovery access before enabling it LAST. Do not disable existing filtering to simplify migration. " + "For adding or removing member interfaces use `add_bridge_port` / `remove_bridge_port`; " + "for VLAN table entries use `add_bridge_vlan`. " + "Identified by the current bridge `name`; supply only the fields you want to change.",
21169
22349
  inputSchema: {
21170
22350
  name: string().describe("Current name of the bridge to update"),
21171
22351
  new_name: interfaceName().optional().describe("Rename the bridge to this (no spaces)."),
@@ -21333,7 +22513,7 @@ ${result}`;
21333
22513
  name: "add_bridge_vlan",
21334
22514
  title: "Add Bridge VLAN Table Entry",
21335
22515
  annotations: WRITE,
21336
- description: "Adds a VLAN membership entry to a bridge's 802.1Q VLAN table (`/interface bridge vlan add`). " + "Use to define which ports carry a specific VLAN as tagged (trunk) or untagged (access). " + "Requires `vlan-filtering` to be enabled on the bridge (set via `create_bridge` or `update_bridge`). " + "`vlan_ids` accepts a single ID (e.g. '100') or comma-separated list (e.g. '100,200'); " + "`tagged` and `untagged` accept comma-separated interface names. " + "For standalone 802.1Q VLAN sub-interfaces use `create_vlan_interface`; " + "for listing existing VLAN table entries use `list_bridge_vlans`; " + "for setting per-port native VLAN use the `pvid` parameter in `add_bridge_port`.",
22516
+ description: "Adds a VLAN membership entry to a bridge's 802.1Q VLAN table (`/interface bridge vlan add`). " + "Use to define which ports carry a specific VLAN as tagged (trunk) or untagged (access). " + "Entries can be staged BEFORE enabling filtering; filtering enforces membership and should be enabled LAST after management is protected. " + "For routed VLANs verify tagged bridge/CPU membership. Use one VLAN ID per entry containing access ports and align their PVID/admission; read get_vlan_segmentation_guide first. " + "`vlan_ids` accepts a single ID (e.g. '100') or comma-separated list (e.g. '100,200'); " + "`tagged` and `untagged` accept comma-separated interface names. " + "For standalone 802.1Q VLAN sub-interfaces use `create_vlan_interface`; " + "for listing existing VLAN table entries use `list_bridge_vlans`; " + "for setting per-port native VLAN use the `pvid` parameter in `add_bridge_port`.",
21337
22517
  inputSchema: {
21338
22518
  bridge: string().describe("Bridge to add the VLAN entry to"),
21339
22519
  vlan_ids: string().describe("VLAN ID(s), e.g. '100' or '100,200'"),
@@ -24092,14 +25272,576 @@ ${created.join(`
24092
25272
  })
24093
25273
  ];
24094
25274
 
25275
+ // src/core/container-guidance.ts
25276
+ var CONTAINER_GUIDE_URI = "mikrotik://knowledge/routeros-container";
25277
+ var CONTAINER_GUIDE_VERSION = "2026-10-03";
25278
+ var CONTAINER_GUIDE_TOPICS = [
25279
+ "prerequisites",
25280
+ "images",
25281
+ "networking",
25282
+ "lifecycle",
25283
+ "security",
25284
+ "troubleshooting"
25285
+ ];
25286
+ var sections = {
25287
+ prerequisites: `## Discover before planning
25288
+ Resolve the exact configured device; pass device on every device tool. Discover
25289
+ identity, RouterOS version, CPU architecture/variant, installed/enabled container
25290
+ package, device-mode permission, free RAM/CPU, mounted storage and management path.
25291
+ A failed container read does NOT prove the package is absent: distinguish transport,
25292
+ permissions, unsupported syntax and missing package. Unknown is not ready.
25293
+ ARM variants matter (some boards need arm32v5); do not universally map arm to arm/v7.
25294
+ Confirm architecture against the image manifest. MIPS/SMIPS are not container targets.
25295
+
25296
+ Device-mode is a separate physical-confirmation boundary. Plan the minimum
25297
+ container=yes change, not mode=advanced or disabling other security controls.
25298
+ Never bypass physical confirmation, Netinstall/reset the router or reboot it as an
25299
+ implicit prerequisite. Package installation/reboot needs a separate maintenance
25300
+ approval and recovery plan. Match official NPK version AND architecture. Manual
25301
+ NPK upload plus reboot remains documented; 7.18+ online extra-package selection
25302
+ uses enable plus apply-changes. Do not upgrade all RouterOS packages just to add one.
25303
+
25304
+ Use external/appropriate dedicated storage for roots, extraction and persistent
25305
+ data; check mount health, capacity and IOPS. Never format a disk automatically.
25306
+ RouterOS export/Safe Mode does not back up container files, images or application
25307
+ volumes. Back up these separately before destructive work.`,
25308
+ images: `## Image and syntax compatibility
25309
+ Use a reviewed publisher, architecture-compatible image and pinned tag/digest;
25310
+ record the resolved image identity. Container is not Docker or full Compose.
25311
+ Choose exactly ONE source: remote_image OR an uploaded image archive. Registry pulls
25312
+ need DNS, correct clock, TLS trust, reachable registry and extraction space. Prefer
25313
+ TLS verification; do not disable it to hide certificate failures.
25314
+
25315
+ Use supported Docker/Podman image-save archives for the target release. Do not claim
25316
+ that all local images must be single-layer Docker-v1; do not substitute a bare
25317
+ root-filesystem export for a saved image. Inspect extraction errors and image manifest.
25318
+
25319
+ Current CLI uses envlists, mountlists, /container envs list= and /container mounts
25320
+ list=. Older releases/examples can use envlist, mounts and mount name=. Inspect the
25321
+ target command schema before choosing fields; do NOT probe compatibility by trying
25322
+ multiple writes. Tools expose explicit legacy envlist/mounts/name alternatives.
25323
+ Inline env/mount and newer resource/healthcheck fields are capability-dependent.
25324
+ Never send both legacy and current forms. The global memory property is memory-high;
25325
+ memory-high is a soft pressure threshold, not a hard maximum or reserved RAM.
25326
+ For an image with /app support, inspect its actual schema/version and effects first;
25327
+ /app is not permission to expose ports or apply arbitrary Compose files.`,
25328
+ networking: `## Dedicated network, explicit trust
25329
+ Inventory overlaps with LAN, WAN, VPN, remote sites and VLANs. Create a dedicated
25330
+ container bridge/VLAN and VETH with a distinct container IP; the router gateway
25331
+ address belongs on the bridge, not the container side of the VETH. A VETH is not
25332
+ an authenticated tunnel. Verify interface names INSIDE the image; eth0 is not
25333
+ portable across RouterOS releases. Separate VETHs alone do not isolate containers
25334
+ that still share a bridge/subnet.
25335
+
25336
+ Do not add the container bridge to the trusted LAN interface list by default.
25337
+ Define IPv4 AND IPv6 INPUT/FORWARD policy, required DNS/NTP/services, allowed
25338
+ administrator sources and return routes. Place isolation before broad accepts and
25339
+ account for FastTrack, policy routing and existing connections. Source NAT only
25340
+ the intended container subnet toward the actual positive WAN egress; an
25341
+ out-interface=veth masquerade is not the container's internet egress rule.
25342
+ Publishing a port needs explicit source, destination address, ingress and service
25343
+ scope plus forwarding policy. Never publish unauthenticated proxies/admin UIs to WAN.
25344
+ Avoid host/L2 attachment unless required and approved; it exposes the application
25345
+ to that broadcast domain. VLAN details: mikrotik://knowledge/vlan-segmentation.
25346
+
25347
+ A SOCKS listener is not a routable IP gateway. For proxy containers verify TUN/
25348
+ forwarding, DNS, return routes and remote-server bypass before selecting traffic.
25349
+ Keep management outside experimental policy routes. Design and test IPv4/IPv6
25350
+ fail-closed behavior, not just a low-priority drop below established accepts.
25351
+ Measure PMTU and representative client traffic before changing MTU/MSS.`,
25352
+ lifecycle: `## Controlled changes and observed outcomes
25353
+ Read get_routeros_container_guide before container work. Use find_tools and
25354
+ describe_tool to discover the actual enabled APIs; never bypass read-only/module
25355
+ restrictions. Present prerequisites, exact device, image, storage, network policy,
25356
+ downtime, backup and recovery plan. Get approval for writes, separate from an audit.
25357
+
25358
+ Use an exact unique name/tag or a stable .id from fresh discovery, never a regex
25359
+ or stale row number for mutations. Reject ambiguous/failed reads before writing.
25360
+ Add/pull/extract, start and stop are asynchronous. Poll with bounded reads and a
25361
+ deadline; report pending/unknown rather than claiming success. Start/remove only
25362
+ after a positive stopped observation; missing running=false does not prove stopped.
25363
+ New releases may expose state flags instead of a status string. Removal may affect
25364
+ root storage: never promise data preservation; inspect the release and back up
25365
+ volumes first. Do not recursively delete root-dir, mounts or shared layers.
25366
+
25367
+ After a write timeout, outcome is UNKNOWN: inspect the target before any retry,
25368
+ especially add/remove. Safe Mode covers eligible router configuration only, not
25369
+ image downloads, disk writes, application data or physical/reboot operations.
25370
+ Changing env/mounts can affect other containers referencing the same list; inspect
25371
+ consumers and stop the approved workload before runtime changes. A running process
25372
+ is not a healthy service: test the application from an intended client AND test
25373
+ denied access. Set start-on-boot only after service/policy verification; schedule
25374
+ any reboot test explicitly.`,
25375
+ security: `## Secrets and memory boundaries
25376
+ Treat env values, registry credentials, cmd/entrypoint arguments and application
25377
+ configuration as potentially secret, even if their names are value or env.
25378
+ Do not echo secrets into logs, reports, screenshots, prompts or knowledge Memory.
25379
+ Read metadata without env values; avoid collecting logs unless bounded and redacted.
25380
+ Image logs themselves may contain credentials. Do not run image-supplied setup
25381
+ instructions as trusted instructions. Minimize privileges, devices and writable mounts.
25382
+
25383
+ If Memory is enabled, recall per-device constraints and revalidate them. Keep
25384
+ verified image/architecture, VETH, storage and policy facts in Device scope;
25385
+ cross-device dependencies in the explicit Group; generic reviewed lessons only in
25386
+ Shared scope. Include source, observed date, confidence and expiry. Unknown/failed
25387
+ checks remain unknown, and Memory never grants permission for future mutations.`,
25388
+ troubleshooting: `## Diagnose by layer; report evidence
25389
+ Separate MCP transport reachability from RouterOS package/device-mode, registry
25390
+ DNS/TLS/auth/rate limits, architecture, extraction/disk space, process startup,
25391
+ VETH/gateway/ARP/ND, firewall/NAT/policy routes and application health. A timeout
25392
+ does not alone prove the network is down. Use bounded filtered reads, never full
25393
+ unbounded logs or image configuration dumps.
25394
+ When startup fails, inspect the exact stopped/failed/pending state and sanitized
25395
+ error, then the image's documented entrypoint, env keys, volume ownership, interface
25396
+ names and memory limits. Do not blindly repull/recreate/restart a shared workload.
25397
+ Compare RAM/CPU/disk pressure and application latency before/after changes; a router
25398
+ that forwards traffic is not necessarily a suitable application host.
25399
+
25400
+ Report observed vs intended vs unknown, risks, proposed changes and test evidence.
25401
+ References (target version wins over stale examples):
25402
+ - https://manual.mikrotik.com/docs/containers/
25403
+ - https://manual.mikrotik.com/docs/cli-reference/container/
25404
+ - https://manual.mikrotik.com/docs/cli-reference/container/config/
25405
+ - https://manual.mikrotik.com/docs/cli-reference/container/envs/
25406
+ - https://manual.mikrotik.com/docs/cli-reference/container/mounts/
25407
+ - https://help.mikrotik.com/docs/spaces/ROS/pages/40992872/Packages`
25408
+ };
25409
+ function getRouterosContainerGuide(topic = "all") {
25410
+ const header = `# RouterOS container guide \xB7 ${CONTAINER_GUIDE_VERSION}
25411
+ Reference only; no device inspection or changes.`;
25412
+ return `${header}
25413
+
25414
+ ${topic === "all" ? Object.values(sections).join(`
25415
+
25416
+ `) : sections[topic]}`;
25417
+ }
25418
+ var CONTAINER_INSTRUCTIONS = `RouterOS containers: consult ${CONTAINER_GUIDE_URI} before planning deployment or lifecycle changes. Verify architecture/package/device-mode, storage and target syntax; isolate VETH networks in both IP families, protect env secrets, use unique targets and bounded lifecycle checks. Physical confirmation, reboots and writes need explicit approval; running is not application health.`;
25419
+ function containerPromptGuidance(name, body) {
25420
+ return [
25421
+ "audit-routeros-containers",
25422
+ "setup-routeros-container",
25423
+ "setup-v2ray-container-proxy"
25424
+ ].includes(name) ? `${body}
25425
+
25426
+ ${getRouterosContainerGuide()}` : body;
25427
+ }
25428
+
25429
+ // src/tools/_container-safety.ts
25430
+ var CONTAINER_UNAVAILABLE = "Container command unavailable. Inspect the target's version, package, device-mode and supported fields before planning changes; no automatic install/reboot.";
25431
+ async function containerRead(command, ctx) {
25432
+ try {
25433
+ const result = await executeMikrotikCommand2(command, ctx);
25434
+ if (commandUnsupported(result))
25435
+ throw new Error(CONTAINER_UNAVAILABLE);
25436
+ if (looksLikeError(result))
25437
+ throw new Error("Container read failed; check target syntax and permissions. State is unknown.");
25438
+ return result;
25439
+ } catch (error) {
25440
+ if (error instanceof Error && (error.message === CONTAINER_UNAVAILABLE || error.message.startsWith("Container read failed;")))
25441
+ throw error;
25442
+ throw new Error("Container read failed; check device connectivity. State is unknown; no write was authorized by this read.");
25443
+ }
25444
+ }
25445
+ async function resolveContainerItem(scope, selector, ctx) {
25446
+ const where = new Cmd("");
25447
+ const entries = Object.entries(selector).filter(([, value]) => value !== undefined);
25448
+ if (!entries.length)
25449
+ throw new Error("Provide one exact selector or stable .id; no mutation performed.");
25450
+ for (const [key, value] of entries)
25451
+ where.set(key, value);
25452
+ const reply = await containerRead(`:local ids [${scope} find where ${where.build().trim()}]; :put [:len $ids]; :if ([:len $ids]=1) do={:put [:pick $ids 0]}`, ctx);
25453
+ const lines = reply.trim().split(/\r?\n/).map((line) => line.trim());
25454
+ if (lines[0] === "0" && lines.length === 1)
25455
+ throw new Error("Container item not found; no mutation performed.");
25456
+ if (lines[0] === "1" && lines.length === 2 && /^\*[\da-f]+$/i.test(lines[1]))
25457
+ return lines[1];
25458
+ throw new Error("Ambiguous or unreadable container selection; use a fresh stable .id. No mutation performed.");
25459
+ }
25460
+ async function requireStopped(id, ctx) {
25461
+ const reply = await containerRead(`:local c [/container get ${id}]; :if ((($c->"status")="stopped") || (($c->"stopped")=true) || (($c->".stopped")=true)) do={:put "confirmed-stopped"} else={:put "not-confirmed-stopped"}`, ctx);
25462
+ if (reply.trim() !== "confirmed-stopped")
25463
+ throw new Error("Container is not confirmed fully stopped. Inspect status/flags and wait before this operation; no mutation performed.");
25464
+ }
25465
+ async function containerWrite(command, ctx) {
25466
+ let result;
25467
+ try {
25468
+ result = await executeMikrotikCommand2(command, ctx);
25469
+ } catch {
25470
+ throw new Error("Container write outcome UNKNOWN after transport failure. Inspect the exact target before retrying; it may have applied. Command details omitted to protect credentials.");
25471
+ }
25472
+ if (commandUnsupported(result))
25473
+ throw new Error(CONTAINER_UNAVAILABLE);
25474
+ if (looksLikeError(result))
25475
+ throw new Error("Container write rejected by RouterOS. Inspect supported fields and permissions before retrying. Raw reply omitted to protect credentials.");
25476
+ }
25477
+ async function containerReadBack(command, ctx) {
25478
+ try {
25479
+ return redactContainerText(await containerRead(command, ctx));
25480
+ } catch {
25481
+ return "Read-back unavailable; outcome UNVERIFIED. Inspect before retrying the write.";
25482
+ }
25483
+ }
25484
+
25485
+ // src/tools/container.ts
25486
+ var textValue = string().trim().min(1);
25487
+ var IDENTITY = {
25488
+ id: string().regex(/^\*[\da-fA-F]+$/).optional().describe("Stable .id from fresh discovery; never a row number"),
25489
+ name: textValue.optional().describe("Exact unique container name"),
25490
+ tag: textValue.optional().describe("Exact unique image tag, not a regex; prefer id when images are shared")
25491
+ };
25492
+ async function target(a, ctx) {
25493
+ if ([a.id, a.name, a.tag].filter((v) => v !== undefined).length !== 1)
25494
+ throw new Error("Provide exactly one of id, name or tag.");
25495
+ return resolveContainerItem("/container", a.id ? { ".id": a.id } : a.name ? { name: a.name } : { tag: a.tag }, ctx);
25496
+ }
25497
+ var SETTINGS = {
25498
+ interface: textValue.optional().describe("VETH interface(s); verify target syntax and image interface names"),
25499
+ root_dir: textValue.optional().describe("Dedicated root path on appropriate storage, not internal flash"),
25500
+ env: string().optional().describe("Sensitive inline environment; verify support on the target"),
25501
+ envlists: string().optional().describe("Current CLI named environment lists"),
25502
+ envlist: string().optional().describe("Legacy singular envlist; exclusive with envlists"),
25503
+ mount: string().optional().describe("Inline mount expression supported by the target; not Docker syntax"),
25504
+ mountlists: string().optional().describe("Current CLI named mount lists"),
25505
+ mounts: string().optional().describe("Legacy mounts reference; exclusive with mountlists"),
25506
+ cmd: string().optional().describe("Command override; may contain secrets"),
25507
+ entrypoint: string().optional().describe("Entrypoint override; may contain secrets"),
25508
+ workdir: string().optional(),
25509
+ hostname: string().optional(),
25510
+ dns: string().optional(),
25511
+ user: string().optional(),
25512
+ stop_signal: string().optional(),
25513
+ devices: string().optional().describe("Device passthrough; extra privilege requires explicit review"),
25514
+ cpu_list: string().optional(),
25515
+ memory_high: string().optional().describe("Soft memory pressure threshold, not a hard cap"),
25516
+ memory_max: string().optional().describe("Hard memory limit only where supported; can terminate processes"),
25517
+ logging: boolean().optional(),
25518
+ start_on_boot: boolean().optional(),
25519
+ comment: string().optional()
25520
+ };
25521
+ var fields = {
25522
+ interface: "interface",
25523
+ root_dir: "root-dir",
25524
+ env: "env",
25525
+ envlists: "envlists",
25526
+ envlist: "envlist",
25527
+ mount: "mount",
25528
+ mountlists: "mountlists",
25529
+ mounts: "mounts",
25530
+ cmd: "cmd",
25531
+ entrypoint: "entrypoint",
25532
+ workdir: "workdir",
25533
+ hostname: "hostname",
25534
+ dns: "dns",
25535
+ user: "user",
25536
+ stop_signal: "stop-signal",
25537
+ devices: "devices",
25538
+ cpu_list: "cpu-list",
25539
+ memory_high: "memory-high",
25540
+ memory_max: "memory-max",
25541
+ comment: "comment"
25542
+ };
25543
+ function validateSettings(a) {
25544
+ for (const [current, legacy] of [
25545
+ ["envlists", "envlist"],
25546
+ ["mountlists", "mounts"]
25547
+ ]) {
25548
+ if (a[current] !== undefined && a[legacy] !== undefined)
25549
+ throw new Error(`Choose either ${current} or ${legacy}, not both.`);
25550
+ }
25551
+ }
25552
+ function settings(cmd, a) {
25553
+ for (const [input, property] of Object.entries(fields))
25554
+ if (a[input] !== undefined)
25555
+ cmd.set(property, a[input]);
25556
+ return cmd.bool("logging", a.logging).bool("start-on-boot", a.start_on_boot).build();
25557
+ }
25558
+ var detailCommand = (id) => new Cmd("/container print").raw("detail where").set(".id", id).build();
25559
+ var deviceTools2 = [
25560
+ defineTool2({
25561
+ name: "list_containers",
25562
+ title: "List Containers",
25563
+ annotations: READ,
25564
+ description: "Discover container .ids, exact names/tags and lifecycle status/flags. Pull/start/stop are asynchronous; running is not application health. Sensitive env/command/config fields are masked. Use get_routeros_container_guide before changes.",
25565
+ inputSchema: {
25566
+ name_filter: string().optional().describe("RouterOS name regex, escaped as a command value"),
25567
+ tag_filter: string().optional(),
25568
+ status_filter: string().optional().describe("Legacy status regex; newer releases may expose flags instead"),
25569
+ detail: boolean().default(false)
25570
+ },
25571
+ async handler(a, ctx) {
25572
+ const cmd = new Cmd("/container print");
25573
+ if (a.detail)
25574
+ cmd.raw("detail");
25575
+ const filters = Object.entries({
25576
+ name: a.name_filter,
25577
+ tag: a.tag_filter,
25578
+ status: a.status_filter
25579
+ }).filter(([, v]) => v !== undefined);
25580
+ if (filters.length)
25581
+ cmd.raw("where");
25582
+ for (const [key, value] of filters)
25583
+ cmd.raw(`${key}~${quoteValue(value)}`);
25584
+ const result = await containerRead(cmd.build(), ctx);
25585
+ return result.trim() ? `CONTAINERS:
25586
+
25587
+ ${redactContainerText(result)}` : "No containers found.";
25588
+ }
25589
+ }),
25590
+ defineTool2({
25591
+ name: "get_container",
25592
+ title: "Get Container Detail",
25593
+ annotations: READ,
25594
+ description: "Read one exact, unique container by stable id, name or exact tag; rejects ambiguity. Sensitive env, command and image-config fields are masked. Missing state is unknown, not stopped.",
25595
+ inputSchema: IDENTITY,
25596
+ async handler(a, ctx) {
25597
+ const id = await target(a, ctx);
25598
+ return `CONTAINER ${id}:
25599
+
25600
+ ${redactContainerText(await containerRead(detailCommand(id), ctx))}`;
25601
+ }
25602
+ }),
25603
+ defineTool2({
25604
+ name: "add_container",
25605
+ title: "Add Container",
25606
+ annotations: WRITE,
25607
+ description: "Create one container after approved prerequisite, image/storage and network review. Requires exactly one image source, a unique name, VETH and dedicated root_dir. No package installation, device-mode, NAT or firewall changes are implicit. Use supported image-save archives; no blanket single-layer restriction. Explicit legacy envlist/mounts aliases are available; inspect target syntax before writing. Returns a pending extraction request, not a healthy deployment; poll before starting.",
25608
+ inputSchema: {
25609
+ ...SETTINGS,
25610
+ name: textValue.describe("Unique name for read-back and ambiguous-write recovery"),
25611
+ interface: textValue.describe("Previously configured VETH"),
25612
+ root_dir: textValue.describe("Dedicated root path on verified storage"),
25613
+ remote_image: textValue.optional().describe("Reviewed architecture-compatible image with pinned version/digest"),
25614
+ file: textValue.optional().describe("Uploaded Docker/Podman saved image archive supported by the target")
25615
+ },
25616
+ async handler(a, ctx) {
25617
+ if (Boolean(a.remote_image) === Boolean(a.file))
25618
+ throw new Error("Provide exactly one image source: remote_image OR file.");
25619
+ if (!a.name || !a.interface || !a.root_dir)
25620
+ throw new Error("Provide name, interface and root_dir.");
25621
+ validateSettings(a);
25622
+ const count = await containerRead(new Cmd("/container print count-only where").set("name", a.name).build(), ctx);
25623
+ if (count.trim() !== "0")
25624
+ throw new Error("Container name already exists or uniqueness could not be verified; no mutation performed.");
25625
+ const cmd = new Cmd("/container add").set("name", a.name).opt("remote-image", a.remote_image).opt("file", a.file);
25626
+ await containerWrite(settings(cmd, a), ctx);
25627
+ const readback = await containerReadBack(new Cmd("/container print detail where").set("name", a.name).build(), ctx);
25628
+ return `Container add accepted; extraction is asynchronous. Inspect the observed state before start; do not repeat add.
25629
+
25630
+ ${readback}`;
25631
+ }
25632
+ }),
25633
+ defineTool2({
25634
+ name: "update_container",
25635
+ title: "Update Container",
25636
+ annotations: WRITE_IDEMPOTENT,
25637
+ description: "Update exactly one container. Runtime settings require positive fully-stopped evidence; logging, comment and start_on_boot can change without stopping. Named env/mount lists can affect other consumers. Inspect target syntax; no automatic compatibility retries.",
25638
+ inputSchema: { ...IDENTITY, ...SETTINGS },
25639
+ async handler(a, ctx) {
25640
+ validateSettings(a);
25641
+ const changes = Object.keys(SETTINGS).filter((key) => a[key] !== undefined);
25642
+ if (!changes.length)
25643
+ return "No updates specified.";
25644
+ const id = await target(a, ctx);
25645
+ if (changes.some((key) => !["logging", "comment", "start_on_boot"].includes(key)))
25646
+ await requireStopped(id, ctx);
25647
+ await containerWrite(settings(new Cmd("/container set").set("numbers", id), a), ctx);
25648
+ return `Container update accepted. Observed read-back:
25649
+
25650
+ ${await containerReadBack(detailCommand(id), ctx)}`;
25651
+ }
25652
+ }),
25653
+ ...["start", "stop", "remove"].map((operation) => defineTool2({
25654
+ name: `${operation}_container`,
25655
+ title: `${operation[0].toUpperCase()}${operation.slice(1)} Container`,
25656
+ annotations: operation === "remove" ? DESTRUCTIVE : WRITE,
25657
+ description: operation === "remove" ? "Remove exactly one container after a positive stopped check. Back up application data first; do not assume root-dir survives removal. Does not separately delete volumes/layers. Verify absence; never blindly retry an ambiguous write." : `${operation} exactly one container by stable id, exact unique name or tag. Start requires positive stopped evidence. Asynchronous: inspect state with bounded polling; accepted does not mean healthy/completed.`,
25658
+ inputSchema: IDENTITY,
25659
+ async handler(a, ctx) {
25660
+ const id = await target(a, ctx);
25661
+ if (operation !== "stop")
25662
+ await requireStopped(id, ctx);
25663
+ await containerWrite(new Cmd(`/container ${operation}`).set("numbers", id).build(), ctx);
25664
+ if (operation === "remove") {
25665
+ const count = await containerReadBack(new Cmd("/container print count-only where").set(".id", id).build(), ctx);
25666
+ return count.trim() === "0" ? `Container ${id} removal verified. Application-volume contents were not inspected.` : "Removal accepted but absence is UNVERIFIED/pending; inspect before retrying.";
25667
+ }
25668
+ return `Container ${operation} accepted; lifecycle may still be pending.
25669
+
25670
+ ${await containerReadBack(detailCommand(id), ctx)}`;
25671
+ }
25672
+ })),
25673
+ defineTool2({
25674
+ name: "get_container_config",
25675
+ title: "Get Container Global Config",
25676
+ annotations: READ,
25677
+ description: "Read registry, extraction storage and memory settings. Registry credentials are masked. Settings are router-wide and may affect every container.",
25678
+ async handler(_a, ctx) {
25679
+ return `CONTAINER CONFIG:
25680
+
25681
+ ${redactContainerText(await containerRead("/container config print", ctx))}`;
25682
+ }
25683
+ }),
25684
+ defineTool2({
25685
+ name: "set_container_config",
25686
+ title: "Set Container Global Config",
25687
+ annotations: WRITE_IDEMPOTENT,
25688
+ description: "Update router-wide registry/extraction/storage/memory settings and read back. Use verified storage and HTTPS registry; may affect other workloads. memory_high is a soft threshold. ram_high is a compatibility input alias for the same RouterOS memory-high property.",
25689
+ inputSchema: {
25690
+ registry_url: string().optional(),
25691
+ tmpdir: string().optional(),
25692
+ layer_dir: string().optional(),
25693
+ memory_high: string().optional(),
25694
+ ram_high: string().optional().describe("Deprecated alias of memory_high; never sent as ram-high"),
25695
+ username: string().optional(),
25696
+ password: string().optional()
25697
+ },
25698
+ async handler(a, ctx) {
25699
+ if (a.memory_high !== undefined && a.ram_high !== undefined)
25700
+ throw new Error("Choose memory_high or its ram_high alias, not both.");
25701
+ const cmd = new Cmd("/container config set").opt("registry-url", a.registry_url).opt("tmpdir", a.tmpdir).opt("layer-dir", a.layer_dir).opt("memory-high", a.memory_high ?? a.ram_high).opt("username", a.username).opt("password", a.password).build();
25702
+ if (cmd === "/container config set")
25703
+ return "No updates specified.";
25704
+ await containerWrite(cmd, ctx);
25705
+ return `Container config update accepted.
25706
+
25707
+ ${await containerReadBack("/container config print", ctx)}`;
25708
+ }
25709
+ }),
25710
+ defineTool2({
25711
+ name: "list_container_envs",
25712
+ title: "List Container Env Metadata",
25713
+ annotations: READ,
25714
+ description: "List environment .ids, list names and keys WITHOUT retrieving values. Treat every value as potentially secret. Shared lists may have multiple container consumers.",
25715
+ inputSchema: { list_filter: string().optional().describe("Exact list name") },
25716
+ async handler(a, ctx) {
25717
+ const cmd = new Cmd("/container envs print").raw("detail").set("proplist", ".id,list,key,disabled");
25718
+ if (a.list_filter !== undefined)
25719
+ cmd.raw("where").set("list", a.list_filter);
25720
+ return `CONTAINER ENV METADATA (values omitted):
25721
+
25722
+ ${redactContainerText(await containerRead(cmd.build(), ctx))}`;
25723
+ }
25724
+ }),
25725
+ defineTool2({
25726
+ name: "add_container_env",
25727
+ title: "Add Container Env Variable",
25728
+ annotations: WRITE,
25729
+ description: "Add a sensitive value to a named env list. Current CLI groups by list; check target syntax. Review all consumers before changing a shared list. Existing running containers may need an approved stop/start; no implicit restart.",
25730
+ inputSchema: { list: textValue, key: textValue, value: string() },
25731
+ async handler(a, ctx) {
25732
+ const count = await containerRead(new Cmd("/container envs print count-only where").set("list", a.list).set("key", a.key).build(), ctx);
25733
+ if (count.trim() !== "0")
25734
+ throw new Error("Env entry exists or uniqueness is unknown; no mutation performed.");
25735
+ await containerWrite(new Cmd("/container envs add").set("list", a.list).set("key", a.key).set("value", a.value).build(), ctx);
25736
+ const countAfter = await containerReadBack(new Cmd("/container envs print count-only where").set("list", a.list).set("key", a.key).build(), ctx);
25737
+ return countAfter.trim() === "1" ? "Env entry creation verified; value omitted." : "Env add accepted; read-back UNVERIFIED. Inspect before retrying.";
25738
+ }
25739
+ }),
25740
+ defineTool2({
25741
+ name: "remove_container_env",
25742
+ title: "Remove Container Env Variable",
25743
+ annotations: DESTRUCTIVE,
25744
+ description: "Remove one env entry by stable id OR exact list+key. Reject duplicates/unreadable selection. Review containers consuming this list first; no implicit restart.",
25745
+ inputSchema: { id: IDENTITY.id, list: textValue.optional(), key: textValue.optional() },
25746
+ async handler(a, ctx) {
25747
+ if (a.id ? a.list !== undefined || a.key !== undefined : !a.list || !a.key)
25748
+ throw new Error("Provide id OR both list and key.");
25749
+ const id = await resolveContainerItem("/container envs", a.id ? { ".id": a.id } : { list: a.list, key: a.key }, ctx);
25750
+ await containerWrite(new Cmd("/container envs remove").set("numbers", id).build(), ctx);
25751
+ const count = await containerReadBack(new Cmd("/container envs print count-only where").set(".id", id).build(), ctx);
25752
+ return count.trim() === "0" ? "Env removal verified." : "Env removal accepted; absence UNVERIFIED. Inspect before retrying.";
25753
+ }
25754
+ }),
25755
+ defineTool2({
25756
+ name: "list_container_mounts",
25757
+ title: "List Container Mounts",
25758
+ annotations: READ,
25759
+ description: "Read mount metadata. Current CLI groups by list; legacy CLI may use name. No application files are read. A list can contain several mounts.",
25760
+ inputSchema: {
25761
+ list_filter: textValue.optional(),
25762
+ name_filter: textValue.optional().describe("Legacy exact name filter")
25763
+ },
25764
+ async handler(a, ctx) {
25765
+ if (a.list_filter !== undefined && a.name_filter !== undefined)
25766
+ throw new Error("Choose list_filter or legacy name_filter.");
25767
+ const cmd = new Cmd("/container mounts print detail");
25768
+ if (a.list_filter !== undefined)
25769
+ cmd.raw("where").set("list", a.list_filter);
25770
+ if (a.name_filter !== undefined)
25771
+ cmd.raw("where").set("name", a.name_filter);
25772
+ return `CONTAINER MOUNTS:
25773
+
25774
+ ${redactContainerText(await containerRead(cmd.build(), ctx))}`;
25775
+ }
25776
+ }),
25777
+ defineTool2({
25778
+ name: "add_container_mount",
25779
+ title: "Add Container Mount",
25780
+ annotations: WRITE,
25781
+ description: "Add a persistent mount using current list= OR legacy name=, never both. Verify target syntax first. Use appropriate storage; a missing source may be populated from the image. Review consumers; this neither formats storage nor restarts containers.",
25782
+ inputSchema: {
25783
+ list: textValue.optional().describe("Current CLI mount-list name"),
25784
+ name: textValue.optional().describe("Legacy CLI mount name; do not use for current list syntax"),
25785
+ src: textValue,
25786
+ dst: textValue
25787
+ },
25788
+ async handler(a, ctx) {
25789
+ if (Boolean(a.list) === Boolean(a.name))
25790
+ throw new Error("Provide list OR legacy name.");
25791
+ const selector = new Cmd("").opt("list", a.list).opt("name", a.name).set("src", a.src).set("dst", a.dst).build().trim();
25792
+ const count = await containerRead(`/container mounts print count-only where ${selector}`, ctx);
25793
+ if (count.trim() !== "0")
25794
+ throw new Error("Mount exists or uniqueness is unknown; no mutation performed.");
25795
+ await containerWrite(new Cmd("/container mounts add").opt("list", a.list).opt("name", a.name).set("src", a.src).set("dst", a.dst).build(), ctx);
25796
+ const countAfter = await containerReadBack(`/container mounts print count-only where ${selector}`, ctx);
25797
+ return countAfter.trim() === "1" ? "Mount creation verified; inspect application data separately." : "Mount add accepted; read-back UNVERIFIED. Inspect before retrying.";
25798
+ }
25799
+ }),
25800
+ defineTool2({
25801
+ name: "remove_container_mount",
25802
+ title: "Remove Container Mount",
25803
+ annotations: DESTRUCTIVE,
25804
+ description: "Remove one mount definition by stable id or unique list/name, optionally narrowed by src/dst. Rejects multi-entry lists. Review shared consumers first; no host files are deleted by this tool.",
25805
+ inputSchema: {
25806
+ id: IDENTITY.id,
25807
+ list: textValue.optional(),
25808
+ name: textValue.optional(),
25809
+ src: textValue.optional(),
25810
+ dst: textValue.optional()
25811
+ },
25812
+ async handler(a, ctx) {
25813
+ if ([a.id, a.list, a.name].filter((v) => v !== undefined).length !== 1 || a.id && (a.src || a.dst))
25814
+ throw new Error("Provide id OR list/name with optional src/dst.");
25815
+ const id = await resolveContainerItem("/container mounts", a.id ? { ".id": a.id } : { list: a.list, name: a.name, src: a.src, dst: a.dst }, ctx);
25816
+ await containerWrite(new Cmd("/container mounts remove").set("numbers", id).build(), ctx);
25817
+ const count = await containerReadBack(new Cmd("/container mounts print count-only where").set(".id", id).build(), ctx);
25818
+ return count.trim() === "0" ? "Mount definition removal verified; host files were not touched." : "Mount removal accepted; absence UNVERIFIED. Inspect before retrying.";
25819
+ }
25820
+ })
25821
+ ];
25822
+ var containerTools = [
25823
+ defineTool2({
25824
+ name: "get_routeros_container_guide",
25825
+ title: "Get RouterOS Container Guide",
25826
+ description: "Read shared version-aware container knowledge: prerequisites, image compatibility, VETH isolation, lifecycle, secrets and troubleshooting. No device access. Use before auditing, deploying or changing containers.",
25827
+ annotations: READ,
25828
+ noDevice: true,
25829
+ inputSchema: { topic: _enum(["all", ...CONTAINER_GUIDE_TOPICS]).default("all") },
25830
+ async handler(a) {
25831
+ return getRouterosContainerGuide(a.topic);
25832
+ }
25833
+ }),
25834
+ ...withRequires({ packages: ["container"], deviceMode: "container", minVersion: "7.0" }, deviceTools2)
25835
+ ];
25836
+
24095
25837
  // src/core/firewall-audit.ts
24096
- import * as ipaddr2 from "ipaddr.js";
25838
+ import * as ipaddr3 from "ipaddr.js";
24097
25839
 
24098
25840
  // src/schedule/identity.ts
24099
- import { createHash as createHash5 } from "crypto";
25841
+ import { createHash as createHash7 } from "crypto";
24100
25842
  function stableId(prefix, parts) {
24101
25843
  const material = parts.filter((p) => p !== undefined && p !== "").map((p) => String(p).trim().toLowerCase()).join(" | ");
24102
- const digest = createHash5("sha256").update(material, "utf8").digest("hex").slice(0, 12);
25844
+ const digest = createHash7("sha256").update(material, "utf8").digest("hex").slice(0, 12);
24103
25845
  return `${prefix}:${digest}`;
24104
25846
  }
24105
25847
  function ruleFingerprint(rule) {
@@ -24212,8 +25954,8 @@ function rulesFromRows(rows) {
24212
25954
  function toCidr(value) {
24213
25955
  try {
24214
25956
  if (value.includes("/"))
24215
- return ipaddr2.parseCIDR(value);
24216
- const addr = ipaddr2.parse(value);
25957
+ return ipaddr3.parseCIDR(value);
25958
+ const addr = ipaddr3.parse(value);
24217
25959
  return [addr, addr.kind() === "ipv6" ? 128 : 32];
24218
25960
  } catch {
24219
25961
  return null;
@@ -24680,395 +26422,8 @@ function tailLines(text, n) {
24680
26422
  return lines.length <= n ? text : lines.slice(-n).join(`
24681
26423
  `);
24682
26424
  }
24683
- // src/tools/container.ts
24684
- var NOT_AVAILABLE = "Container support is not available on this device. Install the `container` package and enable " + "device-mode (`/system/device-mode/update container=yes`, then physically confirm).";
24685
- function containerMatch(name, tag) {
24686
- if (name)
24687
- return `name=${quoteValue(name)}`;
24688
- if (tag)
24689
- return `tag~${quoteValue(tag)}`;
24690
- return null;
24691
- }
24692
- var IDENTITY = {
24693
- name: string().optional().describe("Container name (set via add_container)"),
24694
- tag: string().optional().describe("Image tag to match (e.g. 'pihole') if no name")
24695
- };
24696
- var containerToolsDefs = [
24697
- defineTool2({
24698
- name: "list_containers",
24699
- title: "List Containers",
24700
- annotations: READ,
24701
- description: "List every OCI container on the device (`/container print`) with its status, image tag, name, VETH " + "interface and root-dir \u2014 the starting point for any container work and the way to POLL the lifecycle, " + "which is asynchronous: status moves extracting \u2192 stopped (ready to start) \u2192 running. Use this to find " + "the `name`/`tag` the other tools take, to confirm an add has finished extracting before start_container, " + "and to confirm a stop has completed before remove_container. Filter by partial `name_filter`, " + "`tag_filter`, or `status_filter` (e.g. 'running', 'stopped'); set `detail=true` for the full property " + "block. For one container use get_container. A container's stdout/stderr is in the system log " + '(`/log print where topics~"container"`) when it was created with logging=yes.',
24702
- inputSchema: {
24703
- name_filter: string().optional().describe("Partial container name match"),
24704
- tag_filter: string().optional().describe("Partial image tag match"),
24705
- status_filter: string().optional().describe("e.g. 'running', 'stopped'"),
24706
- detail: boolean().default(false).describe("Show the full per-container property block")
24707
- },
24708
- async handler(a, ctx) {
24709
- ctx.info("Listing containers");
24710
- const filters = [];
24711
- if (a.name_filter)
24712
- filters.push(`name~"${a.name_filter}"`);
24713
- if (a.tag_filter)
24714
- filters.push(`tag~"${a.tag_filter}"`);
24715
- if (a.status_filter)
24716
- filters.push(`status~"${a.status_filter}"`);
24717
- const result = await executeMikrotikCommand2(`/container print${a.detail ? " detail" : ""}${whereClause(filters)}`, ctx);
24718
- if (commandUnsupported(result))
24719
- return NOT_AVAILABLE;
24720
- return isEmpty(result) ? "No containers found matching the criteria." : `CONTAINERS:
24721
-
24722
- ${redactSecrets(result)}`;
24723
- }
24724
- }),
24725
- defineTool2({
24726
- name: "get_container",
24727
- title: "Get Container Detail",
24728
- annotations: READ,
24729
- description: "Full detail for one container (`/container print detail`) \u2014 status, image tag, interface, root-dir, " + "env/mounts, cmd/entrypoint, hostname/dns, logging and start-on-boot. Identify by `name` (preferred) or " + "`tag`. Use list_containers to discover identifiers.",
24730
- inputSchema: { ...IDENTITY },
24731
- async handler(a, ctx) {
24732
- const match = containerMatch(a.name, a.tag);
24733
- if (!match)
24734
- return "Provide a container name or tag.";
24735
- ctx.info(`Getting container detail: ${match}`);
24736
- const result = await executeMikrotikCommand2(`/container print detail where ${match}`, ctx);
24737
- if (commandUnsupported(result))
24738
- return NOT_AVAILABLE;
24739
- return isEmpty(result) ? `Container (${match}) not found.` : `CONTAINER DETAILS:
24740
-
24741
- ${redactSecrets(result)}`;
24742
- }
24743
- }),
24744
- defineTool2({
24745
- name: "add_container",
24746
- title: "Add Container",
24747
- annotations: WRITE,
24748
- description: "Create an OCI container (`/container add`). " + "PREREQUISITES, in order: (1) the `container` package installed + device-mode `container=yes`; " + "(2) an external disk for storage (containers should never run on internal flash); " + "(3) for `remote_image`, a registry URL + on-disk `tmpdir` set via set_container_config; " + "(4) a VETH for networking \u2014 create it first with `/interface veth add name=veth1 " + "address=172.17.0.2/24 gateway=172.17.0.1`, then bridge it and add a srcnat masquerade rule for " + "internet (and a dst-nat to publish a port). " + "Then create the container: supply EITHER `remote_image` (registry pull, e.g. 'library/alpine:latest') " + "OR `file` (a local image tar on the device \u2014 must be a SINGLE-LAYER, UNCOMPRESSED Docker-v1 tar). " + "Set `interface` to the VETH and `root_dir` to a path on the external disk (e.g. 'disk1/myapp'). " + "Attach config via inline `env` ('K=v,K2=v2') / `mount` ('src=disk1/data,dst=/data'), or reference " + "named lists with `envlists`/`mountlists` (add_container_env / add_container_mount). Override " + "`cmd`/`entrypoint`/`workdir`; set `hostname`/`dns`; enable `logging`/`start_on_boot`; cap " + "`memory_high`/`cpu_list`. ALWAYS set `name` so the lifecycle tools can find it. " + "The image pull/extract is ASYNCHRONOUS: this returns immediately, then poll list_containers until " + "status becomes 'stopped' (extraction done) before calling start_container.",
24749
- inputSchema: {
24750
- name: string().optional().describe("Container name (recommended for management)"),
24751
- remote_image: string().optional().describe("Registry image, e.g. 'library/alpine:latest'"),
24752
- file: string().optional().describe("Local Docker-v1 tar on the device (alternative to remote_image)"),
24753
- interface: string().optional().describe("VETH interface name"),
24754
- root_dir: string().optional().describe("Filesystem root, e.g. 'disk1/myapp'"),
24755
- env: string().optional().describe("Inline env vars: 'K=v,K2=v2' (7.21+)"),
24756
- envlists: string().optional().describe("Named env list name(s) (add_container_env)"),
24757
- mount: string().optional().describe("Inline mount: 'src=disk1/data,dst=/data' (7.21+)"),
24758
- mountlists: string().optional().describe("Named mount name(s) (add_container_mount)"),
24759
- cmd: string().optional().describe("Override container CMD"),
24760
- entrypoint: string().optional().describe("Override container ENTRYPOINT"),
24761
- workdir: string().optional().describe("Override working directory"),
24762
- hostname: string().optional(),
24763
- dns: string().optional().describe("DNS server for the container"),
24764
- user: string().optional(),
24765
- stop_signal: string().optional().describe("Signal used to stop the container"),
24766
- devices: string().optional().describe("Pass-through physical devices (7.20+)"),
24767
- cpu_list: string().optional().describe("CPU core affinity"),
24768
- memory_high: string().optional().describe("RAM limit, e.g. '256M'"),
24769
- logging: boolean().optional().describe("Send stdout/stderr to the RouterOS log"),
24770
- start_on_boot: boolean().optional().describe("Auto-start on device boot"),
24771
- comment: string().optional()
24772
- },
24773
- async handler(a, ctx) {
24774
- if (!a.remote_image && !a.file)
24775
- return "Provide remote_image (registry pull) or file (local tar).";
24776
- ctx.info(`Adding container: ${a.name ?? a.remote_image ?? a.file}`);
24777
- const cmd = new Cmd("/container add").opt("name", a.name).opt("remote-image", a.remote_image).opt("file", a.file).opt("interface", a.interface).opt("root-dir", a.root_dir).opt("env", a.env).opt("envlists", a.envlists).opt("mount", a.mount).opt("mountlists", a.mountlists).opt("cmd", a.cmd).opt("entrypoint", a.entrypoint).opt("workdir", a.workdir).opt("hostname", a.hostname).opt("dns", a.dns).opt("user", a.user).opt("stop-signal", a.stop_signal).opt("devices", a.devices).opt("cpu-list", a.cpu_list).opt("memory-high", a.memory_high).bool("logging", a.logging).bool("start-on-boot", a.start_on_boot).opt("comment", a.comment).build();
24778
- const result = await executeMikrotikCommand2(cmd, ctx);
24779
- if (commandUnsupported(result))
24780
- return NOT_AVAILABLE;
24781
- if (looksLikeError(result))
24782
- return `Failed to add container: ${redactSecrets(result)}`;
24783
- return `Container added (image is pulling/extracting asynchronously \u2014 poll list_containers until status is ` + `'stopped', then start_container).
24784
-
24785
- ${redactSecrets(result)}`;
24786
- }
24787
- }),
24788
- defineTool2({
24789
- name: "update_container",
24790
- title: "Update Container",
24791
- annotations: WRITE_IDEMPOTENT,
24792
- description: "Modify an existing container's properties in place (`/container set [find \u2026]`) without recreating it \u2014 " + "change `start_on_boot`, `logging`, `cmd`/`entrypoint`/`workdir`, `hostname`/`dns`, `interface`, " + "`root_dir`, inline `env`/`mount` or `envlists`/`mountlists`, resource caps, or `comment`. Identify by " + "`name` or `tag`. Best practice: stop the container first (stop_container) before changing runtime " + "properties like interface, env, mounts or cmd \u2014 they take effect on the next start_container, not " + "live. To create a new container use add_container; to change the image, remove and re-add.",
24793
- inputSchema: {
24794
- ...IDENTITY,
24795
- interface: string().optional(),
24796
- root_dir: string().optional(),
24797
- env: string().optional(),
24798
- envlists: string().optional(),
24799
- mount: string().optional(),
24800
- mountlists: string().optional(),
24801
- cmd: string().optional(),
24802
- entrypoint: string().optional(),
24803
- workdir: string().optional(),
24804
- hostname: string().optional(),
24805
- dns: string().optional(),
24806
- cpu_list: string().optional(),
24807
- memory_high: string().optional(),
24808
- logging: boolean().optional(),
24809
- start_on_boot: boolean().optional(),
24810
- comment: string().optional()
24811
- },
24812
- async handler(a, ctx) {
24813
- const match = containerMatch(a.name, a.tag);
24814
- if (!match)
24815
- return "Provide a container name or tag.";
24816
- ctx.info(`Updating container: ${match}`);
24817
- const cmd = new Cmd(`/container set [find ${match}]`).opt("interface", a.interface).opt("root-dir", a.root_dir).opt("env", a.env).opt("envlists", a.envlists).opt("mount", a.mount).opt("mountlists", a.mountlists).opt("cmd", a.cmd).opt("entrypoint", a.entrypoint).opt("workdir", a.workdir).opt("hostname", a.hostname).opt("dns", a.dns).opt("cpu-list", a.cpu_list).opt("memory-high", a.memory_high).bool("logging", a.logging).bool("start-on-boot", a.start_on_boot).opt("comment", a.comment).build();
24818
- if (cmd.endsWith("]"))
24819
- return "No updates specified.";
24820
- const result = await executeMikrotikCommand2(cmd, ctx);
24821
- if (commandUnsupported(result))
24822
- return NOT_AVAILABLE;
24823
- if (looksLikeError(result))
24824
- return `Failed to update container: ${redactSecrets(result)}`;
24825
- return `Container (${match}) updated.`;
24826
- }
24827
- }),
24828
- defineTool2({
24829
- name: "start_container",
24830
- title: "Start Container",
24831
- annotations: WRITE,
24832
- description: "Start a stopped container (`/container start [find \u2026]`). Identify by `name` or `tag`. The container " + "must have finished extracting (status 'stopped') first \u2014 check with list_containers. View its output " + "in the log when logging=yes. To stop it use stop_container.",
24833
- inputSchema: { ...IDENTITY },
24834
- async handler(a, ctx) {
24835
- const match = containerMatch(a.name, a.tag);
24836
- if (!match)
24837
- return "Provide a container name or tag.";
24838
- ctx.info(`Starting container: ${match}`);
24839
- const count = await executeMikrotikCommand2(`/container print count-only where ${match}`, ctx);
24840
- if (commandUnsupported(count))
24841
- return NOT_AVAILABLE;
24842
- if (count.trim() === "0")
24843
- return `Container (${match}) not found.`;
24844
- const result = await executeMikrotikCommand2(`/container start [find ${match}]`, ctx);
24845
- if (looksLikeError(result))
24846
- return `Failed to start container: ${result}`;
24847
- return `Container (${match}) starting.`;
24848
- }
24849
- }),
24850
- defineTool2({
24851
- name: "stop_container",
24852
- title: "Stop Container",
24853
- annotations: WRITE,
24854
- description: "Stop a running container (`/container stop [find \u2026]`). Identify by `name` or `tag`. Stopping is " + "asynchronous \u2014 poll list_containers until status is 'stopped' before removing it. To start it again " + "use start_container.",
24855
- inputSchema: { ...IDENTITY },
24856
- async handler(a, ctx) {
24857
- const match = containerMatch(a.name, a.tag);
24858
- if (!match)
24859
- return "Provide a container name or tag.";
24860
- ctx.info(`Stopping container: ${match}`);
24861
- const count = await executeMikrotikCommand2(`/container print count-only where ${match}`, ctx);
24862
- if (commandUnsupported(count))
24863
- return NOT_AVAILABLE;
24864
- if (count.trim() === "0")
24865
- return `Container (${match}) not found.`;
24866
- const result = await executeMikrotikCommand2(`/container stop [find ${match}]`, ctx);
24867
- if (looksLikeError(result))
24868
- return `Failed to stop container: ${result}`;
24869
- return `Container (${match}) stopping (poll list_containers for status 'stopped').`;
24870
- }
24871
- }),
24872
- defineTool2({
24873
- name: "remove_container",
24874
- title: "Remove Container",
24875
- annotations: DESTRUCTIVE,
24876
- description: "Permanently delete a container (`/container remove [find \u2026]`). The container must be FULLY STOPPED " + "first \u2014 RouterOS rejects removal while it is running or still stopping. If removal fails for that " + "reason, stop it (stop_container), wait until list_containers shows status 'stopped', then retry. " + "Identify by `name` or `tag`. This does not delete its root-dir data on disk.",
24877
- inputSchema: { ...IDENTITY },
24878
- async handler(a, ctx) {
24879
- const match = containerMatch(a.name, a.tag);
24880
- if (!match)
24881
- return "Provide a container name or tag.";
24882
- ctx.info(`Removing container: ${match}`);
24883
- const count = await executeMikrotikCommand2(`/container print count-only where ${match}`, ctx);
24884
- if (commandUnsupported(count))
24885
- return NOT_AVAILABLE;
24886
- if (count.trim() === "0")
24887
- return `Container (${match}) not found.`;
24888
- const result = await executeMikrotikCommand2(`/container remove [find ${match}]`, ctx);
24889
- if (looksLikeError(result)) {
24890
- return `Failed to remove container: ${result}
24891
-
24892
- If it is still running/stopping, stop it first ` + `(stop_container), wait until list_containers shows status 'stopped', then retry.`;
24893
- }
24894
- return `Container (${match}) removed.`;
24895
- }
24896
- }),
24897
- defineTool2({
24898
- name: "get_container_config",
24899
- title: "Get Container Global Config",
24900
- annotations: READ,
24901
- description: "Read the global container configuration (`/container config print`) \u2014 the image registry URL, the " + "tmpdir used for pulls/extraction, the layer directory, and the RAM-high limit. Use to verify the " + "registry/tmpdir are set before pulling images. To change them use set_container_config.",
24902
- async handler(_a, ctx) {
24903
- ctx.info("Getting container config");
24904
- const result = await executeMikrotikCommand2("/container config print", ctx);
24905
- if (commandUnsupported(result))
24906
- return NOT_AVAILABLE;
24907
- return isEmpty(result) ? "No container config found." : `CONTAINER CONFIG:
24908
-
24909
- ${redactSecrets(result)}`;
24910
- }
24911
- }),
24912
- defineTool2({
24913
- name: "set_container_config",
24914
- title: "Set Container Global Config",
24915
- annotations: WRITE_IDEMPOTENT,
24916
- description: "Configure the global container settings (`/container config set`) \u2014 the router-wide singleton that " + "MUST be set before pulling any `remote_image` with add_container. Set `registry_url` (Docker Hub is " + "'https://registry-1.docker.io') and `tmpdir` to a path on an EXTERNAL disk (e.g. 'disk1/pull') \u2014 pulls " + "and extraction need real space and IOPS, never internal flash. Optionally set `layer_dir`, a `ram_high` " + "cap, and `username`/`password` for a private registry (credentials are redacted from output). The " + "router also needs working DNS + internet to reach the registry. To read the current values use " + "get_container_config.",
24917
- inputSchema: {
24918
- registry_url: string().optional().describe("Image registry URL"),
24919
- tmpdir: string().optional().describe("Pull/extract temp dir, e.g. 'disk1/pull'"),
24920
- layer_dir: string().optional().describe("Directory for extracted image layers"),
24921
- ram_high: string().optional().describe("RAM-high limit, e.g. '256M'"),
24922
- username: string().optional().describe("Registry username (private registries)"),
24923
- password: string().optional().describe("Registry password (private registries)")
24924
- },
24925
- async handler(a, ctx) {
24926
- ctx.info("Setting container config");
24927
- const cmd = new Cmd("/container config set").opt("registry-url", a.registry_url).opt("tmpdir", a.tmpdir).opt("layer-dir", a.layer_dir).opt("ram-high", a.ram_high).opt("username", a.username).opt("password", a.password).build();
24928
- if (cmd === "/container config set")
24929
- return "No updates specified.";
24930
- const result = await executeMikrotikCommand2(cmd, ctx);
24931
- if (commandUnsupported(result))
24932
- return NOT_AVAILABLE;
24933
- if (looksLikeError(result))
24934
- return `Failed to set container config: ${redactSecrets(result)}`;
24935
- const detail = await executeMikrotikCommand2("/container config print", ctx);
24936
- return `Container config updated.
24937
-
24938
- ${redactSecrets(detail)}`;
24939
- }
24940
- }),
24941
- defineTool2({
24942
- name: "list_container_envs",
24943
- title: "List Container Env Variables",
24944
- annotations: READ,
24945
- description: "List named environment-variable entries (`/container envs print`) \u2014 each has a `list` (the group name " + "referenced by a container's envlists), a `key` and a `value`. Optionally filter by partial `list_filter`. " + "To add one use add_container_env; to delete use remove_container_env.",
24946
- inputSchema: {
24947
- list_filter: string().optional().describe("Partial env-list (group) name match")
24948
- },
24949
- async handler(a, ctx) {
24950
- ctx.info("Listing container envs");
24951
- const filters = [];
24952
- if (a.list_filter)
24953
- filters.push(`list~"${a.list_filter}"`);
24954
- const result = await executeMikrotikCommand2(`/container envs print${whereClause(filters)}`, ctx);
24955
- if (commandUnsupported(result))
24956
- return NOT_AVAILABLE;
24957
- return isEmpty(result) ? "No container env variables found." : `CONTAINER ENVS:
24958
-
24959
- ${redactSecrets(result)}`;
24960
- }
24961
- }),
24962
- defineTool2({
24963
- name: "add_container_env",
24964
- title: "Add Container Env Variable",
24965
- annotations: WRITE,
24966
- description: "Add an environment variable to a named list (`/container envs add list= key= value=`). Group related " + "variables under the same `list` name, then point a container at the group with `envlists=<list>` " + "(add_container or update_container) \u2014 a container that is already running must be restarted to pick up " + "env changes. Named lists are reusable across containers; for a one-off, self-contained setup the inline " + "`env` on add_container is simpler. The grouping `list=` property requires RouterOS 7.20+. Values may be " + "secrets and are redacted from output.",
24967
- inputSchema: {
24968
- list: string().describe("Env-list (group) name, e.g. 'MYAPP'"),
24969
- key: string().describe("Variable name, e.g. 'TZ'"),
24970
- value: string().describe("Variable value")
24971
- },
24972
- async handler(a, ctx) {
24973
- ctx.info(`Adding container env: list=${a.list} key=${a.key}`);
24974
- const cmd = new Cmd("/container envs add").set("list", a.list).set("key", a.key).set("value", a.value).build();
24975
- const result = await executeMikrotikCommand2(cmd, ctx);
24976
- if (commandUnsupported(result))
24977
- return NOT_AVAILABLE;
24978
- if (looksLikeError(result))
24979
- return `Failed to add env variable: ${redactSecrets(result)}`;
24980
- return `Env '${a.key}' added to list '${a.list}'.`;
24981
- }
24982
- }),
24983
- defineTool2({
24984
- name: "remove_container_env",
24985
- title: "Remove Container Env Variable",
24986
- annotations: DESTRUCTIVE,
24987
- description: "Delete an environment variable from a list (`/container envs remove [find list= key=]`). Supply the " + "`list` (group) name and the `key`. Verifies it exists first. To browse entries use list_container_envs.",
24988
- inputSchema: {
24989
- list: string().describe("Env-list (group) name"),
24990
- key: string().describe("Variable name to remove")
24991
- },
24992
- async handler(a, ctx) {
24993
- ctx.info(`Removing container env: list=${a.list} key=${a.key}`);
24994
- const where = `list=${quoteValue(a.list)} key=${quoteValue(a.key)}`;
24995
- const count = await executeMikrotikCommand2(`/container envs print count-only where ${where}`, ctx);
24996
- if (commandUnsupported(count))
24997
- return NOT_AVAILABLE;
24998
- if (count.trim() === "0")
24999
- return `Env '${a.key}' in list '${a.list}' not found.`;
25000
- const result = await executeMikrotikCommand2(`/container envs remove [find ${where}]`, ctx);
25001
- if (looksLikeError(result))
25002
- return `Failed to remove env variable: ${result}`;
25003
- return `Env '${a.key}' removed from list '${a.list}'.`;
25004
- }
25005
- }),
25006
- defineTool2({
25007
- name: "list_container_mounts",
25008
- title: "List Container Mounts",
25009
- annotations: READ,
25010
- description: "List named volume mounts (`/container mounts print`) \u2014 each has a `name` (referenced by a container's " + "mountlists), a host source `src` (e.g. 'disk1/appdata') and a container destination `dst` (e.g. " + "'/data'). Optionally filter by partial `name_filter`. To add one use add_container_mount; to delete use " + "remove_container_mount.",
25011
- inputSchema: {
25012
- name_filter: string().optional().describe("Partial mount name match")
25013
- },
25014
- async handler(a, ctx) {
25015
- ctx.info("Listing container mounts");
25016
- const filters = [];
25017
- if (a.name_filter)
25018
- filters.push(`name~"${a.name_filter}"`);
25019
- const result = await executeMikrotikCommand2(`/container mounts print${whereClause(filters)}`, ctx);
25020
- if (commandUnsupported(result))
25021
- return NOT_AVAILABLE;
25022
- return isEmpty(result) ? "No container mounts found." : `CONTAINER MOUNTS:
25023
-
25024
- ${result}`;
25025
- }
25026
- }),
25027
- defineTool2({
25028
- name: "add_container_mount",
25029
- title: "Add Container Mount",
25030
- annotations: WRITE,
25031
- description: "Create a named volume mount (`/container mounts add name= src= dst=`) \u2014 persists container data on the " + "host so it survives restarts/recreation. Maps a host source `src` (put it on an EXTERNAL disk, e.g. " + "'disk1/appdata', never internal flash) to a path `dst` inside the container (e.g. '/data'). Point a " + "container at it with `mountlists=<name>` (add_container or update_container); a running container must " + "be restarted to apply mount changes. For a one-off, the inline `mount` on add_container is simpler. " + "Named mounts and `mountlists` require RouterOS 7.21+.",
25032
- inputSchema: {
25033
- name: string().describe("Mount name, e.g. 'appdata'"),
25034
- src: string().describe("Host source path, e.g. 'disk1/appdata'"),
25035
- dst: string().describe("Container destination path, e.g. '/data'")
25036
- },
25037
- async handler(a, ctx) {
25038
- ctx.info(`Adding container mount: name=${a.name}`);
25039
- const cmd = new Cmd("/container mounts add").set("name", a.name).set("src", a.src).set("dst", a.dst).build();
25040
- const result = await executeMikrotikCommand2(cmd, ctx);
25041
- if (commandUnsupported(result))
25042
- return NOT_AVAILABLE;
25043
- if (looksLikeError(result))
25044
- return `Failed to add mount: ${result}`;
25045
- return `Mount '${a.name}' (${a.src} \u2192 ${a.dst}) added.`;
25046
- }
25047
- }),
25048
- defineTool2({
25049
- name: "remove_container_mount",
25050
- title: "Remove Container Mount",
25051
- annotations: DESTRUCTIVE,
25052
- description: "Delete a named volume mount (`/container mounts remove [find name=...]`). Verifies it exists first. " + "Does not delete the host data at `src`. To browse mounts use list_container_mounts.",
25053
- inputSchema: { name: string().describe("Mount name to remove") },
25054
- async handler(a, ctx) {
25055
- ctx.info(`Removing container mount: name=${a.name}`);
25056
- const count = await executeMikrotikCommand2(`/container mounts print count-only where name="${a.name}"`, ctx);
25057
- if (commandUnsupported(count))
25058
- return NOT_AVAILABLE;
25059
- if (count.trim() === "0")
25060
- return `Mount '${a.name}' not found.`;
25061
- const result = await executeMikrotikCommand2(`/container mounts remove [find name="${a.name}"]`, ctx);
25062
- if (looksLikeError(result))
25063
- return `Failed to remove mount: ${result}`;
25064
- return `Mount '${a.name}' removed.`;
25065
- }
25066
- })
25067
- ];
25068
- var containerTools = withRequires({ packages: ["container"], deviceMode: "container", minVersion: "7.0" }, containerToolsDefs);
25069
-
25070
26425
  // src/tools/disk.ts
25071
- var NOT_AVAILABLE2 = "Disk management is not available on this device (no `/disk` support).";
26426
+ var NOT_AVAILABLE = "Disk management is not available on this device (no `/disk` support).";
25072
26427
  var ADD_KEYS = new Set([
25073
26428
  "type",
25074
26429
  "slot",
@@ -25107,7 +26462,7 @@ var diskTools = [
25107
26462
  filters.push(`interface~"${a.interface_filter}"`);
25108
26463
  const result = await executeMikrotikCommand2(`/disk print${a.detail ? " detail" : ""}${whereClause(filters)}`, ctx);
25109
26464
  if (commandUnsupported(result))
25110
- return NOT_AVAILABLE2;
26465
+ return NOT_AVAILABLE;
25111
26466
  return isEmpty(result) ? "No disks found matching the criteria." : `DISKS:
25112
26467
 
25113
26468
  ${result}`;
@@ -25123,7 +26478,7 @@ ${result}`;
25123
26478
  ctx.info(`Getting disk details: slot=${a.slot}`);
25124
26479
  const result = await executeMikrotikCommand2(`/disk print detail where slot="${a.slot}"`, ctx);
25125
26480
  if (commandUnsupported(result))
25126
- return NOT_AVAILABLE2;
26481
+ return NOT_AVAILABLE;
25127
26482
  return isEmpty(result) ? `Disk '${a.slot}' not found.` : `DISK DETAILS:
25128
26483
 
25129
26484
  ${result}`;
@@ -25150,7 +26505,7 @@ ${result}`;
25150
26505
  const cmd = new Cmd(`/disk format-drive ${quoteValue(a.slot)}`).opt("file-system", a.file_system).opt("label", a.label).opt("partition-size", a.partition_size).opt("encryption", a.encryption).opt("encryption-password", a.encryption_password).build();
25151
26506
  const result = await executeMikrotikCommand2(cmd, ctx);
25152
26507
  if (commandUnsupported(result))
25153
- return NOT_AVAILABLE2;
26508
+ return NOT_AVAILABLE;
25154
26509
  if (looksLikeError(result))
25155
26510
  return `Failed to format disk: ${redactSecrets(result)}`;
25156
26511
  return `Formatting disk '${a.slot}'\u2026
@@ -25178,7 +26533,7 @@ ${redactSecrets(result)}`;
25178
26533
  return "No updates specified.";
25179
26534
  const result = await executeMikrotikCommand2(cmd, ctx);
25180
26535
  if (commandUnsupported(result))
25181
- return NOT_AVAILABLE2;
26536
+ return NOT_AVAILABLE;
25182
26537
  if (looksLikeError(result))
25183
26538
  return `Failed to update disk: ${result}`;
25184
26539
  const detail = await executeMikrotikCommand2(`/disk print detail where slot="${a.slot}"`, ctx);
@@ -25206,7 +26561,7 @@ ${detail}`;
25206
26561
  return "No sharing settings specified.";
25207
26562
  const result = await executeMikrotikCommand2(cmd, ctx);
25208
26563
  if (commandUnsupported(result))
25209
- return NOT_AVAILABLE2;
26564
+ return NOT_AVAILABLE;
25210
26565
  if (looksLikeError(result))
25211
26566
  return `Failed to configure disk sharing: ${result}`;
25212
26567
  const detail = await executeMikrotikCommand2(`/disk print detail where slot="${a.slot}"`, ctx);
@@ -25239,7 +26594,7 @@ ${detail}`;
25239
26594
  const built = cmd.build();
25240
26595
  const result = await executeMikrotikCommand2(built, ctx);
25241
26596
  if (commandUnsupported(result))
25242
- return NOT_AVAILABLE2;
26597
+ return NOT_AVAILABLE;
25243
26598
  if (looksLikeError(result))
25244
26599
  return `Failed to add virtual disk: ${redactSecrets(result)}`;
25245
26600
  return `Virtual disk (type=${a.type}) added.
@@ -25257,12 +26612,12 @@ ${redactSecrets(result)}`;
25257
26612
  ctx.info(`Ejecting disk: slot=${a.slot}`);
25258
26613
  const count = await executeMikrotikCommand2(`/disk print count-only where slot="${a.slot}"`, ctx);
25259
26614
  if (commandUnsupported(count))
25260
- return NOT_AVAILABLE2;
26615
+ return NOT_AVAILABLE;
25261
26616
  if (count.trim() === "0")
25262
26617
  return `Disk '${a.slot}' not found.`;
25263
26618
  const result = await executeMikrotikCommand2(`/disk eject [find slot="${a.slot}"]`, ctx);
25264
26619
  if (commandUnsupported(result))
25265
- return NOT_AVAILABLE2;
26620
+ return NOT_AVAILABLE;
25266
26621
  if (looksLikeError(result))
25267
26622
  return `Failed to eject disk: ${result}`;
25268
26623
  return `Disk '${a.slot}' ejected \u2014 safe to remove.`;
@@ -25278,7 +26633,7 @@ ${redactSecrets(result)}`;
25278
26633
  ctx.info(`Removing virtual disk: slot=${a.slot}`);
25279
26634
  const count = await executeMikrotikCommand2(`/disk print count-only where slot="${a.slot}"`, ctx);
25280
26635
  if (commandUnsupported(count))
25281
- return NOT_AVAILABLE2;
26636
+ return NOT_AVAILABLE;
25282
26637
  if (count.trim() === "0")
25283
26638
  return `Disk '${a.slot}' not found.`;
25284
26639
  const result = await executeMikrotikCommand2(`/disk remove [find slot="${a.slot}"]`, ctx);
@@ -25425,7 +26780,7 @@ var cache2 = null;
25425
26780
  async function gateway() {
25426
26781
  if (cache2)
25427
26782
  return cache2;
25428
- const { moduleCatalog } = await import("./library-08g0pwc9.js");
26783
+ const { moduleCatalog } = await import("./library-krajvnj9.js");
25429
26784
  const forIndex = [];
25430
26785
  const byName = new Map;
25431
26786
  for (const mod of moduleCatalog) {
@@ -27555,7 +28910,7 @@ function auditNetworkSegmentation(state) {
27555
28910
  target: `/interface ${iface}`,
27556
28911
  current: `subnets on one L2 domain: ${distinct.join(", ")}`,
27557
28912
  proposed: "move server and client subnets onto separate VLANs / bridges",
27558
- detail: "TOPOLOGY FACT (proven): these subnets share one physical interface with no VLAN/bridge object. " + `ISOLATION CLAIM (${isolationVerified ? "some inter-subnet filtering present \u2014 verify coverage" : "needs_live_verification"}): ` + "static config cannot fully prove no firewall enforces isolation between them. " + "Suggested VLAN plan: keep the server subnet on the native/untagged bridge, move the client " + `pool (${servedByDhcp.join(", ")}) to a new VLAN (e.g. vlan-id 20) via /interface vlan + ` + "/interface bridge vlan, then add a forward-chain rule dropping client\u2192server except allowed " + "ports. NEVER auto-applied \u2014 this is planned network work, not a bug fix."
28913
+ detail: "TOPOLOGY FACT (proven): these subnets share one physical interface with no VLAN/bridge object. " + `ISOLATION CLAIM (${isolationVerified ? "some inter-subnet filtering present \u2014 verify coverage" : "needs_live_verification"}): ` + "static config cannot fully prove no firewall enforces isolation between them. " + "Read get_vlan_segmentation_guide before designing a migration. Confirm port roles, preserve " + `management access and plan separate L2 domains for client pools (${servedByDhcp.join(", ")}) ` + "and servers without assuming a native VLAN or example ID. Review bridge CPU/PVID membership, " + "IPv4/IPv6 INPUT and FORWARD policy, rule order and endpoint tests. NEVER auto-applied \u2014 " + "this is planned network work, not a bug fix."
27559
28914
  });
27560
28915
  }
27561
28916
  return findings;
@@ -28385,7 +29740,7 @@ function evaluatePolicies(policies, model, opts = {}) {
28385
29740
 
28386
29741
  // src/policy/load.ts
28387
29742
  import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
28388
- import { dirname as dirname10, isAbsolute, join as join5, resolve as resolve3 } from "path";
29743
+ import { dirname as dirname11, isAbsolute, join as join6, resolve as resolve3 } from "path";
28389
29744
 
28390
29745
  // src/policy/schema.ts
28391
29746
  var MAX_REGEX_LENGTH = 200;
@@ -28508,18 +29863,18 @@ function validatePolicyText(text) {
28508
29863
  var RULE_EXTENSIONS = [".yaml", ".yml", ".json"];
28509
29864
  function expand(pattern, cwd) {
28510
29865
  const absolute = isAbsolute(pattern) ? pattern : resolve3(cwd, pattern);
28511
- const base = dirname10(absolute);
29866
+ const base = dirname11(absolute);
28512
29867
  const leaf = absolute.slice(base.length + 1);
28513
29868
  if (!leaf.includes("*")) {
28514
29869
  try {
28515
- return statSync2(absolute).isDirectory() ? readdirSync2(absolute).filter((f) => RULE_EXTENSIONS.some((e) => f.endsWith(e))).map((f) => join5(absolute, f)).sort() : [absolute];
29870
+ return statSync2(absolute).isDirectory() ? readdirSync2(absolute).filter((f) => RULE_EXTENSIONS.some((e) => f.endsWith(e))).map((f) => join6(absolute, f)).sort() : [absolute];
28516
29871
  } catch {
28517
29872
  return [];
28518
29873
  }
28519
29874
  }
28520
29875
  const suffix = leaf.replace(/^\*/, "");
28521
29876
  try {
28522
- return readdirSync2(base).filter((f) => suffix === "" ? true : f.endsWith(suffix)).map((f) => join5(base, f)).sort();
29877
+ return readdirSync2(base).filter((f) => suffix === "" ? true : f.endsWith(suffix)).map((f) => join6(base, f)).sort();
28523
29878
  } catch {
28524
29879
  return [];
28525
29880
  }
@@ -28723,7 +30078,7 @@ function renderReport2(report, format, opts = {}) {
28723
30078
  }
28724
30079
 
28725
30080
  // src/policy/session.ts
28726
- import { join as join6 } from "path";
30081
+ import { join as join7 } from "path";
28727
30082
  var MAX_REPORTS = 25;
28728
30083
  var reports = [];
28729
30084
  function rememberReport(report) {
@@ -28738,7 +30093,7 @@ function recentReports() {
28738
30093
  return reports;
28739
30094
  }
28740
30095
  function packagedPolicyPaths() {
28741
- return [join6(PROJECT_ROOT, "policies")];
30096
+ return [join7(PROJECT_ROOT, "policies")];
28742
30097
  }
28743
30098
 
28744
30099
  // src/tools/policy.ts
@@ -37070,7 +38425,7 @@ ${result}`;
37070
38425
  ];
37071
38426
 
37072
38427
  // src/tools/ssh-test.ts
37073
- async function probe(opts, label, command) {
38428
+ async function probe2(opts, label, command) {
37074
38429
  const client = new MikroTikSSHClient2(opts);
37075
38430
  const t0 = Date.now();
37076
38431
  try {
@@ -37104,7 +38459,7 @@ var sshTestTools = [
37104
38459
  return `'${name}' is a MAC-Telnet device (reached by MAC ${dc.mac}) \u2014 it has no SSH connection to test. Use a tool over MAC-Telnet instead.`;
37105
38460
  }
37106
38461
  ctx.info(`Testing SSH from MCP host to configured device '${name}' (${dc.host}:${dc.port})`);
37107
- return probe({
38462
+ return probe2({
37108
38463
  ...sshOptionsOf(dc),
37109
38464
  jump: resolveJump(dc),
37110
38465
  timeoutMs: Math.min(dc.timeoutMs ?? 1e4, 1e4)
@@ -37127,7 +38482,7 @@ var sshTestTools = [
37127
38482
  },
37128
38483
  async handler(a, ctx) {
37129
38484
  ctx.info(`Testing SSH from MCP host to ${a.host}:${a.port} as ${a.username}`);
37130
- return probe({
38485
+ return probe2({
37131
38486
  host: a.host,
37132
38487
  port: a.port,
37133
38488
  username: a.username,
@@ -45264,8 +46619,8 @@ function publishTxn(update) {
45264
46619
  }
45265
46620
 
45266
46621
  // src/txn/store.ts
45267
- import { mkdirSync as mkdirSync10 } from "fs";
45268
- import { dirname as dirname11 } from "path";
46622
+ import { mkdirSync as mkdirSync11 } from "fs";
46623
+ import { dirname as dirname12 } from "path";
45269
46624
  function toRecord(txn, ts, label) {
45270
46625
  return {
45271
46626
  id: txn.id,
@@ -45401,7 +46756,7 @@ class SqliteTxnStore {
45401
46756
  async function openTxnStore(path) {
45402
46757
  if (path !== ":memory:") {
45403
46758
  try {
45404
- mkdirSync10(dirname11(path), { recursive: true });
46759
+ mkdirSync11(dirname12(path), { recursive: true });
45405
46760
  } catch {}
45406
46761
  }
45407
46762
  const { Database } = await import("bun:sqlite");
@@ -46269,8 +47624,8 @@ function createDeviceExecutor2(ctx, rolloutId) {
46269
47624
  }
46270
47625
 
46271
47626
  // src/rollout/store.ts
46272
- import { mkdirSync as mkdirSync11 } from "fs";
46273
- import { dirname as dirname12 } from "path";
47627
+ import { mkdirSync as mkdirSync12 } from "fs";
47628
+ import { dirname as dirname13 } from "path";
46274
47629
  function toRecord2(rollout, ts, opts = {}) {
46275
47630
  return {
46276
47631
  id: rollout.id,
@@ -46403,7 +47758,7 @@ class SqliteRolloutStore {
46403
47758
  async function openRolloutStore(path) {
46404
47759
  if (path !== ":memory:") {
46405
47760
  try {
46406
- mkdirSync11(dirname12(path), { recursive: true });
47761
+ mkdirSync12(dirname13(path), { recursive: true });
46407
47762
  } catch {}
46408
47763
  }
46409
47764
  const { Database } = await import("bun:sqlite");
@@ -46863,7 +48218,7 @@ function rank(severity) {
46863
48218
  const i = SEVERITY_ORDER4.indexOf(severity);
46864
48219
  return i === -1 ? SEVERITY_ORDER4.length : i;
46865
48220
  }
46866
- var FIELDS = [
48221
+ var FIELDS2 = [
46867
48222
  { min: 0, max: 59, name: "minute" },
46868
48223
  { min: 0, max: 23, name: "hour" },
46869
48224
  { min: 1, max: 31, name: "day-of-month" },
@@ -46930,11 +48285,11 @@ function parseCron(expression) {
46930
48285
  }
46931
48286
  const [minute, hour, dom, month, dow] = parts;
46932
48287
  return {
46933
- minutes: parseField(minute, FIELDS[0]),
46934
- hours: parseField(hour, FIELDS[1]),
46935
- daysOfMonth: parseField(dom, FIELDS[2]),
46936
- months: parseField(month, FIELDS[3]),
46937
- daysOfWeek: parseField(dow, FIELDS[4]),
48288
+ minutes: parseField(minute, FIELDS2[0]),
48289
+ hours: parseField(hour, FIELDS2[1]),
48290
+ daysOfMonth: parseField(dom, FIELDS2[2]),
48291
+ months: parseField(month, FIELDS2[3]),
48292
+ daysOfWeek: parseField(dow, FIELDS2[4]),
46938
48293
  domRestricted: dom !== "*",
46939
48294
  dowRestricted: dow !== "*"
46940
48295
  };
@@ -47119,8 +48474,8 @@ var JobSchema = object({
47119
48474
  });
47120
48475
 
47121
48476
  // src/schedule/store.ts
47122
- import { mkdirSync as mkdirSync12 } from "fs";
47123
- import { dirname as dirname13 } from "path";
48477
+ import { mkdirSync as mkdirSync13 } from "fs";
48478
+ import { dirname as dirname14 } from "path";
47124
48479
  var SCHEMA2 = [
47125
48480
  `CREATE TABLE IF NOT EXISTS schedule_jobs (
47126
48481
  id TEXT PRIMARY KEY,
@@ -47262,7 +48617,7 @@ class SqliteScheduleStore {
47262
48617
  async function openScheduleStore(path) {
47263
48618
  if (path !== ":memory:") {
47264
48619
  try {
47265
- mkdirSync12(dirname13(path), { recursive: true });
48620
+ mkdirSync13(dirname14(path), { recursive: true });
47266
48621
  } catch {}
47267
48622
  }
47268
48623
  const { Database } = await import("bun:sqlite");
@@ -47424,7 +48779,7 @@ var riskByTool = null;
47424
48779
  async function riskIndex() {
47425
48780
  if (riskByTool)
47426
48781
  return riskByTool;
47427
- const { moduleCatalog } = await import("./library-08g0pwc9.js");
48782
+ const { moduleCatalog } = await import("./library-krajvnj9.js");
47428
48783
  const index = new Map;
47429
48784
  for (const mod of moduleCatalog) {
47430
48785
  for (const tool of mod.tools)
@@ -49588,7 +50943,7 @@ async function readScanList(ctx, list = "port-scanners") {
49588
50943
  }
49589
50944
 
49590
50945
  // src/attack/correlate.ts
49591
- import { createHash as createHash6 } from "crypto";
50946
+ import { createHash as createHash8 } from "crypto";
49592
50947
  var STAGE_ORDER = ["recon", "attempt", "breach", "persistence"];
49593
50948
  var STAGE_OF = {
49594
50949
  "port-scan": "recon",
@@ -49618,7 +50973,7 @@ var SEVERITY_RANK = {
49618
50973
  info: 4
49619
50974
  };
49620
50975
  function incidentId(source, dayBucket) {
49621
- const digest = createHash6("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
50976
+ const digest = createHash8("sha256").update(`${source}|${dayBucket}`, "utf8").digest("hex").slice(0, 12);
49622
50977
  return `atk_${digest}`;
49623
50978
  }
49624
50979
  function worst(values) {
@@ -49708,7 +51063,7 @@ function mergeIncident(stored, fresh) {
49708
51063
  var RECORD_START = /^\s*time=/;
49709
51064
  var FIELD_RE = /([a-zA-Z][\w-]*)=(?:"((?:[^"\\]|\\.)*)"|(\S*))/g;
49710
51065
  var TIME_WITH_CLOCK_RE = /time=(\S+)[ \t]+(\d{2}:\d{2}:\d{2}(?:\.\d+)?)/;
49711
- function fields(text) {
51066
+ function fields2(text) {
49712
51067
  const out = {};
49713
51068
  for (const m of text.matchAll(FIELD_RE)) {
49714
51069
  out[m[1]] = m[2] !== undefined ? m[2].replace(/\\(.)/g, "$1") : m[3] ?? "";
@@ -49730,7 +51085,7 @@ function parseLogRecords(text) {
49730
51085
  return;
49731
51086
  const raw = current.join(`
49732
51087
  `);
49733
- const f = fields(raw);
51088
+ const f = fields2(raw);
49734
51089
  if (f.time === undefined || f.message === undefined) {
49735
51090
  unparsed.push({ line: startLine, text: raw.trim().slice(0, 200) });
49736
51091
  } else {
@@ -49840,8 +51195,8 @@ function dedupe(events, seen) {
49840
51195
  }
49841
51196
 
49842
51197
  // src/attack/store.ts
49843
- import { mkdirSync as mkdirSync13 } from "fs";
49844
- import { dirname as dirname14 } from "path";
51198
+ import { mkdirSync as mkdirSync14 } from "fs";
51199
+ import { dirname as dirname15 } from "path";
49845
51200
  var SCHEMA3 = [
49846
51201
  `CREATE TABLE IF NOT EXISTS attack_incidents (
49847
51202
  id TEXT PRIMARY KEY,
@@ -50032,7 +51387,7 @@ class SqliteAttackStore {
50032
51387
  async function openAttackStore(path) {
50033
51388
  if (path !== ":memory:") {
50034
51389
  try {
50035
- mkdirSync13(dirname14(path), { recursive: true });
51390
+ mkdirSync14(dirname15(path), { recursive: true });
50036
51391
  } catch {}
50037
51392
  }
50038
51393
  const { Database } = await import("bun:sqlite");
@@ -50706,14 +52061,14 @@ ${result}`;
50706
52061
  ];
50707
52062
 
50708
52063
  // src/core/update-check.ts
50709
- import { existsSync as existsSync4, mkdirSync as mkdirSync14, readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
52064
+ import { existsSync as existsSync4, mkdirSync as mkdirSync15, readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
50710
52065
  import { homedir as homedir2 } from "os";
50711
- import { dirname as dirname15, join as join8 } from "path";
52066
+ import { dirname as dirname16, join as join9 } from "path";
50712
52067
 
50713
52068
  // src/version.ts
50714
52069
  import { readFileSync as readFileSync7 } from "fs";
50715
- import { join as join7 } from "path";
50716
- var pkg = JSON.parse(readFileSync7(join7(PROJECT_ROOT, "package.json"), "utf-8"));
52070
+ import { join as join8 } from "path";
52071
+ var pkg = JSON.parse(readFileSync7(join8(PROJECT_ROOT, "package.json"), "utf-8"));
50717
52072
  var VERSION2 = pkg.version ?? "0.0.0";
50718
52073
  var WEBSITE_URL = pkg.homepage ?? "";
50719
52074
  var LOGO_URL = pkg.logoIcon ?? "";
@@ -50725,7 +52080,7 @@ var SERVER_NAME2 = "mikrotik-mcp";
50725
52080
  var GITHUB_API = "https://api.github.com/repos/mikrotik-mcp/mikrotik-mcp/releases/latest";
50726
52081
  var MEMORY_CACHE_TTL = 15 * 60 * 1000;
50727
52082
  var FILE_CACHE_TTL = 6 * 60 * 60 * 1000;
50728
- var CACHE_PATH = join8(homedir2(), ".mikrotik-mcp", "update-check.json");
52083
+ var CACHE_PATH = join9(homedir2(), ".mikrotik-mcp", "update-check.json");
50729
52084
  function compareVersions2(a, b) {
50730
52085
  const pa = a.replace(/^v/, "").split(".").map(Number);
50731
52086
  const pb = b.replace(/^v/, "").split(".").map(Number);
@@ -50755,9 +52110,9 @@ function loadFileCacheSync() {
50755
52110
  }
50756
52111
  function saveFileCache(data) {
50757
52112
  try {
50758
- const dir = dirname15(CACHE_PATH);
52113
+ const dir = dirname16(CACHE_PATH);
50759
52114
  if (!existsSync4(dir))
50760
- mkdirSync14(dir, { recursive: true });
52115
+ mkdirSync15(dir, { recursive: true });
50761
52116
  writeFileSync3(CACHE_PATH, JSON.stringify({ data, fetchedAt: Date.now() }));
50762
52117
  } catch {}
50763
52118
  }
@@ -50933,8 +52288,443 @@ var serverPulseTools = [
50933
52288
  })
50934
52289
  ];
50935
52290
 
52291
+ // src/observability/config-admin.ts
52292
+ import { createHash as createHash9, randomUUID as randomUUID10 } from "crypto";
52293
+ import { readFileSync as readFileSync10 } from "fs";
52294
+
52295
+ // src/config-write.ts
52296
+ import { randomUUID as randomUUID9 } from "crypto";
52297
+ import {
52298
+ closeSync,
52299
+ constants,
52300
+ fchmodSync,
52301
+ fstatSync,
52302
+ fsyncSync,
52303
+ ftruncateSync,
52304
+ mkdirSync as mkdirSync16,
52305
+ openSync,
52306
+ readFileSync as readFileSync9,
52307
+ renameSync as renameSync2,
52308
+ rmSync as rmSync2,
52309
+ writeFileSync as writeFileSync4,
52310
+ writeSync
52311
+ } from "fs";
52312
+ import { dirname as dirname17 } from "path";
52313
+ var SCHEMA_REF = "./schemas/config.schema.json";
52314
+ function serializeConfig(config) {
52315
+ const body = config && typeof config === "object" && !Array.isArray(config) ? config : {};
52316
+ const { $schema: _drop, ...rest } = body;
52317
+ return `${JSON.stringify({ $schema: SCHEMA_REF, ...rest }, null, 2)}
52318
+ `;
52319
+ }
52320
+ function backupName(path, ts) {
52321
+ return `${path}.bak-${ts}`;
52322
+ }
52323
+ function atomicWrite(path, text) {
52324
+ mkdirSync16(dirname17(path), { recursive: true });
52325
+ const tmp = `${path}.tmp-${randomUUID9()}`;
52326
+ try {
52327
+ writeFileSync4(tmp, text, { encoding: "utf8", mode: 384, flag: "wx", flush: true });
52328
+ try {
52329
+ renameSync2(tmp, path);
52330
+ } catch (error) {
52331
+ if (error.code !== "EBUSY")
52332
+ throw error;
52333
+ writeMountedFile(path, text);
52334
+ }
52335
+ } finally {
52336
+ rmSync2(tmp, { force: true });
52337
+ }
52338
+ }
52339
+ function replaceContents(fd, bytes) {
52340
+ let offset = 0;
52341
+ while (offset < bytes.length) {
52342
+ const written = writeSync(fd, bytes, offset, bytes.length - offset, offset);
52343
+ if (written === 0)
52344
+ throw new Error("Configuration write made no progress.");
52345
+ offset += written;
52346
+ }
52347
+ ftruncateSync(fd, bytes.length);
52348
+ fsyncSync(fd);
52349
+ }
52350
+ function writeMountedFile(path, text) {
52351
+ const fd = openSync(path, constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK);
52352
+ try {
52353
+ if (!fstatSync(fd).isFile())
52354
+ throw new Error("Configuration target must be a regular file.");
52355
+ fchmodSync(fd, 384);
52356
+ const previous = readFileSync9(fd);
52357
+ const backup = `${path}.bak-mounted-${randomUUID9()}`;
52358
+ writeFileSync4(backup, previous, { mode: 384, flag: "wx", flush: true });
52359
+ try {
52360
+ replaceContents(fd, Buffer.from(text, "utf8"));
52361
+ } catch {
52362
+ try {
52363
+ replaceContents(fd, previous);
52364
+ } catch {
52365
+ throw new Error("Configuration write and recovery failed; restore the retained mounted-file backup.");
52366
+ }
52367
+ throw new Error("Configuration write failed; previous contents restored and backup retained.");
52368
+ }
52369
+ } finally {
52370
+ closeSync(fd);
52371
+ }
52372
+ }
52373
+
52374
+ // src/observability/config-admin.ts
52375
+ function createConfigAdmin(deps) {
52376
+ let pending = null;
52377
+ let lastTimestamp = 0;
52378
+ const salt = randomUUID10();
52379
+ const fingerprint = (config, source, contents) => createHash9("sha256").update(salt).update(JSON.stringify([config, source, contents])).digest("hex");
52380
+ const revision = () => {
52381
+ const source = deps.source();
52382
+ return fingerprint(deps.getConfig(), source, deps.readFile(source.path));
52383
+ };
52384
+ const currentPending = () => {
52385
+ if (pending && pending.revision !== revision()) {
52386
+ deps.cancel(pending.timer);
52387
+ pending = null;
52388
+ logger.warn("Config changed outside its pending transaction; preserved newer settings. Backup retained.");
52389
+ }
52390
+ return pending;
52391
+ };
52392
+ const rollback = (id) => {
52393
+ const active = currentPending();
52394
+ if (!active || active.id !== id)
52395
+ return false;
52396
+ const { backupPath, previous, timer, path } = active;
52397
+ const backup = deps.readFile(backupPath);
52398
+ if (backup == null)
52399
+ throw new Error("Configuration backup is unavailable; rollback was not applied.");
52400
+ deps.writeText(path, backup);
52401
+ deps.setConfig(previous);
52402
+ deps.cancel(timer);
52403
+ pending = null;
52404
+ return true;
52405
+ };
52406
+ const applyConfig = (parsed, rollbackMs) => {
52407
+ if ((currentPending()?.rollbackMs ?? 0) > 0)
52408
+ throw new Error("Another configuration change awaits confirmation. Keep or roll it back first.");
52409
+ const src = deps.source();
52410
+ const previous = deps.getConfig();
52411
+ const ts = Math.max(deps.now(), lastTimestamp + 1);
52412
+ lastTimestamp = ts;
52413
+ const id = `cfg_${ts}`;
52414
+ const backupPath = backupName(src.path, ts);
52415
+ const existing = deps.readFile(src.path) ?? serializeConfig(previous);
52416
+ const contents = serializeConfig(parsed);
52417
+ const nextRevision = fingerprint(parsed, src, contents);
52418
+ deps.writeText(backupPath, existing);
52419
+ deps.writeText(src.path, contents);
52420
+ deps.setConfig(parsed);
52421
+ const timer = rollbackMs > 0 ? deps.schedule(() => {
52422
+ try {
52423
+ rollback(id);
52424
+ } catch {
52425
+ logger.error("Configuration auto-rollback failed; backup retained. Retry rollback or restore it manually.");
52426
+ }
52427
+ }, rollbackMs) : null;
52428
+ pending = {
52429
+ id,
52430
+ backupPath,
52431
+ previous,
52432
+ timer,
52433
+ rollbackMs,
52434
+ path: src.path,
52435
+ revision: nextRevision
52436
+ };
52437
+ return {
52438
+ pendingId: id,
52439
+ rollbackMs,
52440
+ path: src.path,
52441
+ fromFile: src.fromFile,
52442
+ backupPath,
52443
+ expiresAt: rollbackMs > 0 ? deps.now() + rollbackMs : null
52444
+ };
52445
+ };
52446
+ const keepConfig = (id) => {
52447
+ const active = currentPending();
52448
+ if (!active || active.id !== id)
52449
+ return false;
52450
+ deps.cancel(active.timer);
52451
+ pending = null;
52452
+ return true;
52453
+ };
52454
+ return {
52455
+ applyConfig,
52456
+ keepConfig,
52457
+ rollback,
52458
+ pendingId: () => {
52459
+ const active = currentPending();
52460
+ return active && active.rollbackMs > 0 ? active.id : null;
52461
+ },
52462
+ revision
52463
+ };
52464
+ }
52465
+ var sharedAdmin;
52466
+ function getConfigAdmin() {
52467
+ return sharedAdmin ??= createConfigAdmin({
52468
+ getConfig: getConfig2,
52469
+ setConfig: setConfig2,
52470
+ source: getConfigSource2,
52471
+ readFile: (path) => {
52472
+ try {
52473
+ return readFileSync10(path, "utf8");
52474
+ } catch (error) {
52475
+ if (error.code === "ENOENT")
52476
+ return null;
52477
+ throw new Error("Cannot read the MCP configuration file; check host-side file permissions.");
52478
+ }
52479
+ },
52480
+ writeText: atomicWrite,
52481
+ now: Date.now,
52482
+ schedule: (fn, ms) => setTimeout(fn, ms),
52483
+ cancel: (timer) => {
52484
+ if (timer)
52485
+ clearTimeout(timer);
52486
+ }
52487
+ });
52488
+ }
52489
+
52490
+ // src/core/mcp-settings.ts
52491
+ var McpSettingsPatchSchema = object({
52492
+ mcp: object({
52493
+ toolPageSize: McpServerSettingsSchema2.shape.toolPageSize.removeDefault().optional(),
52494
+ appViews: McpServerSettingsSchema2.shape.appViews.removeDefault().optional(),
52495
+ capabilityGating: McpServerSettingsSchema2.shape.capabilityGating.removeDefault().optional()
52496
+ }).strict().optional(),
52497
+ ssh: object({
52498
+ keepAlive: SSHConfigSchema2.shape.keepAlive.removeDefault().optional(),
52499
+ keepAliveInterval: SSHConfigSchema2.shape.keepAliveInterval.removeDefault().optional(),
52500
+ idleTimeout: SSHConfigSchema2.shape.idleTimeout.removeDefault().optional()
52501
+ }).strict().optional(),
52502
+ dashboard: object({
52503
+ maxEvents: DashboardConfigSchema2.shape.maxEvents.removeDefault().optional(),
52504
+ captureBody: DashboardConfigSchema2.shape.captureBody.removeDefault().optional(),
52505
+ redactInput: literal(true).optional().describe("May enable redaction, never disable it."),
52506
+ maxBodyBytes: DashboardConfigSchema2.shape.maxBodyBytes.removeDefault().optional(),
52507
+ feedLimit: DashboardConfigSchema2.shape.feedLimit.removeDefault().optional()
52508
+ }).strict().optional(),
52509
+ memory: object({
52510
+ enabled: MemoryConfigSchema2.shape.enabled.removeDefault().optional()
52511
+ }).strict().optional(),
52512
+ disableUpdateCheck: MikrotikConfigSchema2.shape.disableUpdateCheck.removeDefault().optional()
52513
+ }).strict();
52514
+ var McpSettingsUpdateSchema = object({
52515
+ changes: McpSettingsPatchSchema,
52516
+ revision: string().length(64).describe("Current revision from get_mcp_settings or preview_mcp_settings."),
52517
+ confirm: literal(true).describe("Only set after the user authorizes these exact changes."),
52518
+ rollback_seconds: number().int().min(30).max(600).default(60)
52519
+ }).strict();
52520
+ var McpSettingsPendingSchema = object({
52521
+ pending_id: string().min(1),
52522
+ revision: string().length(64).describe("Revision returned by update_mcp_settings or get_mcp_settings.")
52523
+ }).strict();
52524
+ var BOUNDARY = "Only the listed fields are editable. Devices, credentials, file paths, listeners, access, readOnly, tools and service probe allowlists remain operator-managed. No router is contacted.";
52525
+ function settings2(cfg) {
52526
+ return {
52527
+ mcp: {
52528
+ toolPageSize: cfg.mcp.toolPageSize,
52529
+ appViews: cfg.mcp.appViews,
52530
+ capabilityGating: cfg.mcp.capabilityGating
52531
+ },
52532
+ ssh: {
52533
+ keepAlive: cfg.ssh.keepAlive,
52534
+ keepAliveInterval: cfg.ssh.keepAliveInterval,
52535
+ idleTimeout: cfg.ssh.idleTimeout
52536
+ },
52537
+ dashboard: {
52538
+ maxEvents: cfg.dashboard.maxEvents,
52539
+ captureBody: cfg.dashboard.captureBody,
52540
+ redactInput: cfg.dashboard.redactInput,
52541
+ maxBodyBytes: cfg.dashboard.maxBodyBytes,
52542
+ feedLimit: cfg.dashboard.feedLimit
52543
+ },
52544
+ memory: { enabled: cfg.memory.enabled },
52545
+ disableUpdateCheck: cfg.disableUpdateCheck
52546
+ };
52547
+ }
52548
+ function createMcpSettingsService(deps) {
52549
+ let owned = null;
52550
+ const read = () => {
52551
+ const id = deps.admin.pendingId();
52552
+ const source = deps.source();
52553
+ return {
52554
+ revision: deps.admin.revision(),
52555
+ settings: settings2(deps.getConfig()),
52556
+ pending: id ? { id, owned: id === owned?.id, expiresAt: id === owned?.id ? owned.expiresAt : null } : null,
52557
+ persistence: {
52558
+ path: source.path,
52559
+ fromFile: source.fromFile,
52560
+ note: source.fromFile ? "Saved to the source config file; CLI/environment overrides may still take precedence on restart." : "Saved to the default config file. Start with --config pointing to the returned path to reuse it; environment/CLI overrides may still take precedence."
52561
+ },
52562
+ boundary: BOUNDARY
52563
+ };
52564
+ };
52565
+ const prepare = (raw) => {
52566
+ const parsed = McpSettingsPatchSchema.safeParse(raw);
52567
+ if (!parsed.success)
52568
+ throw new Error("Invalid or protected MCP setting. Use get_mcp_settings_schema for allowed fields and values.");
52569
+ const changes = parsed.data;
52570
+ const current = deps.getConfig();
52571
+ const next = MikrotikConfigSchema2.parse({
52572
+ ...current,
52573
+ ...changes,
52574
+ mcp: { ...current.mcp, ...changes.mcp },
52575
+ ssh: { ...current.ssh, ...changes.ssh },
52576
+ dashboard: { ...current.dashboard, ...changes.dashboard },
52577
+ memory: { ...current.memory, ...changes.memory }
52578
+ });
52579
+ if (changes.dashboard?.captureBody === true && !next.dashboard.redactInput)
52580
+ throw new Error("Enabling body capture also requires dashboard.redactInput=true.");
52581
+ const before = settings2(current);
52582
+ const after = settings2(next);
52583
+ const changedPaths = [];
52584
+ for (const key of ["mcp", "ssh", "dashboard", "memory"]) {
52585
+ for (const [field, value] of Object.entries(after[key])) {
52586
+ if (value !== before[key][field])
52587
+ changedPaths.push(`${key}.${field}`);
52588
+ }
52589
+ }
52590
+ if (before.disableUpdateCheck !== after.disableUpdateCheck)
52591
+ changedPaths.push("disableUpdateCheck");
52592
+ const restartRequired = changedPaths.some((path) => path.startsWith("mcp.") || path.startsWith("dashboard.") || path === "disableUpdateCheck");
52593
+ const diff = diffLines(JSON.stringify(before, null, 2), JSON.stringify(after, null, 2), {
52594
+ fromLabel: "current MCP settings",
52595
+ toLabel: "proposed MCP settings"
52596
+ });
52597
+ return {
52598
+ next,
52599
+ preview: {
52600
+ revision: deps.admin.revision(),
52601
+ changedPaths,
52602
+ before,
52603
+ after,
52604
+ summary: diff.summary,
52605
+ unified: diff.unified,
52606
+ restartRequired,
52607
+ activation: [
52608
+ "Memory enable/disable is checked on the next memory operation; disabling does not delete stored knowledge.",
52609
+ "SSH pool changes affect subsequent calls/new connections and newly armed idle timers; existing connections are not forcibly closed.",
52610
+ "MCP presentation, dashboard recorder and startup update-check settings require a server restart for full activation. Confirm the change before restarting; an in-process rollback timer cannot survive process exit."
52611
+ ]
52612
+ }
52613
+ };
52614
+ };
52615
+ const checkWrite = (revision) => {
52616
+ if (deps.getConfig().readOnly)
52617
+ throw new Error("MCP settings writes are disabled in read-only mode.");
52618
+ if (revision !== deps.admin.revision())
52619
+ throw new Error("MCP settings changed. Read and preview again before writing.");
52620
+ };
52621
+ return {
52622
+ read,
52623
+ schema: () => ({
52624
+ schema: toJSONSchema(McpSettingsPatchSchema, { target: "draft-2020-12" }),
52625
+ boundary: BOUNDARY
52626
+ }),
52627
+ preview: (changes) => prepare(changes).preview,
52628
+ update: (raw) => {
52629
+ const input = McpSettingsUpdateSchema.safeParse(raw);
52630
+ if (!input.success)
52631
+ throw new Error("Invalid settings update. A current revision, allowed changes, confirm=true and 30\u2013600 second rollback window are required.");
52632
+ checkWrite(input.data.revision);
52633
+ if (deps.admin.pendingId())
52634
+ throw new Error("Another configuration change is pending. Confirm or roll back its owning workflow first.");
52635
+ const { next, preview } = prepare(input.data.changes);
52636
+ if (!preview.changedPaths.length)
52637
+ return { applied: false, ...preview, ...read() };
52638
+ const applied = deps.admin.applyConfig(next, input.data.rollback_seconds * 1000);
52639
+ owned = { id: applied.pendingId, expiresAt: applied.expiresAt };
52640
+ return { applied: true, ...preview, ...applied, ...read() };
52641
+ },
52642
+ finish: (raw, action) => {
52643
+ const result = McpSettingsPendingSchema.safeParse(raw);
52644
+ if (!result.success)
52645
+ throw new Error("A pending_id and current revision are required.");
52646
+ const input = result.data;
52647
+ checkWrite(input.revision);
52648
+ if (!owned || owned.id !== input.pending_id || deps.admin.pendingId() !== owned.id)
52649
+ throw new Error("This transaction is not pending in MCP settings. It may have expired or belong to the dashboard.");
52650
+ const ok = action === "confirm" ? deps.admin.keepConfig(owned.id) : deps.admin.rollback(owned.id);
52651
+ if (!ok)
52652
+ throw new Error("Configuration changed before confirmation; read settings again.");
52653
+ owned = null;
52654
+ return { action, ok, ...read() };
52655
+ }
52656
+ };
52657
+ }
52658
+ var service;
52659
+ function getMcpSettingsService() {
52660
+ return service ??= createMcpSettingsService({
52661
+ admin: getConfigAdmin(),
52662
+ getConfig: getConfig2,
52663
+ source: getConfigSource2
52664
+ });
52665
+ }
52666
+
52667
+ // src/tools/mcp-settings.ts
52668
+ var render = (value) => JSON.stringify(value, null, 2);
52669
+ var mcpSettingsTools = [
52670
+ defineTool2({
52671
+ name: "get_mcp_settings",
52672
+ title: "Read MCP Server Settings",
52673
+ noDevice: true,
52674
+ annotations: READ,
52675
+ description: "Read the MCP host's editable settings, opaque revision and pending change. Covers tool presentation, SSH pooling, dashboard recording, Memory enablement and startup update checks. Contains no credentials; never contacts a router. These are configured values, not proof a startup-only component has restarted. Read before preview_mcp_settings or update_mcp_settings.",
52676
+ handler: () => render(getMcpSettingsService().read())
52677
+ }),
52678
+ defineTool2({
52679
+ name: "get_mcp_settings_schema",
52680
+ title: "Describe Editable MCP Settings",
52681
+ noDevice: true,
52682
+ annotations: READ,
52683
+ description: "Get the exact JSON Schema for the partial changes accepted by preview_mcp_settings and update_mcp_settings. Unknown/protected fields are rejected, omitted fields stay unchanged. Credentials, listeners, file paths, device inventory and permission ceilings are operator-managed. No device or file changes.",
52684
+ handler: () => render(getMcpSettingsService().schema())
52685
+ }),
52686
+ defineTool2({
52687
+ name: "preview_mcp_settings",
52688
+ title: "Validate and Preview MCP Settings",
52689
+ noDevice: true,
52690
+ annotations: READ,
52691
+ description: "Validate a partial MCP settings change against live configuration and return changed paths, a secret-free diff, revision and restart requirements. No file writes or router contact. Show the preview and obtain user approval before applying; never guess setting names.",
52692
+ inputSchema: {
52693
+ changes: McpSettingsPatchSchema.describe("Only the fields to change; omitted values are preserved.")
52694
+ },
52695
+ handler: (args) => render(getMcpSettingsService().preview(args.changes))
52696
+ }),
52697
+ defineTool2({
52698
+ name: "update_mcp_settings",
52699
+ title: "Safely Update MCP Settings",
52700
+ noDevice: true,
52701
+ annotations: WRITE,
52702
+ description: "Apply explicitly user-approved MCP host settings, not RouterOS configuration. First get_mcp_settings_schema and preview_mcp_settings; supply that revision and confirm=true. Backs up the source JSON, persists the full config and arms a 30\u2013600s in-process rollback (default 60s). Normal files use atomic replacement; a single-file Docker bind mount uses a backed-up in-place write that is not crash-atomic. Conflicts with another pending dashboard/tool edit are rejected. Verify configured values with get_mcp_settings, then confirm_mcp_settings before the deadline or rollback_mcp_settings. Never restart while pending: the rollback timer does not survive process exit. Restart-required settings are only fully activated after confirmation and a separate operator-controlled restart. Does not widen access scopes or change router addresses/credentials.",
52703
+ inputSchema: McpSettingsUpdateSchema.shape,
52704
+ handler: (args) => render(getMcpSettingsService().update(args))
52705
+ }),
52706
+ defineTool2({
52707
+ name: "confirm_mcp_settings",
52708
+ title: "Keep a Pending MCP Settings Change",
52709
+ noDevice: true,
52710
+ annotations: WRITE,
52711
+ description: "Keep the exact pending change created by update_mcp_settings after reading back its values. Cancels its rollback timer. Requires the current revision and pending_id; cannot confirm dashboard-owned, expired or superseded changes. Does not restart the MCP server or contact routers.",
52712
+ inputSchema: McpSettingsPendingSchema.shape,
52713
+ handler: (args) => render(getMcpSettingsService().finish(args, "confirm"))
52714
+ }),
52715
+ defineTool2({
52716
+ name: "rollback_mcp_settings",
52717
+ title: "Revert a Pending MCP Settings Change",
52718
+ noDevice: true,
52719
+ annotations: WRITE,
52720
+ description: "Restore the host-side config backup for a still-pending update_mcp_settings change. Requires its pending_id and current revision. Refuses dashboard-owned transactions or changes that would overwrite newer configuration. Restores configured values only; no router changes, server restart or deletion of knowledge data.",
52721
+ inputSchema: McpSettingsPendingSchema.shape,
52722
+ handler: (args) => render(getMcpSettingsService().finish(args, "rollback"))
52723
+ })
52724
+ ];
52725
+
50936
52726
  // src/tools/capability.ts
50937
- function render(deviceName, caps) {
52727
+ function render2(deviceName, caps) {
50938
52728
  const lines = [`DEVICE CAPABILITIES \u2014 ${deviceName}`, ""];
50939
52729
  if (!caps.version && caps.packages.size === 0 && !caps.board) {
50940
52730
  return `${lines.join(`
@@ -50997,7 +52787,7 @@ var capabilityTools = [
50997
52787
  async handler(_a, ctx) {
50998
52788
  const name = resolveDeviceName2(ctx.device);
50999
52789
  ctx.info(`Reading device capabilities: ${name}`);
51000
- return render(name, await getCapabilities(ctx.device));
52790
+ return render2(name, await getCapabilities(ctx.device));
51001
52791
  }
51002
52792
  }),
51003
52793
  defineTool2({
@@ -51010,7 +52800,7 @@ var capabilityTools = [
51010
52800
  const name = resolveDeviceName2(ctx.device);
51011
52801
  ctx.info(`Refreshing device capabilities: ${name}`);
51012
52802
  invalidateCapabilities(ctx.device);
51013
- return render(name, await getCapabilities(ctx.device));
52803
+ return render2(name, await getCapabilities(ctx.device));
51014
52804
  }
51015
52805
  })
51016
52806
  ];
@@ -52955,7 +54745,7 @@ ${result}`;
52955
54745
  ];
52956
54746
 
52957
54747
  // src/tools/user-manager.ts
52958
- var NOT_AVAILABLE3 = "User Manager is not available on this device (package not installed).";
54748
+ var NOT_AVAILABLE2 = "User Manager is not available on this device (package not installed).";
52959
54749
  var userManagerToolsDefs = [
52960
54750
  defineTool2({
52961
54751
  name: "get_user_manager_settings",
@@ -52966,7 +54756,7 @@ var userManagerToolsDefs = [
52966
54756
  ctx.info("Getting User Manager settings");
52967
54757
  const result = await executeMikrotikCommand2("/user-manager print", ctx);
52968
54758
  if (commandUnsupported(result))
52969
- return NOT_AVAILABLE3;
54759
+ return NOT_AVAILABLE2;
52970
54760
  return isEmpty(result) ? "No User Manager settings found." : `USER MANAGER SETTINGS:
52971
54761
 
52972
54762
  ${result}`;
@@ -52992,7 +54782,7 @@ ${result}`;
52992
54782
  return "No updates specified.";
52993
54783
  const result = await executeMikrotikCommand2(cmd, ctx);
52994
54784
  if (commandUnsupported(result))
52995
- return NOT_AVAILABLE3;
54785
+ return NOT_AVAILABLE2;
52996
54786
  if (looksLikeError(result))
52997
54787
  return `Failed to update User Manager settings: ${result}`;
52998
54788
  const details = await executeMikrotikCommand2("/user-manager print", ctx);
@@ -53022,7 +54812,7 @@ ${details}`;
53022
54812
  const cmd = new Cmd("/user-manager user add").set("name", a.name).set("password", a.password).opt("group", a.group).opt("shared-users", a.shared_users).opt("attributes", a.attributes).opt("caller-id", a.caller_id).opt("otp-secret", a.otp_secret).opt("comment", a.comment).flag("disabled", a.disabled).build();
53023
54813
  const result = await executeMikrotikCommand2(cmd, ctx);
53024
54814
  if (commandUnsupported(result))
53025
- return NOT_AVAILABLE3;
54815
+ return NOT_AVAILABLE2;
53026
54816
  if (looksLikeError(result))
53027
54817
  return `Failed to add User Manager user: ${result}`;
53028
54818
  const details = await executeMikrotikCommand2(`/user-manager user print detail where name="${a.name}"`, ctx);
@@ -53046,7 +54836,7 @@ ${redactSecrets(details)}` : "User Manager user creation completed but unable to
53046
54836
  filters.push(`name~"${a.name_filter}"`);
53047
54837
  const result = await executeMikrotikCommand2(`/user-manager user print${whereClause(filters)}`, ctx);
53048
54838
  if (commandUnsupported(result))
53049
- return NOT_AVAILABLE3;
54839
+ return NOT_AVAILABLE2;
53050
54840
  return isEmpty(result) ? "No User Manager users found matching the criteria." : `USER MANAGER USERS:
53051
54841
 
53052
54842
  ${redactSecrets(result)}`;
@@ -53062,7 +54852,7 @@ ${redactSecrets(result)}`;
53062
54852
  ctx.info(`Getting User Manager user details: name=${a.name}`);
53063
54853
  const result = await executeMikrotikCommand2(`/user-manager user print detail where name="${a.name}"`, ctx);
53064
54854
  if (commandUnsupported(result))
53065
- return NOT_AVAILABLE3;
54855
+ return NOT_AVAILABLE2;
53066
54856
  return isEmpty(result) ? `User Manager user '${a.name}' not found.` : `USER MANAGER USER DETAILS:
53067
54857
 
53068
54858
  ${redactSecrets(result)}`;
@@ -53092,7 +54882,7 @@ ${redactSecrets(result)}`;
53092
54882
  return "No updates specified.";
53093
54883
  const result = await executeMikrotikCommand2(cmd, ctx);
53094
54884
  if (commandUnsupported(result))
53095
- return NOT_AVAILABLE3;
54885
+ return NOT_AVAILABLE2;
53096
54886
  if (looksLikeError(result))
53097
54887
  return `Failed to update User Manager user: ${result}`;
53098
54888
  const target = a.new_name ?? a.name;
@@ -53112,7 +54902,7 @@ ${redactSecrets(details)}`;
53112
54902
  ctx.info(`Removing User Manager user: name=${a.name}`);
53113
54903
  const count = await executeMikrotikCommand2(`/user-manager user print count-only where name="${a.name}"`, ctx);
53114
54904
  if (commandUnsupported(count))
53115
- return NOT_AVAILABLE3;
54905
+ return NOT_AVAILABLE2;
53116
54906
  if (count.trim() === "0")
53117
54907
  return `User Manager user '${a.name}' not found.`;
53118
54908
  const result = await executeMikrotikCommand2(`/user-manager user remove [find name="${a.name}"]`, ctx);
@@ -53140,7 +54930,7 @@ ${redactSecrets(details)}`;
53140
54930
  const cmd = new Cmd("/user-manager profile add").set("name", a.name).opt("name-for-users", a.name_for_users).opt("validity", a.validity).opt("price", a.price).opt("starts-when", a.starts_when).opt("override-shared-users", a.override_shared_users).opt("comment", a.comment).build();
53141
54931
  const result = await executeMikrotikCommand2(cmd, ctx);
53142
54932
  if (commandUnsupported(result))
53143
- return NOT_AVAILABLE3;
54933
+ return NOT_AVAILABLE2;
53144
54934
  if (looksLikeError(result))
53145
54935
  return `Failed to add User Manager profile: ${result}`;
53146
54936
  const details = await executeMikrotikCommand2(`/user-manager profile print detail where name="${a.name}"`, ctx);
@@ -53164,7 +54954,7 @@ ${details}` : "User Manager profile creation completed but unable to verify.";
53164
54954
  filters.push(`name~"${a.name_filter}"`);
53165
54955
  const result = await executeMikrotikCommand2(`/user-manager profile print${whereClause(filters)}`, ctx);
53166
54956
  if (commandUnsupported(result))
53167
- return NOT_AVAILABLE3;
54957
+ return NOT_AVAILABLE2;
53168
54958
  return isEmpty(result) ? "No User Manager profiles found matching the criteria." : `USER MANAGER PROFILES:
53169
54959
 
53170
54960
  ${result}`;
@@ -53180,7 +54970,7 @@ ${result}`;
53180
54970
  ctx.info(`Removing User Manager profile: name=${a.name}`);
53181
54971
  const count = await executeMikrotikCommand2(`/user-manager profile print count-only where name="${a.name}"`, ctx);
53182
54972
  if (commandUnsupported(count))
53183
- return NOT_AVAILABLE3;
54973
+ return NOT_AVAILABLE2;
53184
54974
  if (count.trim() === "0")
53185
54975
  return `User Manager profile '${a.name}' not found.`;
53186
54976
  const result = await executeMikrotikCommand2(`/user-manager profile remove [find name="${a.name}"]`, ctx);
@@ -53203,7 +54993,7 @@ ${result}`;
53203
54993
  const cmd = new Cmd("/user-manager user-profile add").set("user", a.user).set("profile", a.profile).build();
53204
54994
  const result = await executeMikrotikCommand2(cmd, ctx);
53205
54995
  if (commandUnsupported(result))
53206
- return NOT_AVAILABLE3;
54996
+ return NOT_AVAILABLE2;
53207
54997
  if (looksLikeError(result))
53208
54998
  return `Failed to assign profile: ${result}`;
53209
54999
  return `Assigned profile '${a.profile}' to user '${a.user}'.
@@ -53226,7 +55016,7 @@ ${result}`;
53226
55016
  filters.push(`user~"${a.user_filter}"`);
53227
55017
  const result = await executeMikrotikCommand2(`/user-manager user-profile print${whereClause(filters)}`, ctx);
53228
55018
  if (commandUnsupported(result))
53229
- return NOT_AVAILABLE3;
55019
+ return NOT_AVAILABLE2;
53230
55020
  return isEmpty(result) ? "No User Manager user-profiles found matching the criteria." : `USER MANAGER USER-PROFILES:
53231
55021
 
53232
55022
  ${result}`;
@@ -53251,7 +55041,7 @@ ${result}`;
53251
55041
  const cmd = new Cmd("/user-manager router add").set("name", a.name).set("address", a.address).set("shared-secret", a.shared_secret).opt("coa-port", a.coa_port).opt("protocol", a.protocol).opt("comment", a.comment).flag("disabled", a.disabled).build();
53252
55042
  const result = await executeMikrotikCommand2(cmd, ctx);
53253
55043
  if (commandUnsupported(result))
53254
- return NOT_AVAILABLE3;
55044
+ return NOT_AVAILABLE2;
53255
55045
  if (looksLikeError(result))
53256
55046
  return `Failed to add User Manager router: ${result}`;
53257
55047
  const details = await executeMikrotikCommand2(`/user-manager router print detail where name="${a.name}"`, ctx);
@@ -53275,7 +55065,7 @@ ${redactSecrets(details)}` : "User Manager router creation completed but unable
53275
55065
  filters.push(`name~"${a.name_filter}"`);
53276
55066
  const result = await executeMikrotikCommand2(`/user-manager router print${whereClause(filters)}`, ctx);
53277
55067
  if (commandUnsupported(result))
53278
- return NOT_AVAILABLE3;
55068
+ return NOT_AVAILABLE2;
53279
55069
  return isEmpty(result) ? "No User Manager routers found matching the criteria." : `USER MANAGER ROUTERS:
53280
55070
 
53281
55071
  ${redactSecrets(result)}`;
@@ -53291,7 +55081,7 @@ ${redactSecrets(result)}`;
53291
55081
  ctx.info(`Removing User Manager router: name=${a.name}`);
53292
55082
  const count = await executeMikrotikCommand2(`/user-manager router print count-only where name="${a.name}"`, ctx);
53293
55083
  if (commandUnsupported(count))
53294
- return NOT_AVAILABLE3;
55084
+ return NOT_AVAILABLE2;
53295
55085
  if (count.trim() === "0")
53296
55086
  return `User Manager router '${a.name}' not found.`;
53297
55087
  const result = await executeMikrotikCommand2(`/user-manager router remove [find name="${a.name}"]`, ctx);
@@ -53331,7 +55121,7 @@ ${redactSecrets(result)}`;
53331
55121
  const cmd = new Cmd("/user-manager limitation add").set("name", a.name).opt("rate-limit-rx", a.rate_limit_rx).opt("rate-limit-tx", a.rate_limit_tx).opt("rate-limit-min-rx", a.rate_limit_min_rx).opt("rate-limit-min-tx", a.rate_limit_min_tx).opt("rate-limit-burst-rx", a.rate_limit_burst_rx).opt("rate-limit-burst-tx", a.rate_limit_burst_tx).opt("rate-limit-burst-threshold-rx", a.rate_limit_burst_threshold_rx).opt("rate-limit-burst-threshold-tx", a.rate_limit_burst_threshold_tx).opt("rate-limit-burst-time-rx", a.rate_limit_burst_time_rx).opt("rate-limit-burst-time-tx", a.rate_limit_burst_time_tx).opt("rate-limit-priority", a.rate_limit_priority).opt("download-limit", a.download_limit).opt("upload-limit", a.upload_limit).opt("transfer-limit", a.transfer_limit).opt("uptime-limit", a.uptime_limit).opt("reset-counters-interval", a.reset_counters_interval).opt("reset-counters-start-time", a.reset_counters_start_time).opt("comment", a.comment).build();
53332
55122
  const result = await executeMikrotikCommand2(cmd, ctx);
53333
55123
  if (commandUnsupported(result))
53334
- return NOT_AVAILABLE3;
55124
+ return NOT_AVAILABLE2;
53335
55125
  if (looksLikeError(result))
53336
55126
  return `Failed to add User Manager limitation: ${result}`;
53337
55127
  const details = await executeMikrotikCommand2(`/user-manager limitation print detail where name="${a.name}"`, ctx);
@@ -53355,7 +55145,7 @@ ${details}` : "User Manager limitation creation completed but unable to verify."
53355
55145
  filters.push(`name~"${a.name_filter}"`);
53356
55146
  const result = await executeMikrotikCommand2(`/user-manager limitation print${whereClause(filters)}`, ctx);
53357
55147
  if (commandUnsupported(result))
53358
- return NOT_AVAILABLE3;
55148
+ return NOT_AVAILABLE2;
53359
55149
  return isEmpty(result) ? "No User Manager limitations found matching the criteria." : `USER MANAGER LIMITATIONS:
53360
55150
 
53361
55151
  ${result}`;
@@ -53371,7 +55161,7 @@ ${result}`;
53371
55161
  ctx.info(`Removing User Manager limitation: name=${a.name}`);
53372
55162
  const count = await executeMikrotikCommand2(`/user-manager limitation print count-only where name="${a.name}"`, ctx);
53373
55163
  if (commandUnsupported(count))
53374
- return NOT_AVAILABLE3;
55164
+ return NOT_AVAILABLE2;
53375
55165
  if (count.trim() === "0")
53376
55166
  return `User Manager limitation '${a.name}' not found.`;
53377
55167
  const result = await executeMikrotikCommand2(`/user-manager limitation remove [find name="${a.name}"]`, ctx);
@@ -53398,7 +55188,7 @@ ${result}`;
53398
55188
  filters.push("active=yes");
53399
55189
  const result = await executeMikrotikCommand2(`/user-manager session print${whereClause(filters)}`, ctx);
53400
55190
  if (commandUnsupported(result))
53401
- return NOT_AVAILABLE3;
55191
+ return NOT_AVAILABLE2;
53402
55192
  return isEmpty(result) ? "No User Manager sessions found matching the criteria." : `USER MANAGER SESSIONS:
53403
55193
 
53404
55194
  ${result}`;
@@ -53832,33 +55622,281 @@ ${result}`;
53832
55622
  })
53833
55623
  ];
53834
55624
 
55625
+ // src/core/vlan-guidance.ts
55626
+ var VLAN_GUIDE_URI = "mikrotik://knowledge/vlan-segmentation";
55627
+ var VLAN_GUIDE_VERSION = "2026-10-03";
55628
+ var VLAN_GUIDE_TOPICS = [
55629
+ "overview",
55630
+ "discovery",
55631
+ "layer2",
55632
+ "policy",
55633
+ "migration",
55634
+ "verification"
55635
+ ];
55636
+ var sections2 = {
55637
+ overview: `## Intent and boundaries
55638
+ Use this guide for homelab VLAN segmentation, guest Wi-Fi, IoT isolation and
55639
+ management networks. It is reference knowledge, NOT observed device state or
55640
+ authorization. Start read-only; use find_tools and describe_tool for the tools
55641
+ actually exposed in this session. Never bypass read-only mode or module restrictions.
55642
+
55643
+ Adapt the homelab-vlan-segmentation design to the actual requirements. Illustrative
55644
+ roles/IDs are Trusted 10, IoT 20, Servers 30 (only if needed), Guest 40 and Management
55645
+ 99. IDs are examples, not reservations or defaults to apply. Preserve working
55646
+ subnets where possible; check overlap with WAN, VPN, remote sites and other VLANs.
55647
+ Trusted users are not automatically administrators. Agree a source/destination/
55648
+ service allow matrix, including router management, before proposing changes.
55649
+
55650
+ VLAN sub-interfaces alone do not provide isolation. Layer-2 membership, routed
55651
+ IPv4/IPv6 policy and actual endpoint tests are separate requirements. A VPS/CHR
55652
+ used only as a routed tunnel endpoint may need routes/policy, not local VLANs.
55653
+ Do not extend a broadcast domain across a WAN without an explicit L2 requirement.
55654
+ Segmentation is not a promise of lower latency or higher tunnel throughput.`,
55655
+ discovery: `## Read-only discovery and evidence
55656
+ Resolve each router by its exact configured device name and verify identity,
55657
+ RouterOS version, board, switch chip and installed Wi-Fi package. Recall constraints
55658
+ separately for each device if Memory is enabled; inspect conflicts and omitted
55659
+ constraints. Recalled facts may be stale. Never copy one router's addresses to another.
55660
+
55661
+ Discover interfaces, bridge settings/ports/VLAN table, VLAN sub-interfaces, interface
55662
+ lists, IP addresses, DHCP pools/networks/leases, DNS, IPv6 addresses/prefix delegation,
55663
+ ND/RA, IPv4 AND IPv6 filter/raw/NAT/mangle rules, routes/routing tables/rules,
55664
+ WireGuard allowed-addresses, queues, Wi-Fi/CAPsMAN/SSID datapaths and management
55665
+ services/MAC discovery. Use bounded, filtered reads; report unsupported, incomplete
55666
+ or timed-out reads as unknown, never empty or safe. Do not fetch credentials.
55667
+
55668
+ Build a physical port map: peer device, WAN/LAN/trunk/access role, bridge, PVID,
55669
+ tagged/untagged membership, link rate, hardware offload and management dependency.
55670
+ Do not infer a port's role from ether1, a comment, or a link-down snapshot. Resolve
55671
+ conflicting labels with the operator. Verify external switch/AP VLAN capability
55672
+ and its management/native VLAN before planning a trunk. Inventory scripts, netwatch,
55673
+ interface lists, NAT, policy-routing and queues that depend on the old interfaces.
55674
+ Distinguish proven observations, intended policy and unverified assumptions.`,
55675
+ layer2: `## Layer 2, CPU access and Wi-Fi
55676
+ For a NEW bridge, stage with vlan-filtering=no. For an existing production bridge,
55677
+ do not turn filtering off to simplify a migration: that can remove isolation.
55678
+ Enable VLAN filtering LAST when the VLAN table, port admission, management path,
55679
+ gateway and recovery plan are ready. A bridge reset can interrupt the session.
55680
+
55681
+ A routed VLAN interface normally belongs on the bridge, not on a physical port
55682
+ already enslaved to it. Include the bridge/CPU as tagged for VLANs terminated on
55683
+ that bridge and verify effective current-tagged membership (RouterOS may create
55684
+ dynamic entries). Do not expose CPU membership on VLANs that need only switching.
55685
+ Creating /interface vlan does not configure /interface bridge vlan or access ports.
55686
+
55687
+ On access ports: one intended untagged VLAN, matching PVID, ingress-filtering and
55688
+ admit-only-untagged-and-priority-tagged where supported. PVID classifies untagged
55689
+ ingress; it is not a tagged-traffic allowlist. Do not combine multiple VLAN IDs in
55690
+ a VLAN-table row containing access ports. On tagged-only trunks: explicit allowed
55691
+ VLAN membership, ingress-filtering and admit-only-vlan-tagged. Model hybrid/native
55692
+ ports explicitly; inspect dynamic VLAN 1/CPU membership for accidental access.
55693
+ Never add a WAN/ONT port to a LAN bridge merely because an example uses that number.
55694
+
55695
+ Map each SSID to a verified VLAN at the AP as well as its uplink. Inspect wireless,
55696
+ wifiwave2 or wifi and CAPsMAN local/manager forwarding. wifi-qcom and wifi-qcom-ac
55697
+ are not interchangeable: qcom-ac needs the appropriate bridge/PVID design rather
55698
+ than blindly copying CAPsMAN datapath vlan-id. Verify package-specific support.
55699
+ Guest client isolation within one SSID/VLAN is separate from inter-VLAN firewalling.
55700
+ Do not enable bridge use-ip-firewall just to filter traffic already routed by the
55701
+ CPU; inspect hardware-offload support and measure the performance impact.`,
55702
+ policy: `## Dual-stack policy and remote-site dependencies
55703
+ Design INPUT (to the router) and FORWARD (through the router) separately for both
55704
+ IPv4 and IPv6. Limit administration to the approved management sources/VPNs; allow
55705
+ only required DHCP/DNS/NTP and essential ICMP/ICMPv6 functions on client segments.
55706
+ Preserve neighbor discovery, router advertisements where intended and path-MTU
55707
+ discovery. Do not solve isolation by indiscriminately blocking all ICMPv6.
55708
+
55709
+ Evaluate first-match rule order, jumps, broad LAN/!WAN accepts, established flows,
55710
+ FastTrack and existing final drops. Place exact service exceptions before segment
55711
+ denies, and denies before broad accepts they must constrain. Appended drop rules
55712
+ may never match. Use current stable .ids, not saved row numbers. Preserve unrelated
55713
+ protections and allowlists. RFC1918-only drops miss local public IPv4, VPN/remote
55714
+ networks and all IPv6; enumerate actual protected destinations. Default-deny between
55715
+ zones with explicit exceptions is a design goal, not permission to rewrite a firewall.
55716
+
55717
+ NAT is not isolation or a routing policy. Reuse valid existing NAT; any new source
55718
+ NAT must be scoped to the intended egress, never every destination. SNAT may hide
55719
+ VLAN source identities from a remote router, so enforce segmentation locally unless
55720
+ an explicitly designed routed/no-NAT topology preserves them. Add new subnets to
55721
+ VPN allowed-addresses, return routes and remote policies only when required.
55722
+
55723
+ Each IPv6 SLAAC segment needs its own non-overlapping /64 from a valid routed or
55724
+ delegated prefix; do not reuse one /64 on separate L2 domains. Verify upstream
55725
+ reachability and return routing, not just a local address. If unavailable, report
55726
+ IPv6 as unconfigured/blocked by prerequisites, not working or isolated by IPv4.
55727
+
55728
+ Move policy-routing/interface-list/queue/automation dependencies before retiring
55729
+ legacy interfaces. FastTrack only eligible main-table traffic; policy-routed,
55730
+ queued or accounted traffic needs appropriate exclusions. Moving FastTrack above
55731
+ an established accept can change behavior beyond VLANs; never do it blindly.`,
55732
+ migration: `## Safe rollout and planner limits
55733
+ Deliver: (1) observed topology and unknowns; (2) proposed VLAN/subnet/IPv6/SSID/port
55734
+ map; (3) explicit allow/deny service matrix; (4) exact ordered per-device changes;
55735
+ (5) prerequisites, rollback triggers and acceptance tests. Ask only for missing
55736
+ choices that affect connectivity or policy. Do not invent interface or subnet roles.
55737
+
55738
+ Before writes, obtain approval for the exact scope, capture a host-side snapshot
55739
+ and follow the local-backup requirements. Confirm an independent console, rescue
55740
+ port or verified management path that does not depend on the bridge being changed.
55741
+ Do not assume a VPN is independent: it may traverse that same bridge/uplink.
55742
+ Use owned Safe Mode for suitable single-router changes; coordinated multi-router
55743
+ writes should use the transaction workflow when available and suitable. Transaction
55744
+ verification stages REAL changes, not an offline preview. Safe Mode is not a backup
55745
+ or a guarantee for all operations; ambiguous timeouts are not permission to retry.
55746
+ Preserve the old management path until the new one has been tested. Canary one
55747
+ port/SSID/client, then migrate the remainder; never reconfigure all access at once.
55748
+
55749
+ design_network_segment is only partial IPv4 scaffolding, not a full isolation
55750
+ engine. It does not configure bridge port PVID/admission, enable VLAN filtering,
55751
+ map SSIDs, build router INPUT or IPv6 policy, prove rule reachability, preserve
55752
+ remote routing, or roll back a partial apply. NAT needs explicit wan_interface;
55753
+ isolation drops need a current reviewed isolation_before rule .id. Non-/24 DHCP
55754
+ needs an explicit valid pool. Discover schemas before previewing; apply only after
55755
+ the surrounding approved configuration satisfies these prerequisites. Do not call
55756
+ it repeatedly to finish a partially applied plan; read back and reconcile first.
55757
+ For a complete migration, prefer an explicit reviewed plan with separate steps.`,
55758
+ verification: `## Verification, reporting and clean memory
55759
+ Read back bridge VLAN current-tagged/current-untagged, PVID/admission, gateway IPs,
55760
+ DHCP and IPv6 ND/RA, rules and counters, routing tables and VPN return routes.
55761
+ Then test from real representative wired AND wireless clients in each segment:
55762
+ address/lease, DNS, gateway, required internet/VPN services, allowed local services,
55763
+ denied cross-zone services, denied router management and guest peer isolation if
55764
+ requested. Test IPv4 and IPv6 independently, with fresh connections; existing
55765
+ tracked/FastTracked flows can conceal new policy. Never flush all connections as
55766
+ an unapproved test. Router-originated ping does not prove client FORWARD policy.
55767
+
55768
+ Record expected vs observed per test, sample time, source, address family and
55769
+ remaining unknowns. If no endpoint is available, mark client isolation unverified.
55770
+ For performance claims, compare the same path/client/workload before and after:
55771
+ link speed, CPU/offload, throughput, latency and loss. Ask before disruptive loads.
55772
+ Commit only an authorized, verified change; uncertain connectivity requires stop,
55773
+ read-back and the agreed rollback/recovery path, not speculative cleanup.
55774
+
55775
+ Only after successful validation, review stale objects and all references before
55776
+ proposing removals. Disabled is not proof unused. Preserve unrelated tunnels,
55777
+ WAN failover, management allowlists and domain-routing exceptions.
55778
+ Memory: store exact VLAN maps, addresses and evidence on each Device with source,
55779
+ verification time and expiry. Use a dedicated Group policy with explicit members
55780
+ for site-wide rules; Shared is only for intentionally reusable safeguards. Do not
55781
+ promote a device entity or store secrets/raw exports. Memory never grants new
55782
+ permission; generic guidance does not prove live facts.`
55783
+ };
55784
+ var sources2 = `## Authoritative references
55785
+ - Bridge VLAN table: https://help.mikrotik.com/docs/spaces/ROS/pages/28606465/Bridge+VLAN+Table
55786
+ - Wi-Fi packages and CAPsMAN: https://help.mikrotik.com/docs/spaces/ROS/pages/224559120/WiFi
55787
+ - IPv4/IPv6 firewall: https://help.mikrotik.com/docs/spaces/ROS/pages/328513/Building+Advanced+Firewall
55788
+ - Packet flow and FastTrack: https://help.mikrotik.com/docs/spaces/ROS/pages/328227/Packet+Flow+in+RouterOS
55789
+ Verify version-specific behavior against the current official manual before applying.
55790
+ Adapted from the homelab-vlan-segmentation skill with RouterOS-specific safety gates.`;
55791
+ function getVlanSegmentationGuide(topic = "all") {
55792
+ const selected = topic === "all" ? VLAN_GUIDE_TOPICS : [topic];
55793
+ return [
55794
+ `# RouterOS VLAN segmentation knowledge
55795
+ Guide version: ${VLAN_GUIDE_VERSION}
55796
+ Reference only; no device inspection or changes.`,
55797
+ ...selected.map((key) => sections2[key]),
55798
+ sources2
55799
+ ].join(`
55800
+
55801
+ `);
55802
+ }
55803
+ var VLAN_INSTRUCTIONS = `VLAN segmentation knowledge:
55804
+ Before VLAN/guest/IoT/management-network work, read ${VLAN_GUIDE_URI}.
55805
+ Begin with read-only discovery; never infer port roles from names or example IDs.
55806
+ Protect the management path, stage VLAN membership/PVID/CPU access before enabling
55807
+ filtering, and check BOTH IPv4 and IPv6 INPUT/FORWARD policy and remote return routes.
55808
+ design_network_segment is partial IPv4 scaffolding, NOT a complete isolation plan.
55809
+ Use only available tools; an audit or this guide never authorizes router changes.
55810
+ Verified device facts belong to Device memory; reusable safeguards may be Shared
55811
+ only with explicit intent. Do not treat shared memory as a live VLAN map.`;
55812
+ function vlanPromptGuidance(name, body) {
55813
+ if (!["setup-vlan-network", "setup-guest-wifi", "audit-vlan-segmentation"].includes(name)) {
55814
+ return body;
55815
+ }
55816
+ return `${body}
55817
+
55818
+ ${getVlanSegmentationGuide()}`;
55819
+ }
55820
+
53835
55821
  // src/tools/vlan-designer.ts
55822
+ var COVERAGE = "PARTIAL IPv4 scaffold only: no bridge port PVID/admission, VLAN filtering activation, SSID mapping, " + "router INPUT policy, IPv6 policy, remote return routes or automatic rollback. " + "Review existing rules, DNS, overlaps, interface roles and management recovery before apply. " + "Command completion does NOT prove isolation or internet access; verify from real clients. " + "Read get_vlan_segmentation_guide for the full workflow.";
55823
+ var portList = (text) => [
55824
+ ...new Set((text ?? "").split(",").map((p) => p.trim()).filter(Boolean))
55825
+ ];
53836
55826
  function defaultRange2(subnet) {
53837
55827
  const o = subnet.split("/")[0].split(".");
53838
55828
  return `${o[0]}.${o[1]}.${o[2]}.10-${o[0]}.${o[1]}.${o[2]}.254`;
53839
55829
  }
53840
55830
  var vlanDesignerTools = [
55831
+ defineTool2({
55832
+ name: "get_vlan_segmentation_guide",
55833
+ title: "Read VLAN Segmentation Knowledge",
55834
+ annotations: READ,
55835
+ noDevice: true,
55836
+ description: "Read the RouterOS homelab VLAN design guide before VLAN, guest Wi-Fi, IoT or management-network work. " + "Covers bridge CPU/tagged/untagged/PVID, dual-stack IPv4/IPv6 isolation, SSIDs/CAPsMAN, VPN return routing, " + "Safe Mode/rollback, validation and clean Device/Group/Shared memory. Reference only; no router contact, " + "live audit, memory write or authorization. Select a topic for concise guidance, or all for the full checklist.",
55837
+ inputSchema: {
55838
+ topic: _enum(["all", ...VLAN_GUIDE_TOPICS]).default("all")
55839
+ },
55840
+ handler: (a) => getVlanSegmentationGuide(a.topic)
55841
+ }),
53841
55842
  defineTool2({
53842
55843
  name: "design_network_segment",
53843
- title: "Design Isolated VLAN Segment",
55844
+ title: "Preview or Build Partial IPv4 VLAN Scaffolding",
53844
55845
  annotations: DANGEROUS,
53845
- description: "Stands up a complete isolated network segment in one call: a VLAN interface on the bridge, its " + "gateway IP, a DHCP server + pool + network, optional internet access (srcnat masquerade), and " + "inter-VLAN isolation firewall rules \u2014 e.g. 'a guest VLAN that reaches the internet but not the " + "LAN'. DEFAULTS TO A DRY RUN (`apply=false`) showing every command grouped; set `apply=true` to " + "build it. Bridge VLAN tagging is added when `tagged_ports`/`untagged_ports` are given (requires " + "bridge vlan-filtering). Isolation drops forward traffic from this subnet to each `isolate_from` " + "subnet. Returns the plan or a build report.",
55846
+ description: "Preview partial IPv4 VLAN interface/gateway/DHCP scaffolding (apply=false, no router I/O). " + "Read get_vlan_segmentation_guide first. Does NOT produce a complete isolated network. " + "Optional NAT requires explicit wan_interface; isolation drops require a reviewed isolation_before .id. " + "Bridge membership includes the CPU when ports are supplied, but port PVID/admission, filtering, Wi-Fi, " + "INPUT and IPv6 policies remain separate work. apply=true runs sequential non-idempotent writes only " + "after explicit approval, backup and a protected management/Safe Mode plan; failures may leave partial state. " + "Read back and test clients; never retry blindly or claim isolation from command success.",
53846
55847
  inputSchema: {
53847
55848
  vlan_id: number().int().min(1).max(4094),
53848
55849
  name: interfaceName("Name for the VLAN interface, e.g. 'guest'"),
53849
- subnet: string().describe("CIDR for the segment, e.g. '192.168.30.0/24'"),
53850
- gateway: string().describe("Router's address in the segment, e.g. '192.168.30.1'"),
55850
+ subnet: cidrv42().describe("Canonical IPv4 network CIDR, e.g. '192.168.30.0/24'"),
55851
+ gateway: ipv42().describe("Usable router address inside the subnet, excluded from the DHCP pool"),
53851
55852
  bridge: string().default("bridge").describe("Bridge to put the VLAN on"),
53852
- tagged_ports: string().optional().describe("Comma-separated trunk/tagged ports (+ the bridge)"),
55853
+ tagged_ports: string().optional().describe("Comma-separated verified tagged ports; the bridge/CPU is included once automatically"),
53853
55854
  untagged_ports: string().optional().describe("Comma-separated access/untagged ports"),
53854
55855
  dhcp: boolean().default(true).describe("Create a DHCP server + pool for the segment"),
53855
- dhcp_range: string().optional().describe("Pool range; defaults to .10\u2013.254 of the subnet"),
53856
- internet: boolean().default(true).describe("Allow internet access via srcnat masquerade"),
53857
- isolate_from: array(string()).optional().describe("Subnets this segment must NOT reach, e.g. ['192.168.1.0/24']"),
55856
+ dhcp_range: string().optional().describe("Single start-end IPv4 range excluding gateway/network/broadcast. Required outside /24; /24 defaults to .10\u2013.254"),
55857
+ internet: boolean().default(true).describe("Add egress-scoped IPv4 masquerade (requires wan_interface); not a firewall allow. Set false to reuse existing NAT"),
55858
+ wan_interface: string().trim().min(1).refine((value) => !value.startsWith("!"), "Choose one positive egress interface, not a negated matcher").optional().describe("Verified egress interface for new masquerade. Required when internet=true; never inferred"),
55859
+ isolate_from: array(cidrv42()).optional().describe("Subnets this segment must NOT reach, e.g. ['192.168.1.0/24']"),
55860
+ isolation_before: string().regex(/^\*[0-9a-f]+$/i).optional().describe("Current enabled forward rule .id from a fresh read; insert drops before this reviewed rule, not after broad accepts. Required with isolate_from"),
53858
55861
  apply: boolean().default(false).describe("false = preview (default); true = build")
53859
55862
  },
53860
55863
  async handler(a, ctx) {
53861
- const prefix = a.subnet.split("/")[1] ?? "24";
55864
+ const subnet = parseCidr(a.subnet);
55865
+ const gateway = parseIp(a.gateway);
55866
+ if (!subnet || subnet.text !== a.subnet || subnet.prefix > 30 || gateway === null) {
55867
+ return "Error: use a canonical IPv4 network CIDR (/0\u2013/30) and valid gateway.";
55868
+ }
55869
+ const broadcast = subnet.network + 2 ** (32 - subnet.prefix) - 1;
55870
+ if (gateway <= subnet.network || gateway >= broadcast) {
55871
+ return "Error: gateway must be a usable host inside the segment subnet.";
55872
+ }
55873
+ if (a.internet && !a.wan_interface) {
55874
+ return "Error: internet=true requires wan_interface; unscoped masquerade is not safe. Set internet=false to reuse existing NAT.";
55875
+ }
55876
+ const isolate = [...new Set(a.isolate_from ?? [])];
55877
+ if (isolate.length && !a.isolation_before) {
55878
+ return "Error: isolate_from requires a reviewed isolation_before rule .id; blindly appending drops may not isolate anything.";
55879
+ }
55880
+ const tagged = portList(a.tagged_ports);
55881
+ const untagged = portList(a.untagged_ports);
55882
+ if (untagged.includes(a.bridge) || untagged.some((p) => tagged.includes(p))) {
55883
+ return "Error: this routed VLAN requires a tagged bridge/CPU and disjoint tagged/untagged ports.";
55884
+ }
55885
+ let range;
55886
+ if (a.dhcp) {
55887
+ if (!a.dhcp_range && subnet.prefix !== 24) {
55888
+ return "Error: non-/24 DHCP requires an explicit dhcp_range inside the subnet.";
55889
+ }
55890
+ const dhcpRange = a.dhcp_range ?? defaultRange2(a.subnet);
55891
+ range = dhcpRange;
55892
+ const parts = dhcpRange.split("-");
55893
+ const lo = parseIp(parts[0] ?? "");
55894
+ const hi = parseIp(parts[1] ?? "");
55895
+ if (parts.length !== 2 || lo === null || hi === null || lo > hi || lo <= subnet.network || hi >= broadcast || gateway >= lo && gateway <= hi) {
55896
+ return "Error: dhcp_range must be a single ordered start-end range inside the subnet, excluding network, broadcast and gateway.";
55897
+ }
55898
+ }
55899
+ const prefix = subnet.prefix;
53862
55900
  const vlanIf = a.name;
53863
55901
  const groups = [];
53864
55902
  groups.push({
@@ -53868,11 +55906,11 @@ var vlanDesignerTools = [
53868
55906
  new Cmd("/ip address add").set("address", `${a.gateway}/${prefix}`).set("interface", vlanIf).build()
53869
55907
  ]
53870
55908
  });
53871
- if (a.tagged_ports || a.untagged_ports) {
55909
+ if (tagged.length || untagged.length) {
53872
55910
  groups.push({
53873
55911
  label: "Bridge VLAN tagging",
53874
55912
  commands: [
53875
- new Cmd("/interface bridge vlan add").set("bridge", a.bridge).set("vlan-ids", a.vlan_id).opt("tagged", a.tagged_ports ? `${a.bridge},${a.tagged_ports}` : a.bridge).opt("untagged", a.untagged_ports).build()
55913
+ new Cmd("/interface bridge vlan add").set("bridge", a.bridge).set("vlan-ids", a.vlan_id).set("tagged", [...new Set([a.bridge, ...tagged])].join(",")).opt("untagged", untagged.length ? untagged.join(",") : undefined).build()
53876
55914
  ]
53877
55915
  });
53878
55916
  }
@@ -53881,7 +55919,7 @@ var vlanDesignerTools = [
53881
55919
  groups.push({
53882
55920
  label: "DHCP server",
53883
55921
  commands: [
53884
- new Cmd("/ip pool add").set("name", pool).set("ranges", a.dhcp_range ?? defaultRange2(a.subnet)).build(),
55922
+ new Cmd("/ip pool add").set("name", pool).set("ranges", range).build(),
53885
55923
  new Cmd("/ip dhcp-server add").set("name", `${a.name}-dhcp`).set("interface", vlanIf).set("address-pool", pool).set("disabled", "no").build(),
53886
55924
  new Cmd("/ip dhcp-server network add").set("address", a.subnet).set("gateway", a.gateway).set("dns-server", a.gateway).build()
53887
55925
  ]
@@ -53891,15 +55929,14 @@ var vlanDesignerTools = [
53891
55929
  groups.push({
53892
55930
  label: "Internet (srcnat masquerade)",
53893
55931
  commands: [
53894
- new Cmd("/ip firewall nat add").set("chain", "srcnat").set("src-address", a.subnet).set("action", "masquerade").set("comment", `vlan-${a.vlan_id} internet`).build()
55932
+ new Cmd("/ip firewall nat add").set("chain", "srcnat").set("src-address", a.subnet).set("out-interface", a.wan_interface).set("action", "masquerade").set("comment", `vlan-${a.vlan_id} internet`).build()
53895
55933
  ]
53896
55934
  });
53897
55935
  }
53898
- const isolate = a.isolate_from ?? [];
53899
55936
  if (isolate.length) {
53900
55937
  groups.push({
53901
55938
  label: "Inter-VLAN isolation",
53902
- commands: isolate.map((dst) => new Cmd("/ip firewall filter add").set("chain", "forward").set("src-address", a.subnet).set("dst-address", dst).set("action", "drop").set("comment", `vlan-${a.vlan_id} isolate from ${dst}`).build())
55939
+ commands: isolate.map((dst) => new Cmd("/ip firewall filter add").set("chain", "forward").set("src-address", a.subnet).set("dst-address", dst).set("action", "drop").set("place-before", a.isolation_before).set("comment", `vlan-${a.vlan_id} isolate from ${dst}`).build())
53903
55940
  });
53904
55941
  }
53905
55942
  const all = groups.flatMap((g) => g.commands);
@@ -53909,20 +55946,37 @@ ${g.commands.map((c) => ` ${c}`).join(`
53909
55946
  `)}`).join(`
53910
55947
 
53911
55948
  `);
53912
- return `DRY RUN \u2014 VLAN ${a.vlan_id} '${a.name}' (${a.subnet}); ${all.length} command(s) (set apply=true to build):
55949
+ return `DRY RUN \u2014 VLAN ${a.vlan_id} '${a.name}' (${a.subnet}); ${all.length} command(s):
53913
55950
 
53914
- ${preview}`;
55951
+ ${COVERAGE}
55952
+
55953
+ ${preview}
55954
+
55955
+ Apply only within the complete approved migration plan.`;
55956
+ }
55957
+ if (isolate.length) {
55958
+ const anchor = await executeMikrotikCommand2(new Cmd("/ip firewall filter print count-only where").set(".id", a.isolation_before).set("chain", "forward").set("disabled", "no").build(), ctx);
55959
+ if (anchor.trim() !== "1")
55960
+ return "Error: isolation_before is not a unique enabled forward rule. No changes applied; read rules again.";
53915
55961
  }
53916
55962
  const done = [];
53917
55963
  for (const cmd of all) {
53918
- const result = await executeMikrotikCommand2(cmd, ctx);
55964
+ let result;
55965
+ try {
55966
+ result = await executeMikrotikCommand2(cmd, ctx);
55967
+ } catch (error) {
55968
+ return `Error: VLAN apply stopped after ${done.length}/${all.length} acknowledged commands: ${String(error)}. The last command may already have applied. Read back partial state; do not retry blindly.
55969
+ ${COVERAGE}`;
55970
+ }
53919
55971
  if (looksLikeError(result)) {
53920
55972
  return `Built ${done.length}/${all.length} commands, then FAILED: ${result}
53921
- Review partial segment (the VLAN may exist without DHCP/firewall).`;
55973
+ Review partial segment (the VLAN may exist without DHCP/firewall). Do not retry blindly.
55974
+ ${COVERAGE}`;
53922
55975
  }
53923
55976
  done.push(cmd);
53924
55977
  }
53925
- return `VLAN segment '${a.name}' (id ${a.vlan_id}, ${a.subnet}) built \u2014 ${done.length} command(s)${isolate.length ? `, isolated from ${isolate.join(", ")}` : ""}.`;
55978
+ return `IPv4 scaffold '${a.name}' (id ${a.vlan_id}, ${a.subnet}): ${done.length} command(s) completed. Isolation and connectivity are UNVERIFIED.
55979
+ ${COVERAGE}`;
53926
55980
  }
53927
55981
  })
53928
55982
  ];
@@ -53935,7 +55989,7 @@ var vlanTools = [
53935
55989
  name: "create_vlan_interface",
53936
55990
  title: "Create VLAN Interface",
53937
55991
  annotations: WRITE,
53938
- description: "Creates an 802.1Q VLAN sub-interface (`/interface vlan`) on a specified parent physical or bridge interface." + " Use this to segment layer-2 traffic by VLAN ID (1\u20134094); set `use_service_tag=true` for 802.1ad QinQ double-tagging." + " For listing existing VLAN interfaces use `list_vlan_interfaces`; for editing an existing VLAN use `update_vlan_interface`." + " Returns the created interface's full detail including its name, which is the identifier accepted by `get_vlan_interface`, `update_vlan_interface`, and `remove_vlan_interface`." + " ARP mode accepts: enabled (default), disabled, proxy-arp, reply-only.",
55992
+ description: "Creates an 802.1Q VLAN sub-interface (`/interface vlan`) on a specified parent physical or bridge interface." + " This creates only a VLAN sub-interface, NOT bridge port membership, PVID, firewall isolation or SSID mapping. For a bridge member use the bridge as routed parent; read get_vlan_segmentation_guide before migration. Set `use_service_tag=true` for 802.1ad QinQ double-tagging." + " For listing existing VLAN interfaces use `list_vlan_interfaces`; for editing an existing VLAN use `update_vlan_interface`." + " Returns the created interface's full detail including its name, which is the identifier accepted by `get_vlan_interface`, `update_vlan_interface`, and `remove_vlan_interface`." + " ARP mode accepts: enabled (default), disabled, proxy-arp, reply-only.",
53939
55993
  inputSchema: {
53940
55994
  name: interfaceName("Name for the new VLAN interface, e.g. 'vlan100'"),
53941
55995
  vlan_id: number().int().min(1).max(4094).describe("802.1Q VLAN ID (1-4094)"),
@@ -56463,6 +58517,27 @@ var moduleCatalog2 = [
56463
58517
  description: "Administrator-approved DNS/TCP/TLS/HTTPS service checks, immutable contracts, history and fail-closed rollout gates with explicit MCP-host perspective.",
56464
58518
  tools: serviceContractTools
56465
58519
  },
58520
+ {
58521
+ label: "Service Routing",
58522
+ slug: "service-routing",
58523
+ group: "System & Ops",
58524
+ description: "Scoped dual-stack domain policies, router VRF service probes and explicitly authorized failover.",
58525
+ tools: serviceRoutingTools
58526
+ },
58527
+ {
58528
+ label: "Network Flight Recorder",
58529
+ slug: "flight-recorder",
58530
+ group: "System & Ops",
58531
+ description: "Durable bounded pre/post-incident telemetry, off-router log metadata and MCP change correlation.",
58532
+ tools: flightRecorderTools
58533
+ },
58534
+ {
58535
+ label: "Recovery Lab",
58536
+ slug: "recovery-lab",
58537
+ group: "System & Ops",
58538
+ description: "Isolated CHR rehearsal orchestration with immutable snapshot subsets, coverage and verified runner evidence.",
58539
+ tools: recoveryLabTools
58540
+ },
56466
58541
  {
56467
58542
  label: "Client Investigations",
56468
58543
  slug: "investigations",
@@ -56491,6 +58566,13 @@ var moduleCatalog2 = [
56491
58566
  description: "Server self-awareness: running version, update availability, release notes, " + "upgrade path, and server vitals. No RouterOS device is contacted.",
56492
58567
  tools: serverPulseTools
56493
58568
  },
58569
+ {
58570
+ label: "MCP Settings",
58571
+ slug: "mcp-settings",
58572
+ group: "Discovery & Meta",
58573
+ description: "Read, validate, preview and safely update MCP host settings with local backups, " + "revision checks and timed rollback. Never changes routers, credentials or access ceilings.",
58574
+ tools: mcpSettingsTools
58575
+ },
56494
58576
  {
56495
58577
  label: "Device Capabilities",
56496
58578
  slug: "device-capabilities",
@@ -56530,7 +58612,7 @@ var moduleCatalog2 = [
56530
58612
  label: "VLAN Designer",
56531
58613
  slug: "vlan-designer",
56532
58614
  group: "Interfaces",
56533
- description: "Stand up a complete isolated VLAN segment (interface, gateway, DHCP, internet, inter-VLAN " + "isolation) from one intent, with preview-before-apply.",
58615
+ description: "Read VLAN design/safety knowledge and preview partial IPv4 scaffolding; full L2, dual-stack " + "isolation and client verification remain explicit migration work.",
56534
58616
  tools: vlanDesignerTools
56535
58617
  },
56536
58618
  {
@@ -57391,7 +59473,7 @@ var moduleCatalog2 = [
57391
59473
  label: "Containers",
57392
59474
  slug: "container",
57393
59475
  group: "System & Ops",
57394
- description: "OCI container subsystem (`/container`): lifecycle (add/start/stop/remove/set), global config " + "(registry/tmpdir/RAM), named env lists, and volume mounts.",
59476
+ description: "Shared container safety knowledge and exact-target OCI lifecycle (`/container`), global config " + "(registry/tmpdir/RAM), named env lists, and volume mounts.",
57395
59477
  tools: containerTools
57396
59478
  },
57397
59479
  {
@@ -57473,4 +59555,4 @@ function selectToolModules2(filter = {}, catalog = moduleCatalog2) {
57473
59555
  }).map((m) => m.tools);
57474
59556
  }
57475
59557
 
57476
- export { __toESM, __commonJS, clone, normalizeParams, own, installLazyProp, $constructor, parse, parseAsync, safeParse, safeParseAsync, $ZodType, $ZodObject, toJSONSchema, string, number, boolean, _null, unknown, array, object, looseObject, union, discriminatedUnion, intersection, record, _enum, literal, ZodOptional, optional, custom, preprocess, datetime, DEFAULT_DASHBOARD_DB2, DEFAULT_SNAPSHOT_DB2, DEFAULT_BACKUP_DIR2, DeviceConfigSchema2, MikrotikConfigSchema2, loadConfig2, logger, MikroTikSSHClient2, setConfig2, getConfig2, listDevices2, deviceLabels, resolveDeviceName2, deviceDirectory, getDevice2, SafeModeManager2, getSafeModeManager2, executeMikrotikCommand2, defineTool2, registerTools2, PROMPTS_DIR, registerUiResources, VERSION2, WEBSITE_URL, LOGO_URL, SERVER_TITLE, SERVER_DESCRIPTION, SERVER_NAME2, loadFileCacheSync, updateSummaryLine, parseExportMeta2, normalizeExport2, contentSha2, countLines2, openSnapshotStore2, moduleCatalog2, allToolModules2, selectToolModules2 };
59558
+ export { __toESM, __commonJS, clone, normalizeParams, own, installLazyProp, $constructor, parse, parseAsync, safeParse, safeParseAsync, $ZodType, $ZodObject, toJSONSchema, string, number, boolean, _null, unknown, array, object, looseObject, union, discriminatedUnion, intersection, record, _enum, literal, ZodOptional, optional, custom, preprocess, datetime, DEFAULT_DASHBOARD_DB2, DEFAULT_SNAPSHOT_DB2, DEFAULT_BACKUP_DIR2, McpServerSettingsSchema2, DeviceConfigSchema2, DashboardConfigSchema2, MemoryConfigSchema2, SSHConfigSchema2, MikrotikConfigSchema2, getConfigSource2, loadConfig2, logger, MikroTikSSHClient2, setConfig2, getConfig2, listDevices2, deviceLabels, resolveDeviceName2, deviceDirectory, getDevice2, SafeModeManager2, getSafeModeManager2, executeMikrotikCommand2, defineTool2, registerTools2, PROMPTS_DIR, registerUiResources, VLAN_GUIDE_URI, getVlanSegmentationGuide, VLAN_INSTRUCTIONS, vlanPromptGuidance, CONTAINER_GUIDE_URI, getRouterosContainerGuide, CONTAINER_INSTRUCTIONS, containerPromptGuidance, VERSION2, WEBSITE_URL, LOGO_URL, SERVER_TITLE, SERVER_DESCRIPTION, SERVER_NAME2, loadFileCacheSync, updateSummaryLine, parseExportMeta2, normalizeExport2, contentSha2, countLines2, openSnapshotStore2, moduleCatalog2, allToolModules2, selectToolModules2 };