@usex/mikrotik-mcp 6.2.0 → 6.3.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.
@@ -11815,12 +11815,25 @@ class SafeModeManager2 {
11815
11815
  uncertain = false;
11816
11816
  probeSequence = 0;
11817
11817
  queue = Promise.resolve();
11818
+ commandTimeoutMs = HARD_CAP_MS;
11819
+ idleTimeoutMs = IDLE_TIMEOUT_MS;
11820
+ setTimeouts(commandTimeoutMs, idleTimeoutMs) {
11821
+ if (!Number.isInteger(commandTimeoutMs) || commandTimeoutMs < 1000 || commandTimeoutMs > 600000 || !Number.isInteger(idleTimeoutMs) || idleTimeoutMs < 1000 || idleTimeoutMs > commandTimeoutMs) {
11822
+ throw new Error("Timeouts must be integer milliseconds: 1000 <= idleTimeoutMs <= commandTimeoutMs <= 600000.");
11823
+ }
11824
+ this.commandTimeoutMs = commandTimeoutMs;
11825
+ this.idleTimeoutMs = idleTimeoutMs;
11826
+ return `Safe Mode command timeout: ${commandTimeoutMs}ms; idle timeout: ${idleTimeoutMs}ms. Applies to subsequent commands only; does not change RouterOS rollback timing or clear an uncertain session.`;
11827
+ }
11818
11828
  constructor(deviceName) {
11819
11829
  this.deviceName = deviceName;
11820
11830
  }
11821
11831
  get isActive() {
11822
11832
  return this.active;
11823
11833
  }
11834
+ get requiresRecovery() {
11835
+ return this.droppedUnexpectedly || this.uncertain;
11836
+ }
11824
11837
  lock(fn) {
11825
11838
  const run = this.queue.then(fn, fn);
11826
11839
  this.queue = run.then(() => {
@@ -11861,20 +11874,20 @@ class SafeModeManager2 {
11861
11874
  return `Error: Safe mode did not activate. Response: ${JSON.stringify(response.slice(0, 300))}`;
11862
11875
  }
11863
11876
  this.active = true;
11864
- return "Safe mode ENABLED. All changes are temporary \u2014 they will be reverted " + "automatically if the connection drops or you call rollback_safe_mode. " + "Call commit_safe_mode to make changes permanent.";
11877
+ return "Safe mode ENABLED. RouterOS tracks reversible changes while protection remains active. " + "Keep a backup; disconnect requests rollback but does not prove restoration. " + "Call commit_safe_mode after verification.";
11865
11878
  });
11866
11879
  }
11867
11880
  execute(command) {
11868
11881
  return this.lock(async () => {
11869
11882
  if (this.droppedUnexpectedly) {
11870
- throw new Error("Safe Mode session dropped \u2014 RouterOS auto-reverted every staged change; nothing " + "was saved. Re-enable Safe Mode and re-apply, or apply the change directly.");
11883
+ throw new Error("Safe Mode session dropped. Rollback is unverified; inspect device state against the backup before retrying writes.");
11871
11884
  }
11872
11885
  if (!this.active || !this.channel) {
11873
11886
  throw new Error("Safe mode session is not active.");
11874
11887
  }
11875
11888
  if (this.uncertain)
11876
11889
  throw new Error(UNCERTAIN_SESSION);
11877
- const response = this.readUntilPrompt(IDLE_TIMEOUT_MS, undefined, HARD_CAP_MS, true);
11890
+ const response = this.readUntilPrompt(this.idleTimeoutMs, undefined, this.commandTimeoutMs, true);
11878
11891
  this.channel.write(`${command}
11879
11892
  `);
11880
11893
  const { text, timedOut } = await response;
@@ -11882,16 +11895,19 @@ class SafeModeManager2 {
11882
11895
  this.uncertain = true;
11883
11896
  throw new Error(`Safe Mode command did not return a recognized prompt before the timeout (command: ${command}). ` + `Execution may have occurred; do not retry the write blindly. ${UNCERTAIN_SESSION}`);
11884
11897
  }
11898
+ if (classifyPrompt(text) !== "safe") {
11899
+ this.uncertain = true;
11900
+ throw new Error(`Safe Mode protection was lost or could not be confirmed. Changes may already be permanent. ${UNCERTAIN_SESSION}`);
11901
+ }
11885
11902
  return this.extractOutput(text, command);
11886
11903
  });
11887
11904
  }
11888
11905
  commit() {
11889
11906
  return this.lock(async () => {
11890
11907
  if (this.droppedUnexpectedly) {
11891
- this.droppedUnexpectedly = false;
11892
11908
  return {
11893
11909
  ok: false,
11894
- message: "Commit FAILED \u2014 the Safe Mode session dropped before this commit, so RouterOS " + "automatically reverted ALL staged changes and NOTHING was saved. Re-enable Safe Mode " + "and re-apply the changes (or apply them directly and verify each with a read)."
11910
+ message: "Commit FAILED \u2014 the Safe Mode session dropped. Rollback is unverified; compare device state with the backup before retrying."
11895
11911
  };
11896
11912
  }
11897
11913
  if (!this.active || !this.channel) {
@@ -11901,16 +11917,16 @@ class SafeModeManager2 {
11901
11917
  return { ok: false, message: UNCERTAIN_SESSION };
11902
11918
  const before = await this.probeMode();
11903
11919
  if (before === "released") {
11904
- this.cleanup();
11920
+ this.uncertain = true;
11905
11921
  return {
11906
- ok: true,
11907
- message: "Safe mode already exited \u2014 your changes are committed. Safe mode DISABLED."
11922
+ ok: false,
11923
+ message: "Safe Mode exited before commit was requested. Changes may be permanent; verify device state against the backup."
11908
11924
  };
11909
11925
  }
11910
11926
  if (before === "unknown") {
11911
11927
  return {
11912
11928
  ok: false,
11913
- message: "Could not read a prompt to determine Safe Mode state. The session is left open so " + "nothing is reverted \u2014 call get_safe_mode_status, retry commit_safe_mode, or rollback_safe_mode."
11929
+ message: "Could not determine Safe Mode state. Session left open; outcome unverified. " + "Call safe_mode_status or rollback_safe_mode and inspect device state."
11914
11930
  };
11915
11931
  }
11916
11932
  this.channel.write(CTRL_X);
@@ -11927,7 +11943,7 @@ class SafeModeManager2 {
11927
11943
  default:
11928
11944
  return {
11929
11945
  ok: false,
11930
- message: "Commit status unclear \u2014 no prompt seen after the commit. The session is left open so " + "nothing is reverted; verify with get_safe_mode_status or retry commit_safe_mode."
11946
+ message: "Commit status unclear \u2014 no prompt seen after commit. Session left open; outcome unverified. " + "Inspect device state before retrying."
11931
11947
  };
11932
11948
  }
11933
11949
  });
@@ -11936,21 +11952,21 @@ class SafeModeManager2 {
11936
11952
  return this.lock(async () => {
11937
11953
  if (this.droppedUnexpectedly) {
11938
11954
  this.droppedUnexpectedly = false;
11939
- return "Safe Mode session had already dropped \u2014 RouterOS auto-reverted all staged changes; " + "nothing was left to roll back.";
11955
+ return "Safe Mode session had already dropped. Rollback is unverified; compare device state with the backup. Do not blindly reapply writes.";
11940
11956
  }
11941
11957
  if (!this.active)
11942
11958
  return "Safe mode is not active. Nothing to roll back.";
11943
11959
  this.cleanup();
11944
- return "Safe mode session closed. MikroTik has reverted all uncommitted changes automatically.";
11960
+ return "Safe mode session closed to request automatic rollback. Rollback is unverified and may be delayed; compare device state with the backup before retrying writes.";
11945
11961
  });
11946
11962
  }
11947
11963
  status() {
11948
11964
  if (this.droppedUnexpectedly) {
11949
- return "Safe mode session DROPPED unexpectedly \u2014 RouterOS auto-reverted all staged changes; they " + "were NOT saved. Re-enable Safe Mode and re-apply, or apply changes directly (verify each with a read).";
11965
+ return "Safe mode session DROPPED unexpectedly. Rollback is unverified; inspect device state against the backup before retrying writes.";
11950
11966
  }
11951
11967
  if (this.uncertain && this.active)
11952
11968
  return UNCERTAIN_SESSION;
11953
- return this.active ? "Safe mode is ACTIVE. Changes are pending \u2014 they are NOT yet persisted. " + "Call commit_safe_mode to persist or rollback_safe_mode to revert." : "Safe mode is NOT active. Changes take effect and persist immediately.";
11969
+ return this.active ? `Safe mode is ACTIVE (last observed). Command timeout: ${this.commandTimeoutMs}ms; idle timeout: ${this.idleTimeoutMs}ms. ` + "Call commit_safe_mode to persist or rollback_safe_mode to revert." : "Safe mode is NOT active. Changes take effect and persist immediately.";
11954
11970
  }
11955
11971
  handleUnexpectedDrop = () => {
11956
11972
  if (!this.active)
@@ -11966,6 +11982,7 @@ class SafeModeManager2 {
11966
11982
  let buf = "";
11967
11983
  let idleTimer;
11968
11984
  const hardTimer = setTimeout(() => finish(stripAnsi(buf), true), hardCapMs);
11985
+ const onClose = () => finish(stripAnsi(buf), true);
11969
11986
  function armIdle() {
11970
11987
  clearTimeout(idleTimer);
11971
11988
  idleTimer = setTimeout(() => finish(stripAnsi(buf), true), idleMs);
@@ -11988,10 +12005,14 @@ class SafeModeManager2 {
11988
12005
  clearTimeout(idleTimer);
11989
12006
  clearTimeout(hardTimer);
11990
12007
  channel.removeListener("data", onData);
12008
+ channel.removeListener("close", onClose);
12009
+ channel.removeListener("error", onClose);
11991
12010
  resolve({ text: result, timedOut });
11992
12011
  }
11993
12012
  armIdle();
11994
12013
  channel.on("data", onData);
12014
+ channel.once("close", onClose);
12015
+ channel.once("error", onClose);
11995
12016
  });
11996
12017
  }
11997
12018
  async probeMode() {
@@ -12126,7 +12147,7 @@ async function runOnce(command, deviceName, opts, ctx) {
12126
12147
  async function executeMikrotikCommand2(command, ctx, opts) {
12127
12148
  const deviceName = resolveDeviceName2(ctx.device);
12128
12149
  const safe = getSafeModeManager2(deviceName);
12129
- if (safe.isActive) {
12150
+ if (safe.isActive || safe.requiresRecovery) {
12130
12151
  ctx.info(`[${deviceName}] Executing (safe mode): ${containerCommandForLog(command)}`);
12131
12152
  ctx.transport = "ssh";
12132
12153
  return safe.execute(command);
@@ -14845,13 +14866,13 @@ async function undoMigration(id, confirm, selected) {
14845
14866
  throw new Error("Undo lost Safe Mode or exceeded its time budget.");
14846
14867
  await checkedRead(item.undo, createContext(undefined, device));
14847
14868
  }
14848
- const beforeTarget = (await import("./library-dh2r9fza.js")).openSnapshotStore;
14849
- const db = await beforeTarget((await import("./library-vj9yv0px.js")).DEFAULT_SNAPSHOT_DB);
14869
+ const beforeTarget = (await import("./library-akf94mf2.js")).openSnapshotStore;
14870
+ const db = await beforeTarget((await import("./library-g661a57q.js")).DEFAULT_SNAPSHOT_DB);
14850
14871
  try {
14851
14872
  const original = db.get(p.snapshots.target);
14852
14873
  if (!original)
14853
14874
  throw new Error("Original target snapshot unavailable.");
14854
- const { normalizeExport } = await import("./library-ts0epdh7.js");
14875
+ const { normalizeExport } = await import("./library-hykdpvnj.js");
14855
14876
  if (normalizeExport((await migrationInventory(device)).export) !== normalizeExport(original.body))
14856
14877
  throw new Error("Target differs from its backup. Undo verification failed.");
14857
14878
  } finally {
@@ -26780,23 +26801,13 @@ async function applyWritesSafely(ctx, deviceName, commands, opts = {}) {
26780
26801
  await mgr.rollback().catch(() => {
26781
26802
  return;
26782
26803
  });
26783
- if (!fallback)
26784
- return {
26785
- applied,
26786
- total,
26787
- safeMode: `rolled back (a write failed: ${wedged})`,
26788
- committed: false,
26789
- error: wedged,
26790
- fellBack: false
26791
- };
26792
- const r = await applyCommandsDirect(ctx, commands);
26793
26804
  return {
26794
- applied: r.applied,
26805
+ applied,
26795
26806
  total,
26796
- safeMode: `Safe Mode wedged (${wedged}) \u2014 rolled back and re-applied directly (snapshot is the rollback point)`,
26797
- committed: !r.error,
26798
- error: r.error,
26799
- fellBack: true
26807
+ safeMode: `rollback requested, unverified (a write failed: ${wedged}); inspect the snapshot before retrying`,
26808
+ committed: false,
26809
+ error: wedged,
26810
+ fellBack: false
26800
26811
  };
26801
26812
  }
26802
26813
  const c = await mgr.commit();
@@ -27175,7 +27186,7 @@ var cache3 = null;
27175
27186
  async function gateway() {
27176
27187
  if (cache3)
27177
27188
  return cache3;
27178
- const { moduleCatalog } = await import("./library-2a48dhze.js");
27189
+ const { moduleCatalog } = await import("./library-2m4as43g.js");
27179
27190
  const forIndex = [];
27180
27191
  const byName = new Map;
27181
27192
  for (const mod of moduleCatalog) {
@@ -49437,6 +49448,19 @@ ${details}`;
49437
49448
 
49438
49449
  // src/tools/safe-mode.ts
49439
49450
  var safeModeTools = [
49451
+ defineTool2({
49452
+ name: "set_safe_mode_timeout",
49453
+ title: "Set Safe Mode Command Timeouts",
49454
+ annotations: WRITE,
49455
+ description: "Set per-device MCP Safe Mode command deadlines before or during a session. Applies only to subsequent commands. Increase for slow exports, decrease for faster failure detection. Does not change RouterOS rollback timing, MCP client deadlines, or unblock an uncertain session. Settings are in-memory and reset on MCP restart. Defaults: command 120000ms, idle 15000ms.",
49456
+ inputSchema: {
49457
+ commandTimeoutMs: number().int().min(1000).max(600000).describe("Absolute command deadline in milliseconds."),
49458
+ idleTimeoutMs: number().int().min(1000).max(600000).describe("Maximum silence in milliseconds; must not exceed commandTimeoutMs.")
49459
+ },
49460
+ handler(a, ctx) {
49461
+ return getSafeModeManager2(resolveDeviceName2(ctx.device)).setTimeouts(a.commandTimeoutMs, a.idleTimeoutMs);
49462
+ }
49463
+ }),
49440
49464
  defineTool2({
49441
49465
  name: "safe_mode_status",
49442
49466
  title: "Get Safe Mode Session Status",
@@ -49452,7 +49476,7 @@ var safeModeTools = [
49452
49476
  name: "enable_safe_mode",
49453
49477
  title: "Enable Safe Mode Session",
49454
49478
  annotations: WRITE,
49455
- description: "Opens a Safe Mode SSH session on the targeted device (RouterOS Ctrl+X equivalent) \u2014 all subsequent configuration changes are staged in memory and auto-reverted if the SSH connection drops before an explicit commit." + " Use this to make reversible, transactional configuration changes without risk of permanent misconfiguration." + " Safe Mode is SSH-only and is not supported over MAC-Telnet connections." + " Check current state first with safe_mode_status; persist staged changes with commit_safe_mode; discard staged changes without saving with rollback_safe_mode.",
49479
+ description: "Opens a Safe Mode SSH session on the targeted device (RouterOS Ctrl+X equivalent) \u2014 all subsequent configuration changes are staged in memory and auto-reverted if the SSH connection drops before an explicit commit." + " Take a backup first: protection may be lost and disconnect is not proof of rollback. Use set_safe_mode_timeout to tune subsequent command deadlines." + " Safe Mode is SSH-only and is not supported over MAC-Telnet connections." + " Check current state first with safe_mode_status; persist staged changes with commit_safe_mode; discard staged changes without saving with rollback_safe_mode.",
49456
49480
  async handler(_a, ctx) {
49457
49481
  const device = resolveDeviceName2(ctx.device);
49458
49482
  ctx.info(`[${device}] Enabling MikroTik safe mode`);
@@ -49474,7 +49498,7 @@ var safeModeTools = [
49474
49498
  name: "rollback_safe_mode",
49475
49499
  title: "Roll Back Safe Mode Changes",
49476
49500
  annotations: WRITE,
49477
- description: "Discards all pending Safe Mode changes on the targeted device by closing the SSH session, triggering RouterOS's automatic revert \u2014 all configuration changes staged since enable_safe_mode was called are undone as if they were never applied." + " Use this when staged changes are incorrect or need to be abandoned without saving." + " To persist staged changes instead, use commit_safe_mode." + " Check current Safe Mode state with safe_mode_status.",
49501
+ description: "Closes the targeted Safe Mode SSH session to request RouterOS automatic rollback. Completion is unverified and may be delayed; compare live configuration against a backup before retrying writes." + " Use this when staged changes are incorrect or need to be abandoned without saving." + " To persist staged changes instead, use commit_safe_mode." + " Check current Safe Mode state with safe_mode_status.",
49478
49502
  async handler(_a, ctx) {
49479
49503
  const device = resolveDeviceName2(ctx.device);
49480
49504
  ctx.info(`[${device}] Rolling back safe mode changes`);
@@ -52026,7 +52050,7 @@ var riskByTool = null;
52026
52050
  async function riskIndex() {
52027
52051
  if (riskByTool)
52028
52052
  return riskByTool;
52029
- const { moduleCatalog } = await import("./library-2a48dhze.js");
52053
+ const { moduleCatalog } = await import("./library-2m4as43g.js");
52030
52054
  const index = new Map;
52031
52055
  for (const mod of moduleCatalog) {
52032
52056
  for (const tool of mod.tools)