@usex/mikrotik-mcp 4.20.0 → 4.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  LOGO_URL,
12
12
  MikrotikConfigSchema,
13
13
  PKG_META,
14
+ PROJECT_ROOT,
14
15
  PROMPTS_DIR,
15
16
  REDACTED,
16
17
  SERVER_DESCRIPTION,
@@ -124,7 +125,7 @@ import {
124
125
  updateAaaEntity,
125
126
  updateSummaryLine,
126
127
  writeBackup
127
- } from "./shared/cli-fa29149s.js";
128
+ } from "./shared/cli-8ecncq7y.js";
128
129
 
129
130
  // src/cli.ts
130
131
  import { existsSync as existsSync2 } from "fs";
@@ -132,8 +133,8 @@ import { existsSync as existsSync2 } from "fs";
132
133
  // src/observability/dashboard.ts
133
134
  import { spawn } from "child_process";
134
135
  import { readFileSync as readFileSync3 } from "fs";
135
- import { homedir, networkInterfaces } from "os";
136
- import { dirname as dirname5, join as join3 } from "path";
136
+ import { homedir as homedir2, networkInterfaces } from "os";
137
+ import { dirname as dirname5, join as join4 } from "path";
137
138
  var {serve } = globalThis.Bun;
138
139
  import { z as z2 } from "zod";
139
140
 
@@ -815,6 +816,142 @@ function stopHealthChecks() {
815
816
  }
816
817
  }
817
818
 
819
+ // src/observability/geo.ts
820
+ import { lookup } from "dns/promises";
821
+ var LOG_TAG2 = "mikrotik-mcp";
822
+ var cache = new Map;
823
+ var REFRESH_MS = 24 * 60 * 60000;
824
+ var timer2 = null;
825
+ var inFlight2 = false;
826
+ function getDeviceGeo(name) {
827
+ return cache.get(name)?.geo ?? null;
828
+ }
829
+ var IPV4_RE = /^\d{1,3}(?:\.\d{1,3}){3}$/;
830
+ var PRIVATE_RE = /^(?:10\.|127\.|0\.|169\.254\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.|::1$|f[cd])/i;
831
+ function isIpLiteral(host) {
832
+ return IPV4_RE.test(host) || host.includes(":");
833
+ }
834
+ async function publicIpOf(host) {
835
+ let ip = host;
836
+ if (!isIpLiteral(host)) {
837
+ try {
838
+ ip = (await lookup(host)).address;
839
+ } catch {
840
+ return null;
841
+ }
842
+ }
843
+ return PRIVATE_RE.test(ip) ? null : ip;
844
+ }
845
+ function toGeo(country, code, city) {
846
+ if (!code)
847
+ return null;
848
+ return { countryCode: code.toLowerCase(), country: country ?? code, city: city || undefined };
849
+ }
850
+ async function fetchIpkit(ip) {
851
+ const res = await fetch(`https://ipkit.ir/${ip}`, {
852
+ headers: { accept: "application/json" },
853
+ signal: AbortSignal.timeout(8000)
854
+ });
855
+ if (!res.ok)
856
+ throw new Error(`ipkit HTTP ${res.status}`);
857
+ const d = await res.json();
858
+ if (d.is_private)
859
+ return null;
860
+ return toGeo(d.country, d.country_code, d.city);
861
+ }
862
+ async function fetchIpquery(ip) {
863
+ const res = await fetch(`https://api.ipquery.io/${ip}`, { signal: AbortSignal.timeout(8000) });
864
+ if (!res.ok)
865
+ throw new Error(`ipquery HTTP ${res.status}`);
866
+ const d = await res.json();
867
+ return toGeo(d.location?.country, d.location?.country_code, d.location?.city);
868
+ }
869
+ async function fetchGeo(ip) {
870
+ try {
871
+ return await fetchIpkit(ip);
872
+ } catch (e) {
873
+ logger.warn(`[${LOG_TAG2}] ipkit geo failed for ${ip}, trying ipquery: ${e instanceof Error ? e.message : String(e)}`);
874
+ }
875
+ try {
876
+ return await fetchIpquery(ip);
877
+ } catch (e) {
878
+ logger.warn(`[${LOG_TAG2}] geo lookup failed for ${ip}: ${e instanceof Error ? e.message : String(e)}`);
879
+ return null;
880
+ }
881
+ }
882
+ async function resolveDevice(name, host) {
883
+ const ip = host ? await publicIpOf(host) : null;
884
+ const geo = ip ? await fetchGeo(ip) : null;
885
+ cache.set(name, { geo, at: Date.now() });
886
+ }
887
+ async function refreshGeo() {
888
+ if (inFlight2)
889
+ return;
890
+ inFlight2 = true;
891
+ try {
892
+ const now = Date.now();
893
+ await Promise.all(Object.entries(getConfig().devices).map(([name, dc]) => {
894
+ const c = cache.get(name);
895
+ if (c && now - c.at < REFRESH_MS)
896
+ return Promise.resolve();
897
+ return resolveDevice(name, dc.mac ? undefined : dc.host);
898
+ }));
899
+ } finally {
900
+ inFlight2 = false;
901
+ }
902
+ }
903
+ function startGeoLookups() {
904
+ refreshGeo();
905
+ timer2 = setInterval(() => void refreshGeo(), REFRESH_MS);
906
+ }
907
+ function stopGeoLookups() {
908
+ if (timer2) {
909
+ clearInterval(timer2);
910
+ timer2 = null;
911
+ }
912
+ }
913
+
914
+ // src/observability/flags.ts
915
+ import { join as join3 } from "path";
916
+ import { mkdir, readFile, writeFile } from "fs/promises";
917
+ import { homedir } from "os";
918
+ var LOG_TAG3 = "mikrotik-mcp";
919
+ var CODE_RE = /^[a-z]{2}$/;
920
+ var sourceUrl = (code) => `https://hatscripts.github.io/circle-flags/flags/${code}.svg`;
921
+ var VENDOR_DIR = join3(PROJECT_ROOT, "assets", "flags");
922
+ var CACHE_DIR = join3(homedir(), ".mikrotik-mcp", "flags");
923
+ var mem = new Map;
924
+ async function flagSvg(code) {
925
+ const c = code.toLowerCase();
926
+ if (!CODE_RE.test(c))
927
+ return null;
928
+ const cached = mem.get(c);
929
+ if (cached !== undefined)
930
+ return cached;
931
+ for (const file of [join3(VENDOR_DIR, `${c}.svg`), join3(CACHE_DIR, `${c}.svg`)]) {
932
+ try {
933
+ const svg = await readFile(file, "utf8");
934
+ mem.set(c, svg);
935
+ return svg;
936
+ } catch {}
937
+ }
938
+ try {
939
+ const res = await fetch(sourceUrl(c), { signal: AbortSignal.timeout(8000) });
940
+ if (!res.ok) {
941
+ if (res.status === 404)
942
+ mem.set(c, null);
943
+ return null;
944
+ }
945
+ const svg = await res.text();
946
+ mem.set(c, svg);
947
+ mkdir(CACHE_DIR, { recursive: true }).then(() => writeFile(join3(CACHE_DIR, `${c}.svg`), svg)).catch(() => {});
948
+ return svg;
949
+ } catch (e) {
950
+ logger.warn(`[${LOG_TAG3}] flag fetch failed for '${c}': ${e instanceof Error ? e.message : String(e)}`);
951
+ return null;
952
+ }
953
+ }
954
+
818
955
  // src/observability/traffic-hub.ts
819
956
  var POLL_MS = 1000;
820
957
  var hubs = new Map;
@@ -1140,8 +1277,8 @@ var CAPSMAN_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
1140
1277
  var DEFAULT_CAPSMAN_INTERVAL_MS = 5 * 60000;
1141
1278
  var MIN_CAPSMAN_INTERVAL_MS = 60000;
1142
1279
  var MAX_CAPSMAN_INTERVAL_MS = 6 * 60 * 60000;
1143
- var timer2 = null;
1144
- var inFlight2 = false;
1280
+ var timer3 = null;
1281
+ var inFlight3 = false;
1145
1282
  var noCapsman = new Set;
1146
1283
  function clampInterval(ms) {
1147
1284
  if (!Number.isFinite(ms))
@@ -1168,9 +1305,9 @@ async function sampleDevice(store, device, ts) {
1168
1305
  store.recordRadioSamples(device, ts, samples);
1169
1306
  }
1170
1307
  async function sampleCapsmanOnce(store) {
1171
- if (inFlight2)
1308
+ if (inFlight3)
1172
1309
  return;
1173
- inFlight2 = true;
1310
+ inFlight3 = true;
1174
1311
  const ts = Date.now();
1175
1312
  try {
1176
1313
  const cfg = getConfig();
@@ -1185,18 +1322,18 @@ async function sampleCapsmanOnce(store) {
1185
1322
  }));
1186
1323
  store.pruneSamples(ts - CAPSMAN_RETENTION_MS);
1187
1324
  } finally {
1188
- inFlight2 = false;
1325
+ inFlight3 = false;
1189
1326
  }
1190
1327
  }
1191
1328
  function startCapsmanSampler(store, intervalMs = DEFAULT_CAPSMAN_INTERVAL_MS) {
1192
1329
  const ms = clampInterval(intervalMs);
1193
1330
  sampleCapsmanOnce(store);
1194
- timer2 = setInterval(() => void sampleCapsmanOnce(store), ms);
1331
+ timer3 = setInterval(() => void sampleCapsmanOnce(store), ms);
1195
1332
  }
1196
1333
  function stopCapsmanSampler() {
1197
- if (timer2) {
1198
- clearInterval(timer2);
1199
- timer2 = null;
1334
+ if (timer3) {
1335
+ clearInterval(timer3);
1336
+ timer3 = null;
1200
1337
  }
1201
1338
  }
1202
1339
 
@@ -1336,8 +1473,8 @@ var USAGE_RETENTION_MS = 93 * 24 * 60 * 60 * 1000;
1336
1473
  var DEFAULT_USAGE_INTERVAL_MS = 60000;
1337
1474
  var MIN_USAGE_INTERVAL_MS = 30000;
1338
1475
  var MAX_USAGE_INTERVAL_MS = 6 * 60 * 60000;
1339
- var timer3 = null;
1340
- var inFlight3 = false;
1476
+ var timer4 = null;
1477
+ var inFlight4 = false;
1341
1478
  var currentStore = null;
1342
1479
  var currentIntervalMs = DEFAULT_USAGE_INTERVAL_MS;
1343
1480
  function clampInterval2(ms) {
@@ -1398,9 +1535,9 @@ async function ingestSessions(store, device) {
1398
1535
  store.upsertSessions(device, sessions);
1399
1536
  }
1400
1537
  async function sampleUsageOnce(store) {
1401
- if (inFlight3)
1538
+ if (inFlight4)
1402
1539
  return;
1403
- inFlight3 = true;
1540
+ inFlight4 = true;
1404
1541
  const ts = Date.now();
1405
1542
  try {
1406
1543
  const cfg = getConfig();
@@ -1416,32 +1553,32 @@ async function sampleUsageOnce(store) {
1416
1553
  }));
1417
1554
  store.pruneSamples(ts - USAGE_RETENTION_MS);
1418
1555
  } finally {
1419
- inFlight3 = false;
1556
+ inFlight4 = false;
1420
1557
  }
1421
1558
  }
1422
1559
  function startUsageSampler(store, intervalMs = DEFAULT_USAGE_INTERVAL_MS) {
1423
1560
  currentStore = store;
1424
1561
  currentIntervalMs = clampInterval2(intervalMs);
1425
1562
  sampleUsageOnce(store);
1426
- timer3 = setInterval(() => void sampleUsageOnce(store), currentIntervalMs);
1563
+ timer4 = setInterval(() => void sampleUsageOnce(store), currentIntervalMs);
1427
1564
  }
1428
1565
  function getUsageSamplerInterval() {
1429
1566
  return currentIntervalMs;
1430
1567
  }
1431
1568
  function setUsageSamplerInterval(intervalMs) {
1432
1569
  currentIntervalMs = clampInterval2(intervalMs);
1433
- if (timer3)
1434
- clearInterval(timer3);
1570
+ if (timer4)
1571
+ clearInterval(timer4);
1435
1572
  if (currentStore) {
1436
1573
  const store = currentStore;
1437
- timer3 = setInterval(() => void sampleUsageOnce(store), currentIntervalMs);
1574
+ timer4 = setInterval(() => void sampleUsageOnce(store), currentIntervalMs);
1438
1575
  }
1439
1576
  return currentIntervalMs;
1440
1577
  }
1441
1578
  function stopUsageSampler() {
1442
- if (timer3) {
1443
- clearInterval(timer3);
1444
- timer3 = null;
1579
+ if (timer4) {
1580
+ clearInterval(timer4);
1581
+ timer4 = null;
1445
1582
  }
1446
1583
  currentStore = null;
1447
1584
  }
@@ -1834,7 +1971,7 @@ function runUpgrade(spec) {
1834
1971
  env: process.env,
1835
1972
  stdio: ["ignore", "pipe", "pipe"]
1836
1973
  });
1837
- const timer4 = setTimeout(() => {
1974
+ const timer5 = setTimeout(() => {
1838
1975
  child.kill();
1839
1976
  resolve({ ok: false, log: `${out}
1840
1977
  (timed out after 180s)` });
@@ -1842,19 +1979,19 @@ function runUpgrade(spec) {
1842
1979
  child.stdout?.on("data", (d) => out += d.toString());
1843
1980
  child.stderr?.on("data", (d) => out += d.toString());
1844
1981
  child.on("error", (e) => {
1845
- clearTimeout(timer4);
1982
+ clearTimeout(timer5);
1846
1983
  resolve({ ok: false, log: `${out}
1847
1984
  spawn error: ${String(e)}` });
1848
1985
  });
1849
1986
  child.on("exit", (code) => {
1850
- clearTimeout(timer4);
1987
+ clearTimeout(timer5);
1851
1988
  resolve({ ok: code === 0, log: out.trim() || `(exit ${code})` });
1852
1989
  });
1853
1990
  });
1854
1991
  }
1855
1992
  function dashboardHtml() {
1856
1993
  try {
1857
- return readFileSync3(join3(UI_DIST_DIR, "observability.html"), "utf8");
1994
+ return readFileSync3(join4(UI_DIST_DIR, "observability.html"), "utf8");
1858
1995
  } catch {
1859
1996
  return `<!doctype html><meta charset=utf-8><body style="font:14px system-ui;padding:24px;background:#0b0d10;color:#e8eaed">
1860
1997
  <h2>MikroTik MCP \u2014 Observability Dashboard</h2>
@@ -1948,6 +2085,7 @@ function devicesPayload(store) {
1948
2085
  jumpVia: dc.jumpVia,
1949
2086
  jumpHost: dc.jumpHost ? { host: dc.jumpHost.host, port: dc.jumpHost.port } : undefined,
1950
2087
  status: getDeviceStatus(name),
2088
+ geo: getDeviceGeo(name),
1951
2089
  history: getDeviceHistory(name),
1952
2090
  activity: activity.get(name) ?? {
1953
2091
  calls: 0,
@@ -2733,7 +2871,7 @@ async function featureRoutes(req, url) {
2733
2871
  const raw = b?.dir?.trim();
2734
2872
  if (!raw)
2735
2873
  return json3({ error: "dir required" }, 400);
2736
- const dir = raw === "~" || raw.startsWith("~/") ? join3(homedir(), raw.slice(1)) : raw;
2874
+ const dir = raw === "~" || raw.startsWith("~/") ? join4(homedir2(), raw.slice(1)) : raw;
2737
2875
  const next = { ...getConfig(), backupDir: dir };
2738
2876
  setConfig(next);
2739
2877
  try {
@@ -2840,14 +2978,15 @@ async function runDashboard(cfg, transportLabel) {
2840
2978
  transport: transportLabel
2841
2979
  });
2842
2980
  startHealthChecks(30000);
2981
+ startGeoLookups();
2843
2982
  try {
2844
- usageStore = await openUsageStore(join3(dirname5(cfg.dbPath), "usage.db"));
2983
+ usageStore = await openUsageStore(join4(dirname5(cfg.dbPath), "usage.db"));
2845
2984
  startUsageSampler(usageStore);
2846
2985
  } catch (e) {
2847
2986
  logger.warn(`[${SERVER_TAG3}] usage history disabled: ${String(e)}`);
2848
2987
  }
2849
2988
  try {
2850
- capsmanStore = await openCapsmanStore(join3(dirname5(cfg.dbPath), "capsman.db"));
2989
+ capsmanStore = await openCapsmanStore(join4(dirname5(cfg.dbPath), "capsman.db"));
2851
2990
  startCapsmanSampler(capsmanStore);
2852
2991
  } catch (e) {
2853
2992
  logger.warn(`[${SERVER_TAG3}] capsman trends disabled: ${String(e)}`);
@@ -2959,6 +3098,18 @@ async function runDashboard(cfg, transportLabel) {
2959
3098
  devices: ps
2960
3099
  });
2961
3100
  }
3101
+ if (url.pathname.startsWith("/api/flag/")) {
3102
+ const code = url.pathname.slice("/api/flag/".length).replace(/\.svg$/, "");
3103
+ const svg = await flagSvg(code);
3104
+ if (!svg)
3105
+ return new Response("flag not found", { status: 404 });
3106
+ return new Response(svg, {
3107
+ headers: {
3108
+ "content-type": "image/svg+xml; charset=utf-8",
3109
+ "cache-control": "public, max-age=86400"
3110
+ }
3111
+ });
3112
+ }
2962
3113
  if (url.pathname === "/api/devices") {
2963
3114
  return json3(devicesPayload(db));
2964
3115
  }
@@ -3169,6 +3320,7 @@ async function runDashboard(cfg, transportLabel) {
3169
3320
  store,
3170
3321
  stop() {
3171
3322
  stopHealthChecks();
3323
+ stopGeoLookups();
3172
3324
  stopUsageSampler();
3173
3325
  stopCapsmanSampler();
3174
3326
  server.stop(true);
@@ -3359,18 +3511,18 @@ function installToolPagination(server, pageSize) {
3359
3511
  const sdkHandler = low._requestHandlers?.get("tools/list");
3360
3512
  if (typeof sdkHandler !== "function")
3361
3513
  return;
3362
- let cache = null;
3514
+ let cache2 = null;
3363
3515
  server.server.setRequestHandler(ListToolsRequestSchema, async (request, extra) => {
3364
- if (!cache)
3365
- cache = (await sdkHandler(request, extra)).tools ?? [];
3366
- const total = cache.length;
3516
+ if (!cache2)
3517
+ cache2 = (await sdkHandler(request, extra)).tools ?? [];
3518
+ const total = cache2.length;
3367
3519
  const cursor = request.params?.cursor;
3368
3520
  let start = 0;
3369
3521
  if (typeof cursor === "string") {
3370
3522
  const n = Number.parseInt(cursor, 10);
3371
3523
  start = Number.isFinite(n) && n > 0 ? Math.min(n, total) : 0;
3372
3524
  }
3373
- const tools = cache.slice(start, start + pageSize);
3525
+ const tools = cache2.slice(start, start + pageSize);
3374
3526
  const end = start + tools.length;
3375
3527
  return end < total ? { tools, nextCursor: String(end) } : { tools };
3376
3528
  });
package/dist/index.js CHANGED
@@ -29,7 +29,7 @@ import {
29
29
  selectToolModules,
30
30
  setConfig,
31
31
  updateSummaryLine
32
- } from "./shared/library-ypdm9bkx.js";
32
+ } from "./shared/library-v21pwa2g.js";
33
33
  // src/server.ts
34
34
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
35
35
  import { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
@@ -4,7 +4,7 @@ import {
4
4
  allToolModules,
5
5
  moduleCatalog,
6
6
  selectToolModules
7
- } from "./cli-fa29149s.js";
7
+ } from "./cli-8ecncq7y.js";
8
8
  export {
9
9
  selectToolModules,
10
10
  moduleCatalog,