@solomonneas/librenms-mcp 0.2.0 → 0.2.2
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/README.md +177 -56
- package/dist/cli.js +1656 -0
- package/dist/index.js +586 -63
- package/dist/mcp-bin.js +1206 -0
- package/dist/mcp-server.js +672 -127
- package/openclaw.plugin.json +12 -4
- package/package.json +49 -13
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1656 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { realpathSync } from "fs";
|
|
5
|
+
import { pathToFileURL } from "url";
|
|
6
|
+
|
|
7
|
+
// src/config.ts
|
|
8
|
+
import { Effect as Effect6 } from "effect";
|
|
9
|
+
|
|
10
|
+
// node_modules/@lidless-labs/effect-operator-kit/dist/index.js
|
|
11
|
+
import { Data } from "effect";
|
|
12
|
+
import { Effect } from "effect";
|
|
13
|
+
import { Effect as Effect2 } from "effect";
|
|
14
|
+
import { Duration, Effect as Effect3, Schedule } from "effect";
|
|
15
|
+
import { Cause, Effect as Effect4, Exit } from "effect";
|
|
16
|
+
import { Cause as Cause2, Effect as Effect5 } from "effect";
|
|
17
|
+
var ConfigError = class extends Data.TaggedError("ConfigError") {
|
|
18
|
+
};
|
|
19
|
+
var AuthError = class extends Data.TaggedError("AuthError") {
|
|
20
|
+
};
|
|
21
|
+
var ForbiddenError = class extends Data.TaggedError("ForbiddenError") {
|
|
22
|
+
};
|
|
23
|
+
var NotFoundError = class extends Data.TaggedError("NotFoundError") {
|
|
24
|
+
};
|
|
25
|
+
var TimeoutError = class extends Data.TaggedError("TimeoutError") {
|
|
26
|
+
};
|
|
27
|
+
var TransportError = class extends Data.TaggedError("TransportError") {
|
|
28
|
+
};
|
|
29
|
+
var ParseError = class extends Data.TaggedError("ParseError") {
|
|
30
|
+
};
|
|
31
|
+
var UnexpectedStatusError = class extends Data.TaggedError("UnexpectedStatusError") {
|
|
32
|
+
};
|
|
33
|
+
var fromProcessEnv = (env) => ({
|
|
34
|
+
get: (key) => (env ?? process.env)[key]
|
|
35
|
+
});
|
|
36
|
+
var isBlank = (raw) => raw === void 0 || raw.trim() === "";
|
|
37
|
+
var failConfig = (partial) => Effect.fail(new ConfigError(partial));
|
|
38
|
+
var readRaw = (env, key) => env.get(key);
|
|
39
|
+
var TRUE_TOKENS = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
|
|
40
|
+
var FALSE_TOKENS = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
|
|
41
|
+
var parseBooleanEnv = (env, key, fallback) => {
|
|
42
|
+
const raw = readRaw(env, key);
|
|
43
|
+
if (isBlank(raw)) {
|
|
44
|
+
return Effect.succeed(fallback);
|
|
45
|
+
}
|
|
46
|
+
const token = raw.trim().toLowerCase();
|
|
47
|
+
if (TRUE_TOKENS.has(token)) {
|
|
48
|
+
return Effect.succeed(true);
|
|
49
|
+
}
|
|
50
|
+
if (FALSE_TOKENS.has(token)) {
|
|
51
|
+
return Effect.succeed(false);
|
|
52
|
+
}
|
|
53
|
+
return failConfig({
|
|
54
|
+
key,
|
|
55
|
+
value: raw,
|
|
56
|
+
message: `${key} must be a boolean (true/false, 1/0, yes/no, on/off)`
|
|
57
|
+
});
|
|
58
|
+
};
|
|
59
|
+
var parseTimeoutEnv = (env, key, opts) => {
|
|
60
|
+
const raw = readRaw(env, key);
|
|
61
|
+
if (isBlank(raw)) {
|
|
62
|
+
return Effect.succeed(opts.fallbackMs);
|
|
63
|
+
}
|
|
64
|
+
const parsed = Number(raw.trim());
|
|
65
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
66
|
+
return failConfig({
|
|
67
|
+
key,
|
|
68
|
+
value: raw,
|
|
69
|
+
message: `${key} must be a positive timeout`
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
const unit = opts.unit ?? "s";
|
|
73
|
+
const ms = unit === "ms" ? parsed : parsed * 1e3;
|
|
74
|
+
if (opts.minMs !== void 0 && ms < opts.minMs) {
|
|
75
|
+
return failConfig({
|
|
76
|
+
key,
|
|
77
|
+
value: raw,
|
|
78
|
+
message: `${key} must be at least ${opts.minMs}ms`
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
if (opts.maxMs !== void 0 && ms > opts.maxMs) {
|
|
82
|
+
return failConfig({
|
|
83
|
+
key,
|
|
84
|
+
value: raw,
|
|
85
|
+
message: `${key} must be at most ${opts.maxMs}ms`
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
return Effect.succeed(ms);
|
|
89
|
+
};
|
|
90
|
+
var SECRET_PATTERNS = [
|
|
91
|
+
/(authorization:\s*)(basic|bearer)\s+[a-z0-9._~+/=-]+/gi,
|
|
92
|
+
/\b(basic|bearer)\s+[a-z0-9._~+/=-]+/gi,
|
|
93
|
+
/(authorization:\s*)(?:token|digest|hawk|oauth|apikey)\s+\S+/gi,
|
|
94
|
+
/(x-n8n-api-key|x-auth-token|x-emby-token|x-api-key)\s*:\s*\S+/gi,
|
|
95
|
+
/(https?:\/\/)([^@\s/]+)@/gi,
|
|
96
|
+
/([?&](?:access_token|refresh_token|client_secret|id_token|x-api-key|\w+_(?:token|secret)|password|token|secret|api[_-]?key|key)=)[^&\s]+/gi,
|
|
97
|
+
/\beyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\b/g
|
|
98
|
+
];
|
|
99
|
+
var MAX_LENGTH = 500;
|
|
100
|
+
var redactString = (message, secrets = []) => {
|
|
101
|
+
let sanitized = message;
|
|
102
|
+
for (const secret of secrets) {
|
|
103
|
+
if (secret) {
|
|
104
|
+
sanitized = sanitized.split(secret).join("[REDACTED]");
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
sanitized = sanitized.replace(SECRET_PATTERNS[0], "$1$2 [REDACTED]").replace(SECRET_PATTERNS[1], "$1 [REDACTED]").replace(SECRET_PATTERNS[2], "$1[REDACTED]").replace(SECRET_PATTERNS[3], "$1: [REDACTED]").replace(SECRET_PATTERNS[4], "$1[REDACTED]@").replace(SECRET_PATTERNS[5], "$1[REDACTED]").replace(SECRET_PATTERNS[6], "[REDACTED]");
|
|
108
|
+
return sanitized.length > MAX_LENGTH ? `${sanitized.slice(0, MAX_LENGTH)}...` : sanitized;
|
|
109
|
+
};
|
|
110
|
+
var defaultRedact = (value) => redactString(value);
|
|
111
|
+
var DEFAULT_SUCCESS_STATUSES = Array.from({ length: 100 }, (_, i) => 200 + i);
|
|
112
|
+
function redactBody(text, redact2) {
|
|
113
|
+
return (redact2 ?? defaultRedact)(text);
|
|
114
|
+
}
|
|
115
|
+
function mergeHeaders(...sources) {
|
|
116
|
+
const merged = new Headers();
|
|
117
|
+
for (const source of sources) {
|
|
118
|
+
if (!source) continue;
|
|
119
|
+
const headers = new Headers(source);
|
|
120
|
+
headers.forEach((value, key) => merged.set(key, value));
|
|
121
|
+
}
|
|
122
|
+
return merged;
|
|
123
|
+
}
|
|
124
|
+
function resolveExpectedStatuses(req) {
|
|
125
|
+
return req.expectedStatuses ?? DEFAULT_SUCCESS_STATUSES;
|
|
126
|
+
}
|
|
127
|
+
function isExpectedStatus(status, expected) {
|
|
128
|
+
return expected.includes(status);
|
|
129
|
+
}
|
|
130
|
+
function resolveBodyEncoding(req) {
|
|
131
|
+
if (req.bodyEncoding !== void 0) return req.bodyEncoding;
|
|
132
|
+
return req.body !== void 0 ? "json" : "none";
|
|
133
|
+
}
|
|
134
|
+
function setContentTypeIfAbsent(headers, contentType) {
|
|
135
|
+
if (!headers.has("content-type")) {
|
|
136
|
+
headers.set("content-type", contentType);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function buildRequestBody(req, headers) {
|
|
140
|
+
const encoding = resolveBodyEncoding(req);
|
|
141
|
+
switch (encoding) {
|
|
142
|
+
case "none":
|
|
143
|
+
return void 0;
|
|
144
|
+
case "json":
|
|
145
|
+
setContentTypeIfAbsent(headers, "application/json");
|
|
146
|
+
return JSON.stringify(req.body);
|
|
147
|
+
case "text":
|
|
148
|
+
setContentTypeIfAbsent(headers, "text/plain");
|
|
149
|
+
return String(req.body);
|
|
150
|
+
case "form": {
|
|
151
|
+
setContentTypeIfAbsent(
|
|
152
|
+
headers,
|
|
153
|
+
"application/x-www-form-urlencoded"
|
|
154
|
+
);
|
|
155
|
+
const params = new URLSearchParams();
|
|
156
|
+
if (req.body && typeof req.body === "object") {
|
|
157
|
+
for (const [key, value] of Object.entries(
|
|
158
|
+
req.body
|
|
159
|
+
)) {
|
|
160
|
+
params.set(key, String(value));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return params.toString();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function mapUnexpectedStatus(req, status, bodyText, expectedStatuses, redact2) {
|
|
168
|
+
const redacted = redactBody(bodyText, redact2);
|
|
169
|
+
const mapperInput = {
|
|
170
|
+
status,
|
|
171
|
+
method: req.method,
|
|
172
|
+
path: req.path,
|
|
173
|
+
bodyText: redacted,
|
|
174
|
+
expectedStatuses
|
|
175
|
+
};
|
|
176
|
+
if (req.statusMapper) {
|
|
177
|
+
const custom = req.statusMapper(mapperInput);
|
|
178
|
+
if (custom !== null) return custom;
|
|
179
|
+
}
|
|
180
|
+
const base = {
|
|
181
|
+
method: req.method,
|
|
182
|
+
path: req.path,
|
|
183
|
+
status,
|
|
184
|
+
body: redacted
|
|
185
|
+
};
|
|
186
|
+
switch (status) {
|
|
187
|
+
case 401:
|
|
188
|
+
return new AuthError(base);
|
|
189
|
+
case 403:
|
|
190
|
+
return new ForbiddenError(base);
|
|
191
|
+
case 404:
|
|
192
|
+
return new NotFoundError(base);
|
|
193
|
+
default:
|
|
194
|
+
return new UnexpectedStatusError({
|
|
195
|
+
method: req.method,
|
|
196
|
+
path: req.path,
|
|
197
|
+
status,
|
|
198
|
+
body: redacted,
|
|
199
|
+
expected: expectedStatuses
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function parseResponseBody(req, bodyText, redact2) {
|
|
204
|
+
const responseType = req.responseType ?? "json";
|
|
205
|
+
if (responseType === "none") {
|
|
206
|
+
return Effect2.succeed(void 0);
|
|
207
|
+
}
|
|
208
|
+
if (responseType === "text") {
|
|
209
|
+
return Effect2.succeed(bodyText);
|
|
210
|
+
}
|
|
211
|
+
if (bodyText.length === 0) {
|
|
212
|
+
return Effect2.succeed(void 0);
|
|
213
|
+
}
|
|
214
|
+
return Effect2.try({
|
|
215
|
+
try: () => JSON.parse(bodyText),
|
|
216
|
+
catch: (cause) => new ParseError({
|
|
217
|
+
path: req.path,
|
|
218
|
+
body: redactBody(bodyText, redact2),
|
|
219
|
+
message: "Failed to parse JSON response",
|
|
220
|
+
cause
|
|
221
|
+
})
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
function fetchWithTimeout(ctx, url, init, timeoutMs, method, path) {
|
|
225
|
+
const fetchImpl = ctx.fetch ?? globalThis.fetch;
|
|
226
|
+
return Effect2.async((resume) => {
|
|
227
|
+
const controller = new AbortController();
|
|
228
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
229
|
+
const finish = (effect) => {
|
|
230
|
+
clearTimeout(timeoutId);
|
|
231
|
+
resume(effect);
|
|
232
|
+
};
|
|
233
|
+
void fetchImpl(url, { ...init, signal: controller.signal }).then((response) => finish(Effect2.succeed(response))).catch((cause) => {
|
|
234
|
+
if (cause instanceof Error && cause.name === "AbortError") {
|
|
235
|
+
finish(
|
|
236
|
+
Effect2.fail(new TimeoutError({ method, path, timeoutMs }))
|
|
237
|
+
);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
finish(
|
|
241
|
+
Effect2.fail(new TransportError({ method, path, cause }))
|
|
242
|
+
);
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
var buildUrl = (baseUrl, path, query) => {
|
|
247
|
+
if (path.includes("\\")) {
|
|
248
|
+
throw new TypeError("buildUrl: path must not contain backslash");
|
|
249
|
+
}
|
|
250
|
+
const url = new URL(path, baseUrl);
|
|
251
|
+
if (url.username || url.password) {
|
|
252
|
+
throw new TypeError("buildUrl: path must not contain URL userinfo");
|
|
253
|
+
}
|
|
254
|
+
if (url.origin !== baseUrl.origin) {
|
|
255
|
+
throw new TypeError(
|
|
256
|
+
`buildUrl: path "${path}" resolves to a different origin (${url.origin}) than baseUrl (${baseUrl.origin})`
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
if (query) {
|
|
260
|
+
for (const [key, value] of Object.entries(query)) {
|
|
261
|
+
if (value === null || value === void 0) continue;
|
|
262
|
+
if (Array.isArray(value)) {
|
|
263
|
+
for (const item of value) {
|
|
264
|
+
if (item === null || item === void 0) continue;
|
|
265
|
+
url.searchParams.append(key, String(item));
|
|
266
|
+
}
|
|
267
|
+
} else {
|
|
268
|
+
url.searchParams.set(key, String(value));
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return url;
|
|
273
|
+
};
|
|
274
|
+
function buildHeaders(ctx, req) {
|
|
275
|
+
const auth = ctx.auth;
|
|
276
|
+
if (!auth) {
|
|
277
|
+
return Effect2.succeed(mergeHeaders(ctx.defaultHeaders, req.headers));
|
|
278
|
+
}
|
|
279
|
+
return Effect2.gen(function* () {
|
|
280
|
+
let headers = mergeHeaders(ctx.defaultHeaders);
|
|
281
|
+
headers = yield* auth.apply(headers);
|
|
282
|
+
return mergeHeaders(headers, req.headers);
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
var sendRequest = (ctx, req) => {
|
|
286
|
+
const url = buildUrl(ctx.baseUrl, req.path, req.query);
|
|
287
|
+
const timeoutMs = req.timeoutMs ?? ctx.timeoutMs;
|
|
288
|
+
const expectedStatuses = resolveExpectedStatuses(req);
|
|
289
|
+
return buildHeaders(ctx, req).pipe(
|
|
290
|
+
Effect2.flatMap((headers) => {
|
|
291
|
+
const body = buildRequestBody(req, headers);
|
|
292
|
+
const init = {
|
|
293
|
+
method: req.method,
|
|
294
|
+
headers,
|
|
295
|
+
...body !== void 0 ? { body } : {}
|
|
296
|
+
};
|
|
297
|
+
return fetchWithTimeout(
|
|
298
|
+
ctx,
|
|
299
|
+
url,
|
|
300
|
+
init,
|
|
301
|
+
timeoutMs,
|
|
302
|
+
req.method,
|
|
303
|
+
req.path
|
|
304
|
+
).pipe(
|
|
305
|
+
Effect2.flatMap(
|
|
306
|
+
(response) => Effect2.tryPromise({
|
|
307
|
+
try: () => response.text(),
|
|
308
|
+
catch: (cause) => new TransportError({
|
|
309
|
+
method: req.method,
|
|
310
|
+
path: req.path,
|
|
311
|
+
cause
|
|
312
|
+
})
|
|
313
|
+
}).pipe(
|
|
314
|
+
Effect2.flatMap((bodyText) => {
|
|
315
|
+
if (!isExpectedStatus(response.status, expectedStatuses)) {
|
|
316
|
+
return Effect2.fail(
|
|
317
|
+
mapUnexpectedStatus(
|
|
318
|
+
req,
|
|
319
|
+
response.status,
|
|
320
|
+
bodyText,
|
|
321
|
+
expectedStatuses,
|
|
322
|
+
ctx.redact
|
|
323
|
+
)
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
return parseResponseBody(req, bodyText, ctx.redact).pipe(
|
|
327
|
+
Effect2.map((parsedBody) => ({
|
|
328
|
+
status: response.status,
|
|
329
|
+
headers: response.headers,
|
|
330
|
+
bodyText,
|
|
331
|
+
body: parsedBody
|
|
332
|
+
}))
|
|
333
|
+
);
|
|
334
|
+
})
|
|
335
|
+
)
|
|
336
|
+
)
|
|
337
|
+
);
|
|
338
|
+
})
|
|
339
|
+
);
|
|
340
|
+
};
|
|
341
|
+
var defaultShouldRetry = (error) => {
|
|
342
|
+
switch (error._tag) {
|
|
343
|
+
case "TransportError":
|
|
344
|
+
case "TimeoutError":
|
|
345
|
+
return true;
|
|
346
|
+
case "UnexpectedStatusError":
|
|
347
|
+
return error.status >= 500;
|
|
348
|
+
default:
|
|
349
|
+
return false;
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
var DEFAULT_POLICY_FIELDS = {
|
|
353
|
+
maxAttempts: 3,
|
|
354
|
+
initialDelayMs: 100,
|
|
355
|
+
maxDelayMs: 5e3,
|
|
356
|
+
factor: 2,
|
|
357
|
+
jitter: true,
|
|
358
|
+
shouldRetry: defaultShouldRetry
|
|
359
|
+
};
|
|
360
|
+
var noRetry = {
|
|
361
|
+
enabled: false,
|
|
362
|
+
...DEFAULT_POLICY_FIELDS,
|
|
363
|
+
shouldRetry: () => false
|
|
364
|
+
};
|
|
365
|
+
var exponentialRetry = (opts) => ({
|
|
366
|
+
enabled: opts.enabled ?? true,
|
|
367
|
+
maxAttempts: opts.maxAttempts ?? DEFAULT_POLICY_FIELDS.maxAttempts,
|
|
368
|
+
initialDelayMs: opts.initialDelayMs ?? DEFAULT_POLICY_FIELDS.initialDelayMs,
|
|
369
|
+
maxDelayMs: opts.maxDelayMs ?? DEFAULT_POLICY_FIELDS.maxDelayMs,
|
|
370
|
+
factor: opts.factor ?? DEFAULT_POLICY_FIELDS.factor,
|
|
371
|
+
jitter: opts.jitter ?? DEFAULT_POLICY_FIELDS.jitter,
|
|
372
|
+
shouldRetry: opts.shouldRetry ?? DEFAULT_POLICY_FIELDS.shouldRetry
|
|
373
|
+
});
|
|
374
|
+
var buildSchedule = (policy) => {
|
|
375
|
+
const base = Schedule.exponential(`${policy.initialDelayMs} millis`, policy.factor);
|
|
376
|
+
const withJitter = policy.jitter ? base.pipe(Schedule.jittered) : base;
|
|
377
|
+
const capped = withJitter.pipe(
|
|
378
|
+
Schedule.modifyDelay((_out, duration) => {
|
|
379
|
+
const ms = Duration.toMillis(duration);
|
|
380
|
+
return ms > policy.maxDelayMs ? `${policy.maxDelayMs} millis` : duration;
|
|
381
|
+
})
|
|
382
|
+
);
|
|
383
|
+
return capped.pipe(Schedule.whileInput((error) => policy.shouldRetry(error)));
|
|
384
|
+
};
|
|
385
|
+
var withRetry = (effect, policy = noRetry) => {
|
|
386
|
+
if (!policy.enabled || policy.maxAttempts <= 1) {
|
|
387
|
+
return effect;
|
|
388
|
+
}
|
|
389
|
+
const retries = Math.max(0, policy.maxAttempts - 1);
|
|
390
|
+
return Effect3.retry(effect, {
|
|
391
|
+
times: retries,
|
|
392
|
+
while: (error) => policy.shouldRetry(error),
|
|
393
|
+
schedule: buildSchedule(policy)
|
|
394
|
+
});
|
|
395
|
+
};
|
|
396
|
+
var ok = (details) => ({
|
|
397
|
+
content: [{ type: "text", text: JSON.stringify(details, null, 2) }],
|
|
398
|
+
details
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
// src/config.ts
|
|
402
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
403
|
+
var ConfigError2 = class extends Error {
|
|
404
|
+
constructor(message) {
|
|
405
|
+
super(message);
|
|
406
|
+
this.name = "ConfigError";
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
function runConfigEffect(effect) {
|
|
410
|
+
const result = Effect6.runSync(Effect6.either(effect));
|
|
411
|
+
if (result._tag === "Left") {
|
|
412
|
+
throw new ConfigError2(result.left.message);
|
|
413
|
+
}
|
|
414
|
+
return result.right;
|
|
415
|
+
}
|
|
416
|
+
function parseTlsInsecure(env) {
|
|
417
|
+
const raw = env.get("LIBRENMS_TLS_INSECURE");
|
|
418
|
+
if (!raw) return false;
|
|
419
|
+
if (["true", "1", "yes"].includes(raw.toLowerCase())) {
|
|
420
|
+
return runConfigEffect(parseBooleanEnv(env, "LIBRENMS_TLS_INSECURE", false));
|
|
421
|
+
}
|
|
422
|
+
return false;
|
|
423
|
+
}
|
|
424
|
+
function parseRequestTimeoutMs(env) {
|
|
425
|
+
return runConfigEffect(
|
|
426
|
+
parseTimeoutEnv(env, "LIBRENMS_REQUEST_TIMEOUT_MS", {
|
|
427
|
+
fallbackMs: DEFAULT_REQUEST_TIMEOUT_MS,
|
|
428
|
+
minMs: 1e3,
|
|
429
|
+
unit: "ms"
|
|
430
|
+
})
|
|
431
|
+
);
|
|
432
|
+
}
|
|
433
|
+
function resolveConfig(env) {
|
|
434
|
+
const reader = fromProcessEnv(env);
|
|
435
|
+
const url = env.LIBRENMS_URL;
|
|
436
|
+
const token = env.LIBRENMS_TOKEN;
|
|
437
|
+
if (!url) throw new ConfigError2("LIBRENMS_URL is required");
|
|
438
|
+
if (!token) throw new ConfigError2("LIBRENMS_TOKEN is required");
|
|
439
|
+
return {
|
|
440
|
+
url: url.replace(/\/+$/, ""),
|
|
441
|
+
token,
|
|
442
|
+
tlsInsecure: parseTlsInsecure(reader),
|
|
443
|
+
requestTimeoutMs: parseRequestTimeoutMs(reader)
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// src/librenms-client.ts
|
|
448
|
+
import { Effect as Effect7 } from "effect";
|
|
449
|
+
import { Agent as UndiciAgent } from "undici";
|
|
450
|
+
|
|
451
|
+
// src/error-message.ts
|
|
452
|
+
function boundaryErrorMessage(error) {
|
|
453
|
+
return error instanceof Error ? error.message : String(error);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// src/librenms-client.ts
|
|
457
|
+
var LibreNmsClientError = class extends Error {
|
|
458
|
+
constructor(status, message) {
|
|
459
|
+
super(`LibreNMS ${status}: ${message}`);
|
|
460
|
+
this.status = status;
|
|
461
|
+
this.name = "LibreNmsClientError";
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
var LibreNmsUnreachableError = class extends Error {
|
|
465
|
+
constructor(cause) {
|
|
466
|
+
super(`LibreNMS unreachable: ${cause}`);
|
|
467
|
+
this.name = "LibreNmsUnreachableError";
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
var LibreNmsClient = class {
|
|
471
|
+
constructor(cfg, opts = {}) {
|
|
472
|
+
this.cfg = cfg;
|
|
473
|
+
this.retryDelayMs = opts.retryDelayMs ?? 1e3;
|
|
474
|
+
this.fetchImpl = opts.fetch ?? fetch;
|
|
475
|
+
if (cfg.tlsInsecure && cfg.url.startsWith("https://")) {
|
|
476
|
+
this.dispatcher = new UndiciAgent({ connect: { rejectUnauthorized: false } });
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
retryDelayMs;
|
|
480
|
+
fetchImpl;
|
|
481
|
+
// Node's global fetch (undici) ignores node:https.Agent. To actually skip
|
|
482
|
+
// cert verification for self-signed LibreNMS hosts we pass an undici Agent
|
|
483
|
+
// via the `dispatcher` init option.
|
|
484
|
+
dispatcher;
|
|
485
|
+
async get(path) {
|
|
486
|
+
return this.request("GET", path);
|
|
487
|
+
}
|
|
488
|
+
async post(path, body) {
|
|
489
|
+
return this.request("POST", path, body);
|
|
490
|
+
}
|
|
491
|
+
async put(path, body) {
|
|
492
|
+
return this.request("PUT", path, body);
|
|
493
|
+
}
|
|
494
|
+
async delete(path) {
|
|
495
|
+
return this.request("DELETE", path);
|
|
496
|
+
}
|
|
497
|
+
async request(method, path, body) {
|
|
498
|
+
const baseUrl = new URL(`${this.cfg.url}/`);
|
|
499
|
+
const requestPath = `api/v0${path}`;
|
|
500
|
+
const auth = {
|
|
501
|
+
apply: (headers) => {
|
|
502
|
+
headers.set("x-auth-token", this.cfg.token);
|
|
503
|
+
return Effect7.succeed(headers);
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
const req = {
|
|
507
|
+
method,
|
|
508
|
+
path: requestPath,
|
|
509
|
+
body,
|
|
510
|
+
bodyEncoding: body !== void 0 ? "json" : "none",
|
|
511
|
+
statusMapper: ({ status, method: mappedMethod, path: mappedPath, bodyText, expectedStatuses }) => new UnexpectedStatusError({
|
|
512
|
+
method: mappedMethod,
|
|
513
|
+
path: mappedPath,
|
|
514
|
+
status,
|
|
515
|
+
body: bodyText,
|
|
516
|
+
expected: expectedStatuses
|
|
517
|
+
})
|
|
518
|
+
};
|
|
519
|
+
const ctx = {
|
|
520
|
+
baseUrl,
|
|
521
|
+
auth,
|
|
522
|
+
timeoutMs: this.cfg.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
523
|
+
fetch: this.fetchWithDispatcher,
|
|
524
|
+
redact: (value) => value
|
|
525
|
+
};
|
|
526
|
+
let result;
|
|
527
|
+
try {
|
|
528
|
+
result = await Effect7.runPromise(
|
|
529
|
+
Effect7.either(
|
|
530
|
+
withRetry(
|
|
531
|
+
sendRequest(ctx, req),
|
|
532
|
+
exponentialRetry({
|
|
533
|
+
maxAttempts: 2,
|
|
534
|
+
initialDelayMs: this.retryDelayMs,
|
|
535
|
+
maxDelayMs: this.retryDelayMs,
|
|
536
|
+
factor: 1,
|
|
537
|
+
jitter: false,
|
|
538
|
+
shouldRetry: shouldRetryLibreNmsRequest
|
|
539
|
+
})
|
|
540
|
+
)
|
|
541
|
+
)
|
|
542
|
+
);
|
|
543
|
+
} catch (error) {
|
|
544
|
+
throw new LibreNmsUnreachableError(boundaryErrorMessage(error));
|
|
545
|
+
}
|
|
546
|
+
if (result._tag === "Right") {
|
|
547
|
+
return result.right.body;
|
|
548
|
+
}
|
|
549
|
+
throw mapLibreNmsRequestError(result.left);
|
|
550
|
+
}
|
|
551
|
+
fetchWithDispatcher = (input, init = {}) => {
|
|
552
|
+
if (!this.dispatcher) return this.fetchImpl(input, init);
|
|
553
|
+
return this.fetchImpl(input, { ...init, dispatcher: this.dispatcher });
|
|
554
|
+
};
|
|
555
|
+
};
|
|
556
|
+
function shouldRetryLibreNmsRequest(error) {
|
|
557
|
+
if (error instanceof TransportError) return true;
|
|
558
|
+
if (error instanceof ParseError) return true;
|
|
559
|
+
if (error instanceof UnexpectedStatusError) return error.status >= 500;
|
|
560
|
+
return false;
|
|
561
|
+
}
|
|
562
|
+
function mapLibreNmsRequestError(error) {
|
|
563
|
+
if (error instanceof UnexpectedStatusError) {
|
|
564
|
+
if (error.status >= 500) return new LibreNmsUnreachableError(`HTTP ${error.status}`);
|
|
565
|
+
return new LibreNmsClientError(error.status, responseErrorMessage(error.body));
|
|
566
|
+
}
|
|
567
|
+
if (error instanceof TimeoutError) {
|
|
568
|
+
return new LibreNmsUnreachableError(
|
|
569
|
+
`${error.method} ${error.path} timed out after ${error.timeoutMs}ms`
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
if (error instanceof TransportError) {
|
|
573
|
+
const cause = error.cause;
|
|
574
|
+
return new LibreNmsUnreachableError(boundaryErrorMessage(cause));
|
|
575
|
+
}
|
|
576
|
+
if (error instanceof ParseError) {
|
|
577
|
+
return new LibreNmsUnreachableError(boundaryErrorMessage(error.cause ?? error.message));
|
|
578
|
+
}
|
|
579
|
+
return new LibreNmsUnreachableError(boundaryErrorMessage(error));
|
|
580
|
+
}
|
|
581
|
+
function responseErrorMessage(bodyText) {
|
|
582
|
+
try {
|
|
583
|
+
return JSON.parse(bodyText).message ?? bodyText;
|
|
584
|
+
} catch {
|
|
585
|
+
return bodyText;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// src/security.ts
|
|
590
|
+
var SECRETS = /* @__PURE__ */ new Set();
|
|
591
|
+
var BASE64_TOKEN_RE = /[A-Za-z0-9+/=]{12,}/g;
|
|
592
|
+
function registerSecret(s) {
|
|
593
|
+
if (s && s.length > 0) SECRETS.add(s);
|
|
594
|
+
}
|
|
595
|
+
function maskString(s) {
|
|
596
|
+
let out = s;
|
|
597
|
+
for (const secret of SECRETS) {
|
|
598
|
+
if (out.includes(secret)) out = out.split(secret).join("REDACTED");
|
|
599
|
+
}
|
|
600
|
+
out = out.replace(BASE64_TOKEN_RE, (token) => {
|
|
601
|
+
try {
|
|
602
|
+
const decoded = Buffer.from(token, "base64").toString("utf8");
|
|
603
|
+
for (const secret of SECRETS) {
|
|
604
|
+
if (decoded.includes(secret)) return "REDACTED";
|
|
605
|
+
}
|
|
606
|
+
} catch {
|
|
607
|
+
}
|
|
608
|
+
return token;
|
|
609
|
+
});
|
|
610
|
+
return out;
|
|
611
|
+
}
|
|
612
|
+
function redact(value) {
|
|
613
|
+
if (typeof value === "string") return maskString(value);
|
|
614
|
+
if (Array.isArray(value)) return value.map(redact);
|
|
615
|
+
if (value && typeof value === "object") {
|
|
616
|
+
const out = {};
|
|
617
|
+
for (const [k, v] of Object.entries(value)) out[k] = redact(v);
|
|
618
|
+
return out;
|
|
619
|
+
}
|
|
620
|
+
return value;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// src/validate.ts
|
|
624
|
+
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
625
|
+
var ValidationError = class extends Error {
|
|
626
|
+
constructor(message) {
|
|
627
|
+
super(message);
|
|
628
|
+
this.name = "ValidationError";
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
var compiledCache = /* @__PURE__ */ new WeakMap();
|
|
632
|
+
function getChecker(schema) {
|
|
633
|
+
let checker = compiledCache.get(schema);
|
|
634
|
+
if (!checker) {
|
|
635
|
+
checker = TypeCompiler.Compile(schema);
|
|
636
|
+
compiledCache.set(schema, checker);
|
|
637
|
+
}
|
|
638
|
+
return checker;
|
|
639
|
+
}
|
|
640
|
+
function validateToolArgs(schema, toolName, args) {
|
|
641
|
+
const checker = getChecker(schema);
|
|
642
|
+
if (checker.Check(args)) return;
|
|
643
|
+
const first = checker.Errors(args).First();
|
|
644
|
+
const where = first?.path ? ` at ${first.path}` : "";
|
|
645
|
+
const detail = first ? `${first.message}${where}` : "schema mismatch";
|
|
646
|
+
throw new ValidationError(
|
|
647
|
+
`Invalid arguments for ${toolName}: ${detail}`
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// mcp-server.ts
|
|
652
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
653
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
654
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
655
|
+
|
|
656
|
+
// src/tools/librenms_status.ts
|
|
657
|
+
import { Type } from "@sinclair/typebox";
|
|
658
|
+
|
|
659
|
+
// src/tools/_util.ts
|
|
660
|
+
function jsonToolResult(payload) {
|
|
661
|
+
const r = ok(payload);
|
|
662
|
+
return { content: r.content };
|
|
663
|
+
}
|
|
664
|
+
function safeInt(value, label, opts = {}) {
|
|
665
|
+
const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
|
|
666
|
+
if (!Number.isInteger(n)) {
|
|
667
|
+
throw new Error(`${label} must be an integer, got: ${String(value)}`);
|
|
668
|
+
}
|
|
669
|
+
const min = opts.min ?? 1;
|
|
670
|
+
if (n < min) throw new Error(`${label} must be >= ${min}, got: ${n}`);
|
|
671
|
+
if (opts.max !== void 0 && n > opts.max) {
|
|
672
|
+
throw new Error(`${label} must be <= ${opts.max}, got: ${n}`);
|
|
673
|
+
}
|
|
674
|
+
return n;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// src/tools/librenms_status.ts
|
|
678
|
+
var Schema = Type.Object({}, { additionalProperties: false });
|
|
679
|
+
function createLibrenmsStatusTool(getClient) {
|
|
680
|
+
return {
|
|
681
|
+
name: "librenms_status",
|
|
682
|
+
label: "librenms: status",
|
|
683
|
+
description: "LibreNMS system health (version, totals, last poll) via GET /api/v0/system.",
|
|
684
|
+
parameters: Schema,
|
|
685
|
+
execute: async () => {
|
|
686
|
+
const client = getClient();
|
|
687
|
+
const r = await client.get("/system");
|
|
688
|
+
return jsonToolResult({ system: r.system?.[0] ?? null });
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// src/tools/librenms_list_devices.ts
|
|
694
|
+
import { Type as Type2 } from "@sinclair/typebox";
|
|
695
|
+
var Schema2 = Type2.Object(
|
|
696
|
+
{
|
|
697
|
+
type: Type2.Optional(
|
|
698
|
+
Type2.Union(
|
|
699
|
+
[
|
|
700
|
+
Type2.Literal("all"),
|
|
701
|
+
Type2.Literal("up"),
|
|
702
|
+
Type2.Literal("down"),
|
|
703
|
+
Type2.Literal("ignored"),
|
|
704
|
+
Type2.Literal("disabled")
|
|
705
|
+
],
|
|
706
|
+
{ description: "Device filter type. Default 'all'." }
|
|
707
|
+
)
|
|
708
|
+
)
|
|
709
|
+
},
|
|
710
|
+
{ additionalProperties: false }
|
|
711
|
+
);
|
|
712
|
+
function createLibrenmsListDevicesTool(getClient) {
|
|
713
|
+
return {
|
|
714
|
+
name: "librenms_list_devices",
|
|
715
|
+
label: "librenms: list devices",
|
|
716
|
+
description: "List devices monitored by LibreNMS via GET /api/v0/devices. Optional type filter (all|up|down|ignored|disabled).",
|
|
717
|
+
parameters: Schema2,
|
|
718
|
+
execute: async (_id, raw) => {
|
|
719
|
+
const args = raw ?? {};
|
|
720
|
+
const path = args.type ? `/devices?type=${encodeURIComponent(args.type)}` : "/devices";
|
|
721
|
+
const client = getClient();
|
|
722
|
+
const r = await client.get(path);
|
|
723
|
+
return jsonToolResult({ devices: r.devices ?? [] });
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// src/tools/librenms_get_device.ts
|
|
729
|
+
import { Type as Type3 } from "@sinclair/typebox";
|
|
730
|
+
var Schema3 = Type3.Object(
|
|
731
|
+
{
|
|
732
|
+
hostname: Type3.String({
|
|
733
|
+
description: "Device hostname or IP as configured in LibreNMS."
|
|
734
|
+
})
|
|
735
|
+
},
|
|
736
|
+
{ additionalProperties: false }
|
|
737
|
+
);
|
|
738
|
+
function createLibrenmsGetDeviceTool(getClient) {
|
|
739
|
+
return {
|
|
740
|
+
name: "librenms_get_device",
|
|
741
|
+
label: "librenms: get device",
|
|
742
|
+
description: "Fetch a single device by hostname via GET /api/v0/devices/{hostname}.",
|
|
743
|
+
parameters: Schema3,
|
|
744
|
+
execute: async (_id, raw) => {
|
|
745
|
+
const args = raw;
|
|
746
|
+
const client = getClient();
|
|
747
|
+
const r = await client.get(`/devices/${encodeURIComponent(args.hostname)}`);
|
|
748
|
+
return jsonToolResult({ device: r.devices?.[0] ?? null });
|
|
749
|
+
}
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
// src/tools/librenms_list_ports.ts
|
|
754
|
+
import { Type as Type4 } from "@sinclair/typebox";
|
|
755
|
+
var Schema4 = Type4.Object(
|
|
756
|
+
{
|
|
757
|
+
hostname: Type4.String({
|
|
758
|
+
description: "Device hostname or IP as configured in LibreNMS."
|
|
759
|
+
})
|
|
760
|
+
},
|
|
761
|
+
{ additionalProperties: false }
|
|
762
|
+
);
|
|
763
|
+
var COLUMNS = "ifName,ifAdminStatus,ifOperStatus,ifInErrors,ifOutErrors,ifSpeed,ifDescr";
|
|
764
|
+
function createLibrenmsListPortsTool(getClient) {
|
|
765
|
+
return {
|
|
766
|
+
name: "librenms_list_ports",
|
|
767
|
+
label: "librenms: list ports",
|
|
768
|
+
description: "List ports on a device via GET /api/v0/devices/{hostname}/ports with a fixed column set (name, status, errors, speed, descr).",
|
|
769
|
+
parameters: Schema4,
|
|
770
|
+
execute: async (_id, raw) => {
|
|
771
|
+
const args = raw;
|
|
772
|
+
const client = getClient();
|
|
773
|
+
const r = await client.get(`/devices/${encodeURIComponent(args.hostname)}/ports?columns=${COLUMNS}`);
|
|
774
|
+
return jsonToolResult({ ports: r.ports ?? [] });
|
|
775
|
+
}
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
// src/tools/librenms_port_health.ts
|
|
780
|
+
import { Type as Type5 } from "@sinclair/typebox";
|
|
781
|
+
var Schema5 = Type5.Object(
|
|
782
|
+
{
|
|
783
|
+
limit: Type5.Optional(
|
|
784
|
+
Type5.Integer({
|
|
785
|
+
minimum: 1,
|
|
786
|
+
description: "Number of top ports to return. Default 10."
|
|
787
|
+
})
|
|
788
|
+
),
|
|
789
|
+
metric: Type5.Optional(
|
|
790
|
+
Type5.Union(
|
|
791
|
+
[
|
|
792
|
+
Type5.Literal("errors_in"),
|
|
793
|
+
Type5.Literal("errors_out"),
|
|
794
|
+
Type5.Literal("utilization")
|
|
795
|
+
],
|
|
796
|
+
{ description: "Ranking metric. Default 'errors_in'." }
|
|
797
|
+
)
|
|
798
|
+
)
|
|
799
|
+
},
|
|
800
|
+
{ additionalProperties: false }
|
|
801
|
+
);
|
|
802
|
+
var COLUMNS2 = "device_id,ifName,ifInErrors,ifOutErrors,ifSpeed,ifInOctets,ifOutOctets";
|
|
803
|
+
function createLibrenmsPortHealthTool(getClient) {
|
|
804
|
+
return {
|
|
805
|
+
name: "librenms_port_health",
|
|
806
|
+
label: "librenms: port health",
|
|
807
|
+
description: "Rank ports by errors_in (default), errors_out, or utilization via GET /api/v0/ports with client-side sort.",
|
|
808
|
+
parameters: Schema5,
|
|
809
|
+
execute: async (_id, raw) => {
|
|
810
|
+
const args = raw ?? {};
|
|
811
|
+
const limit = args.limit ?? 10;
|
|
812
|
+
const metric = args.metric ?? "errors_in";
|
|
813
|
+
const client = getClient();
|
|
814
|
+
const r = await client.get(`/ports?columns=${COLUMNS2}`);
|
|
815
|
+
const ports = r.ports ?? [];
|
|
816
|
+
const sorted = ports.slice().sort((a, b) => {
|
|
817
|
+
if (metric === "errors_in") {
|
|
818
|
+
return (b.ifInErrors ?? 0) - (a.ifInErrors ?? 0);
|
|
819
|
+
}
|
|
820
|
+
if (metric === "errors_out") {
|
|
821
|
+
return (b.ifOutErrors ?? 0) - (a.ifOutErrors ?? 0);
|
|
822
|
+
}
|
|
823
|
+
const aUtil = a.ifSpeed ? ((a.ifInOctets ?? 0) + (a.ifOutOctets ?? 0)) / a.ifSpeed : 0;
|
|
824
|
+
const bUtil = b.ifSpeed ? ((b.ifInOctets ?? 0) + (b.ifOutOctets ?? 0)) / b.ifSpeed : 0;
|
|
825
|
+
return bUtil - aUtil;
|
|
826
|
+
});
|
|
827
|
+
return jsonToolResult({ metric, limit, top: sorted.slice(0, limit) });
|
|
828
|
+
}
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// src/tools/librenms_list_alerts.ts
|
|
833
|
+
import { Type as Type6 } from "@sinclair/typebox";
|
|
834
|
+
var Schema6 = Type6.Object(
|
|
835
|
+
{
|
|
836
|
+
state: Type6.Optional(
|
|
837
|
+
Type6.Union(
|
|
838
|
+
[Type6.Literal(0), Type6.Literal(1), Type6.Literal(2)],
|
|
839
|
+
{ description: "Alert state filter: 0=ok, 1=active, 2=ack." }
|
|
840
|
+
)
|
|
841
|
+
)
|
|
842
|
+
},
|
|
843
|
+
{ additionalProperties: false }
|
|
844
|
+
);
|
|
845
|
+
function createLibrenmsListAlertsTool(getClient) {
|
|
846
|
+
return {
|
|
847
|
+
name: "librenms_list_alerts",
|
|
848
|
+
label: "librenms: list alerts",
|
|
849
|
+
description: "List alerts via GET /api/v0/alerts. Optional state filter (0=ok, 1=active, 2=ack).",
|
|
850
|
+
parameters: Schema6,
|
|
851
|
+
execute: async (_id, raw) => {
|
|
852
|
+
const args = raw ?? {};
|
|
853
|
+
const path = args.state !== void 0 ? `/alerts?state=${encodeURIComponent(args.state)}` : "/alerts";
|
|
854
|
+
const client = getClient();
|
|
855
|
+
const r = await client.get(path);
|
|
856
|
+
return jsonToolResult({ alerts: r.alerts ?? [] });
|
|
857
|
+
}
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// src/tools/librenms_get_alert.ts
|
|
862
|
+
import { Type as Type7 } from "@sinclair/typebox";
|
|
863
|
+
var Schema7 = Type7.Object(
|
|
864
|
+
{
|
|
865
|
+
id: Type7.Integer({ minimum: 1, description: "Alert id." })
|
|
866
|
+
},
|
|
867
|
+
{ additionalProperties: false }
|
|
868
|
+
);
|
|
869
|
+
function createLibrenmsGetAlertTool(getClient) {
|
|
870
|
+
return {
|
|
871
|
+
name: "librenms_get_alert",
|
|
872
|
+
label: "librenms: get alert",
|
|
873
|
+
description: "Fetch a single alert by id via GET /api/v0/alerts/{id}.",
|
|
874
|
+
parameters: Schema7,
|
|
875
|
+
execute: async (_id, raw) => {
|
|
876
|
+
const args = raw;
|
|
877
|
+
const id = safeInt(args.id, "id");
|
|
878
|
+
const client = getClient();
|
|
879
|
+
const r = await client.get(`/alerts/${encodeURIComponent(id)}`);
|
|
880
|
+
return jsonToolResult({ alert: r.alerts?.[0] ?? null });
|
|
881
|
+
}
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// src/tools/librenms_alert_history.ts
|
|
886
|
+
import { Type as Type8 } from "@sinclair/typebox";
|
|
887
|
+
var Schema8 = Type8.Object(
|
|
888
|
+
{
|
|
889
|
+
device_id: Type8.Optional(
|
|
890
|
+
Type8.Integer({
|
|
891
|
+
minimum: 1,
|
|
892
|
+
description: "Optional device id to scope the alert log."
|
|
893
|
+
})
|
|
894
|
+
),
|
|
895
|
+
limit: Type8.Optional(
|
|
896
|
+
Type8.Integer({
|
|
897
|
+
minimum: 1,
|
|
898
|
+
description: "Max number of log entries. Default 25."
|
|
899
|
+
})
|
|
900
|
+
)
|
|
901
|
+
},
|
|
902
|
+
{ additionalProperties: false }
|
|
903
|
+
);
|
|
904
|
+
function createLibrenmsAlertHistoryTool(getClient) {
|
|
905
|
+
return {
|
|
906
|
+
name: "librenms_alert_history",
|
|
907
|
+
label: "librenms: alert history",
|
|
908
|
+
description: "Recent alert log entries via GET /api/v0/logs/alertlog (optionally scoped to a device_id).",
|
|
909
|
+
parameters: Schema8,
|
|
910
|
+
execute: async (_id, raw) => {
|
|
911
|
+
const args = raw ?? {};
|
|
912
|
+
const limit = safeInt(args.limit ?? 25, "limit");
|
|
913
|
+
const path = args.device_id !== void 0 ? `/logs/alertlog/${encodeURIComponent(
|
|
914
|
+
safeInt(args.device_id, "device_id")
|
|
915
|
+
)}?limit=${encodeURIComponent(limit)}` : `/logs/alertlog?limit=${encodeURIComponent(limit)}`;
|
|
916
|
+
const client = getClient();
|
|
917
|
+
const r = await client.get(path);
|
|
918
|
+
return jsonToolResult({
|
|
919
|
+
count: r.logs?.length ?? 0,
|
|
920
|
+
logs: r.logs ?? []
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
// src/tools/librenms_ack_alert.ts
|
|
927
|
+
import { Type as Type9 } from "@sinclair/typebox";
|
|
928
|
+
|
|
929
|
+
// src/gates.ts
|
|
930
|
+
var WriteGateError = class extends Error {
|
|
931
|
+
constructor(message) {
|
|
932
|
+
super(message);
|
|
933
|
+
this.name = "WriteGateError";
|
|
934
|
+
}
|
|
935
|
+
};
|
|
936
|
+
function assertConfirmedWrite(args, toolName) {
|
|
937
|
+
if (args.confirm !== true) {
|
|
938
|
+
throw new WriteGateError(`${toolName} is a write operation. Pass {"confirm": true} to proceed.`);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
// src/tools/librenms_ack_alert.ts
|
|
943
|
+
var Schema9 = Type9.Object(
|
|
944
|
+
{
|
|
945
|
+
id: Type9.Integer({ minimum: 1, description: "Alert id to acknowledge." }),
|
|
946
|
+
note: Type9.Optional(
|
|
947
|
+
Type9.String({ description: "Optional acknowledgement note." })
|
|
948
|
+
),
|
|
949
|
+
until_clear: Type9.Optional(
|
|
950
|
+
Type9.Boolean({
|
|
951
|
+
description: "When true, the ack persists until the alert clears (default LibreNMS behavior: ack until next state change)."
|
|
952
|
+
})
|
|
953
|
+
),
|
|
954
|
+
confirm: Type9.Boolean({
|
|
955
|
+
description: "Must be true to write. Tier-2 safe-write gate."
|
|
956
|
+
})
|
|
957
|
+
},
|
|
958
|
+
{ additionalProperties: false }
|
|
959
|
+
);
|
|
960
|
+
var NAME = "librenms_ack_alert";
|
|
961
|
+
function createLibrenmsAckAlertTool(getClient) {
|
|
962
|
+
return {
|
|
963
|
+
name: NAME,
|
|
964
|
+
label: "librenms: ack alert",
|
|
965
|
+
description: "Acknowledge an active alert by id via PUT /api/v0/alerts/{id}. Tier-2 write; requires confirm:true.",
|
|
966
|
+
parameters: Schema9,
|
|
967
|
+
execute: async (_id, raw) => {
|
|
968
|
+
assertConfirmedWrite(raw, NAME);
|
|
969
|
+
const args = raw;
|
|
970
|
+
const id = safeInt(args.id, "id");
|
|
971
|
+
const client = getClient();
|
|
972
|
+
const body = {};
|
|
973
|
+
if (args.note !== void 0) body.note = args.note;
|
|
974
|
+
if (args.until_clear !== void 0) body.until_clear = args.until_clear;
|
|
975
|
+
const r = await client.put(`/alerts/${encodeURIComponent(id)}`, body);
|
|
976
|
+
return jsonToolResult({ alert_id: id, acked: true, response: r });
|
|
977
|
+
}
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// src/tools/librenms_set_maintenance.ts
|
|
982
|
+
import { Type as Type10 } from "@sinclair/typebox";
|
|
983
|
+
var DURATION_RE = /^\d+:\d{2}$/;
|
|
984
|
+
var START_RE = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
|
|
985
|
+
var Schema10 = Type10.Object(
|
|
986
|
+
{
|
|
987
|
+
hostname: Type10.String({
|
|
988
|
+
description: "Device hostname or IP as configured in LibreNMS."
|
|
989
|
+
}),
|
|
990
|
+
duration: Type10.String({
|
|
991
|
+
description: "Maintenance duration. LibreNMS format `H:i`, e.g. `2:00` for 2 hours or `0:30` for 30 minutes."
|
|
992
|
+
}),
|
|
993
|
+
title: Type10.Optional(
|
|
994
|
+
Type10.String({ description: "Maintenance window title." })
|
|
995
|
+
),
|
|
996
|
+
notes: Type10.Optional(Type10.String({ description: "Free-text notes." })),
|
|
997
|
+
start: Type10.Optional(
|
|
998
|
+
Type10.String({
|
|
999
|
+
description: "Start time. LibreNMS format `Y-m-d H:i:00`, e.g. `2026-05-17 14:30:00`. Default: server now."
|
|
1000
|
+
})
|
|
1001
|
+
),
|
|
1002
|
+
confirm: Type10.Boolean({
|
|
1003
|
+
description: "Must be true to write. Tier-2 safe-write gate."
|
|
1004
|
+
})
|
|
1005
|
+
},
|
|
1006
|
+
{ additionalProperties: false }
|
|
1007
|
+
);
|
|
1008
|
+
var NAME2 = "librenms_set_maintenance";
|
|
1009
|
+
function createLibrenmsSetMaintenanceTool(getClient) {
|
|
1010
|
+
return {
|
|
1011
|
+
name: NAME2,
|
|
1012
|
+
label: "librenms: set maintenance",
|
|
1013
|
+
description: "Put a device into a maintenance window (suppresses alerts) via POST /api/v0/devices/{hostname}/maintenance. Tier-2 write; requires confirm:true.",
|
|
1014
|
+
parameters: Schema10,
|
|
1015
|
+
execute: async (_id, raw) => {
|
|
1016
|
+
assertConfirmedWrite(raw, NAME2);
|
|
1017
|
+
const args = raw;
|
|
1018
|
+
if (!DURATION_RE.test(args.duration)) {
|
|
1019
|
+
throw new Error(
|
|
1020
|
+
`duration must be H:i format (e.g. "2:00" or "0:30"), got: ${args.duration}`
|
|
1021
|
+
);
|
|
1022
|
+
}
|
|
1023
|
+
if (args.start && !START_RE.test(args.start)) {
|
|
1024
|
+
throw new Error(
|
|
1025
|
+
`start must be Y-m-d H:i:00 format (e.g. "2026-05-17 14:30:00"), got: ${args.start}`
|
|
1026
|
+
);
|
|
1027
|
+
}
|
|
1028
|
+
const client = getClient();
|
|
1029
|
+
const body = { duration: args.duration };
|
|
1030
|
+
if (args.title) body.title = args.title;
|
|
1031
|
+
if (args.notes) body.notes = args.notes;
|
|
1032
|
+
if (args.start) body.start = args.start;
|
|
1033
|
+
const r = await client.post(
|
|
1034
|
+
`/devices/${encodeURIComponent(args.hostname)}/maintenance`,
|
|
1035
|
+
body
|
|
1036
|
+
);
|
|
1037
|
+
return jsonToolResult({ hostname: args.hostname, maintenance: r });
|
|
1038
|
+
}
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
// src/tools/librenms_get_port.ts
|
|
1043
|
+
import { Type as Type11 } from "@sinclair/typebox";
|
|
1044
|
+
var Schema11 = Type11.Object(
|
|
1045
|
+
{
|
|
1046
|
+
port_id: Type11.Integer({
|
|
1047
|
+
minimum: 1,
|
|
1048
|
+
description: "LibreNMS internal port id (from librenms_list_ports response rows)."
|
|
1049
|
+
})
|
|
1050
|
+
},
|
|
1051
|
+
{ additionalProperties: false }
|
|
1052
|
+
);
|
|
1053
|
+
function createLibrenmsGetPortTool(getClient) {
|
|
1054
|
+
return {
|
|
1055
|
+
name: "librenms_get_port",
|
|
1056
|
+
label: "librenms: get port",
|
|
1057
|
+
description: "Single-port detail via GET /api/v0/ports/{port_id}. Returns full column set (admin/oper state, traffic + error counters, ifAlias, etc.).",
|
|
1058
|
+
parameters: Schema11,
|
|
1059
|
+
execute: async (_id, raw) => {
|
|
1060
|
+
const args = raw;
|
|
1061
|
+
const portId = safeInt(args.port_id, "port_id");
|
|
1062
|
+
const client = getClient();
|
|
1063
|
+
const r = await client.get(`/ports/${encodeURIComponent(portId)}`);
|
|
1064
|
+
return jsonToolResult({ port: r.port?.[0] ?? null });
|
|
1065
|
+
}
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
// src/tools/librenms_event_log.ts
|
|
1070
|
+
import { Type as Type12 } from "@sinclair/typebox";
|
|
1071
|
+
var Schema12 = Type12.Object(
|
|
1072
|
+
{
|
|
1073
|
+
device_id: Type12.Optional(
|
|
1074
|
+
Type12.Integer({
|
|
1075
|
+
minimum: 1,
|
|
1076
|
+
description: "Optional device id to scope the event log."
|
|
1077
|
+
})
|
|
1078
|
+
),
|
|
1079
|
+
limit: Type12.Optional(
|
|
1080
|
+
Type12.Integer({
|
|
1081
|
+
minimum: 1,
|
|
1082
|
+
description: "Max number of log entries. Default 25."
|
|
1083
|
+
})
|
|
1084
|
+
)
|
|
1085
|
+
},
|
|
1086
|
+
{ additionalProperties: false }
|
|
1087
|
+
);
|
|
1088
|
+
function createLibrenmsEventLogTool(getClient) {
|
|
1089
|
+
return {
|
|
1090
|
+
name: "librenms_event_log",
|
|
1091
|
+
label: "librenms: event log",
|
|
1092
|
+
description: "Recent device events via GET /api/v0/logs/eventlog (optionally scoped to a device_id). Covers device up/down, syslog ingestion, etc. Distinct from alertlog.",
|
|
1093
|
+
parameters: Schema12,
|
|
1094
|
+
execute: async (_id, raw) => {
|
|
1095
|
+
const args = raw ?? {};
|
|
1096
|
+
const limit = safeInt(args.limit ?? 25, "limit");
|
|
1097
|
+
const path = args.device_id !== void 0 ? `/logs/eventlog/${encodeURIComponent(
|
|
1098
|
+
safeInt(args.device_id, "device_id")
|
|
1099
|
+
)}?limit=${encodeURIComponent(limit)}` : `/logs/eventlog?limit=${encodeURIComponent(limit)}`;
|
|
1100
|
+
const client = getClient();
|
|
1101
|
+
const r = await client.get(path);
|
|
1102
|
+
return jsonToolResult({
|
|
1103
|
+
count: r.logs?.length ?? 0,
|
|
1104
|
+
logs: r.logs ?? []
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
// src/tools/librenms_unmute_alert.ts
|
|
1111
|
+
import { Type as Type13 } from "@sinclair/typebox";
|
|
1112
|
+
var Schema13 = Type13.Object(
|
|
1113
|
+
{
|
|
1114
|
+
id: Type13.Integer({ minimum: 1, description: "Alert id to unmute." }),
|
|
1115
|
+
note: Type13.Optional(
|
|
1116
|
+
Type13.String({
|
|
1117
|
+
description: "Optional note appended to the alert audit trail (LibreNMS prefixes it with the API user + timestamp)."
|
|
1118
|
+
})
|
|
1119
|
+
),
|
|
1120
|
+
confirm: Type13.Boolean({
|
|
1121
|
+
description: "Must be true to write. Tier-2 safe-write gate."
|
|
1122
|
+
})
|
|
1123
|
+
},
|
|
1124
|
+
{ additionalProperties: false }
|
|
1125
|
+
);
|
|
1126
|
+
var NAME3 = "librenms_unmute_alert";
|
|
1127
|
+
function createLibrenmsUnmuteAlertTool(getClient) {
|
|
1128
|
+
return {
|
|
1129
|
+
name: NAME3,
|
|
1130
|
+
label: "librenms: unmute alert",
|
|
1131
|
+
description: "Unmute an alert by id via PUT /api/v0/alerts/unmute/{id} (companion to librenms_ack_alert). Tier-2 write; requires confirm:true.",
|
|
1132
|
+
parameters: Schema13,
|
|
1133
|
+
execute: async (_id, raw) => {
|
|
1134
|
+
assertConfirmedWrite(raw, NAME3);
|
|
1135
|
+
const args = raw;
|
|
1136
|
+
const id = safeInt(args.id, "id");
|
|
1137
|
+
const client = getClient();
|
|
1138
|
+
const body = {};
|
|
1139
|
+
if (args.note !== void 0) body.note = args.note;
|
|
1140
|
+
const r = await client.put(`/alerts/unmute/${encodeURIComponent(id)}`, body);
|
|
1141
|
+
return jsonToolResult({ alert_id: id, unmuted: true, response: r });
|
|
1142
|
+
}
|
|
1143
|
+
};
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
// mcp-server.ts
|
|
1147
|
+
function createServer() {
|
|
1148
|
+
const cfg = resolveConfig(process.env);
|
|
1149
|
+
registerSecret(cfg.token);
|
|
1150
|
+
const getClient = () => new LibreNmsClient(cfg);
|
|
1151
|
+
const tools = [
|
|
1152
|
+
createLibrenmsStatusTool(getClient),
|
|
1153
|
+
createLibrenmsListDevicesTool(getClient),
|
|
1154
|
+
createLibrenmsGetDeviceTool(getClient),
|
|
1155
|
+
createLibrenmsListPortsTool(getClient),
|
|
1156
|
+
createLibrenmsPortHealthTool(getClient),
|
|
1157
|
+
createLibrenmsListAlertsTool(getClient),
|
|
1158
|
+
createLibrenmsGetAlertTool(getClient),
|
|
1159
|
+
createLibrenmsAlertHistoryTool(getClient),
|
|
1160
|
+
createLibrenmsAckAlertTool(getClient),
|
|
1161
|
+
createLibrenmsSetMaintenanceTool(getClient),
|
|
1162
|
+
createLibrenmsGetPortTool(getClient),
|
|
1163
|
+
createLibrenmsEventLogTool(getClient),
|
|
1164
|
+
createLibrenmsUnmuteAlertTool(getClient)
|
|
1165
|
+
];
|
|
1166
|
+
const toolMap = new Map(tools.map((t) => [t.name, t]));
|
|
1167
|
+
const server = new Server({ name: "librenms-mcp", version: "0.2.2" }, { capabilities: { tools: {} } });
|
|
1168
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
1169
|
+
tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.parameters }))
|
|
1170
|
+
}));
|
|
1171
|
+
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
1172
|
+
const t = toolMap.get(req.params.name);
|
|
1173
|
+
if (!t) {
|
|
1174
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: `unknown tool: ${req.params.name}` }) }], isError: true };
|
|
1175
|
+
}
|
|
1176
|
+
try {
|
|
1177
|
+
const args = req.params.arguments ?? {};
|
|
1178
|
+
validateToolArgs(t.parameters, t.name, args);
|
|
1179
|
+
return await t.execute(req.params.name, args);
|
|
1180
|
+
} catch (e) {
|
|
1181
|
+
return mcpErrorResult(e);
|
|
1182
|
+
}
|
|
1183
|
+
});
|
|
1184
|
+
return server;
|
|
1185
|
+
}
|
|
1186
|
+
function mcpErrorResult(error) {
|
|
1187
|
+
const msg = redact(boundaryErrorMessage(error));
|
|
1188
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: msg }) }], isError: true };
|
|
1189
|
+
}
|
|
1190
|
+
async function serve() {
|
|
1191
|
+
const server = createServer();
|
|
1192
|
+
const transport = new StdioServerTransport();
|
|
1193
|
+
const __send = transport.send.bind(transport);
|
|
1194
|
+
transport.send = (message) => {
|
|
1195
|
+
const tools = message?.result?.tools;
|
|
1196
|
+
if (Array.isArray(tools)) {
|
|
1197
|
+
for (const t of tools) {
|
|
1198
|
+
if (t?.inputSchema) delete t.inputSchema.$schema;
|
|
1199
|
+
if (t?.outputSchema) delete t.outputSchema.$schema;
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
return __send(message);
|
|
1203
|
+
};
|
|
1204
|
+
await server.connect(transport);
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
// src/cli.ts
|
|
1208
|
+
var VERSION = "0.2.2";
|
|
1209
|
+
var UsageError = class extends Error {
|
|
1210
|
+
};
|
|
1211
|
+
var HELP = `librenmsctrl - read-only operator CLI for a LibreNMS instance
|
|
1212
|
+
|
|
1213
|
+
Usage:
|
|
1214
|
+
librenmsctrl <command> [subcommand] [args] [options]
|
|
1215
|
+
|
|
1216
|
+
Commands:
|
|
1217
|
+
status LibreNMS system health (version, totals, last poll)
|
|
1218
|
+
devices list List monitored devices
|
|
1219
|
+
devices get <hostname> Fetch a single device by hostname
|
|
1220
|
+
ports list <hostname> List ports on a device
|
|
1221
|
+
ports get <port_id> Single-port detail by LibreNMS port id
|
|
1222
|
+
ports health Rank ports by error/utilization counters
|
|
1223
|
+
alerts list List alerts
|
|
1224
|
+
alerts get <id> Fetch a single alert by id
|
|
1225
|
+
alerts history Recent alert-log entries
|
|
1226
|
+
events list Recent device event-log entries
|
|
1227
|
+
mcp Start the MCP server over stdio
|
|
1228
|
+
help Show this help
|
|
1229
|
+
|
|
1230
|
+
Global options:
|
|
1231
|
+
--json Emit raw JSON instead of human-readable text
|
|
1232
|
+
--version, -v Print version
|
|
1233
|
+
--help, -h Show help
|
|
1234
|
+
|
|
1235
|
+
Command options:
|
|
1236
|
+
devices list --type <t> all | up | down | ignored | disabled
|
|
1237
|
+
ports health --metric <m> errors_in | errors_out | utilization (default errors_in)
|
|
1238
|
+
--limit <n> Top N ports (default 10)
|
|
1239
|
+
alerts list --state <s> 0=ok | 1=active | 2=ack
|
|
1240
|
+
alerts history --device-id <n> Scope to a device id
|
|
1241
|
+
--limit <n> Max entries (default 25)
|
|
1242
|
+
events list --device-id <n> Scope to a device id
|
|
1243
|
+
--limit <n> Max entries (default 25)
|
|
1244
|
+
|
|
1245
|
+
Environment:
|
|
1246
|
+
LIBRENMS_URL Base URL of the LibreNMS instance (required)
|
|
1247
|
+
LIBRENMS_TOKEN X-Auth-Token API token (required)
|
|
1248
|
+
LIBRENMS_TLS_INSECURE Set truthy to skip TLS verification (self-signed hosts)
|
|
1249
|
+
LIBRENMS_REQUEST_TIMEOUT_MS Per-request HTTP timeout in ms (default 30000, min 1000)`;
|
|
1250
|
+
function takeFlag(args, name) {
|
|
1251
|
+
const i = args.indexOf(name);
|
|
1252
|
+
if (i === -1) return false;
|
|
1253
|
+
args.splice(i, 1);
|
|
1254
|
+
return true;
|
|
1255
|
+
}
|
|
1256
|
+
function ensureNoExtra(args) {
|
|
1257
|
+
if (args.length) throw new UsageError(`Unexpected arguments: ${args.join(" ")}`);
|
|
1258
|
+
}
|
|
1259
|
+
function requireValue(v, name) {
|
|
1260
|
+
if (v === void 0 || v.startsWith("--")) throw new UsageError(`${name} requires a value`);
|
|
1261
|
+
return v;
|
|
1262
|
+
}
|
|
1263
|
+
function requireInt(v, name, min, max) {
|
|
1264
|
+
const n = Number(requireValue(v, name));
|
|
1265
|
+
if (!Number.isInteger(n) || n < min || n > max) {
|
|
1266
|
+
throw new UsageError(`${name} must be an integer in [${min}, ${max}]`);
|
|
1267
|
+
}
|
|
1268
|
+
return n;
|
|
1269
|
+
}
|
|
1270
|
+
function requireEnum(v, allowed, name) {
|
|
1271
|
+
const s = requireValue(v, name);
|
|
1272
|
+
if (!allowed.includes(s)) {
|
|
1273
|
+
throw new UsageError(`${name} must be one of: ${allowed.join(", ")}`);
|
|
1274
|
+
}
|
|
1275
|
+
return s;
|
|
1276
|
+
}
|
|
1277
|
+
function requirePositional(args, name) {
|
|
1278
|
+
const v = args.shift();
|
|
1279
|
+
if (v === void 0 || v.startsWith("--")) throw new UsageError(`${name} is required`);
|
|
1280
|
+
return v;
|
|
1281
|
+
}
|
|
1282
|
+
function requirePositionalInt(args, name, min) {
|
|
1283
|
+
const raw = requirePositional(args, name);
|
|
1284
|
+
const n = Number(raw);
|
|
1285
|
+
if (!Number.isInteger(n) || n < min) {
|
|
1286
|
+
throw new UsageError(`${name} must be an integer >= ${min}`);
|
|
1287
|
+
}
|
|
1288
|
+
return n;
|
|
1289
|
+
}
|
|
1290
|
+
function parseDevices(args, json) {
|
|
1291
|
+
const sub = args.shift();
|
|
1292
|
+
if (sub === "list") {
|
|
1293
|
+
let type;
|
|
1294
|
+
while (args.length) {
|
|
1295
|
+
const a = args.shift();
|
|
1296
|
+
if (a === "--type") {
|
|
1297
|
+
type = requireEnum(args.shift(), ["all", "up", "down", "ignored", "disabled"], "--type");
|
|
1298
|
+
} else {
|
|
1299
|
+
throw new UsageError(a.startsWith("--") ? `Unknown option: ${a}` : `Unexpected argument: ${a}`);
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
return { kind: "devices-list", json, type };
|
|
1303
|
+
}
|
|
1304
|
+
if (sub === "get") {
|
|
1305
|
+
const hostname = requirePositional(args, "hostname");
|
|
1306
|
+
ensureNoExtra(args);
|
|
1307
|
+
return { kind: "devices-get", json, hostname };
|
|
1308
|
+
}
|
|
1309
|
+
throw new UsageError(`Unknown devices subcommand: ${sub ?? "(none)"} (expected list|get)`);
|
|
1310
|
+
}
|
|
1311
|
+
function parsePorts(args, json) {
|
|
1312
|
+
const sub = args.shift();
|
|
1313
|
+
if (sub === "list") {
|
|
1314
|
+
const hostname = requirePositional(args, "hostname");
|
|
1315
|
+
ensureNoExtra(args);
|
|
1316
|
+
return { kind: "ports-list", json, hostname };
|
|
1317
|
+
}
|
|
1318
|
+
if (sub === "get") {
|
|
1319
|
+
const portId = requirePositionalInt(args, "port_id", 1);
|
|
1320
|
+
ensureNoExtra(args);
|
|
1321
|
+
return { kind: "ports-get", json, portId };
|
|
1322
|
+
}
|
|
1323
|
+
if (sub === "health") {
|
|
1324
|
+
let metric = "errors_in";
|
|
1325
|
+
let limit = 10;
|
|
1326
|
+
while (args.length) {
|
|
1327
|
+
const a = args.shift();
|
|
1328
|
+
if (a === "--metric") {
|
|
1329
|
+
metric = requireEnum(args.shift(), ["errors_in", "errors_out", "utilization"], "--metric");
|
|
1330
|
+
} else if (a === "--limit") {
|
|
1331
|
+
limit = requireInt(args.shift(), "--limit", 1, 1e3);
|
|
1332
|
+
} else {
|
|
1333
|
+
throw new UsageError(a.startsWith("--") ? `Unknown option: ${a}` : `Unexpected argument: ${a}`);
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
return { kind: "ports-health", json, metric, limit };
|
|
1337
|
+
}
|
|
1338
|
+
throw new UsageError(`Unknown ports subcommand: ${sub ?? "(none)"} (expected list|get|health)`);
|
|
1339
|
+
}
|
|
1340
|
+
function parseAlerts(args, json) {
|
|
1341
|
+
const sub = args.shift();
|
|
1342
|
+
if (sub === "list") {
|
|
1343
|
+
let state;
|
|
1344
|
+
while (args.length) {
|
|
1345
|
+
const a = args.shift();
|
|
1346
|
+
if (a === "--state") {
|
|
1347
|
+
state = requireInt(args.shift(), "--state", 0, 2);
|
|
1348
|
+
} else {
|
|
1349
|
+
throw new UsageError(a.startsWith("--") ? `Unknown option: ${a}` : `Unexpected argument: ${a}`);
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
return { kind: "alerts-list", json, state };
|
|
1353
|
+
}
|
|
1354
|
+
if (sub === "get") {
|
|
1355
|
+
const id = requirePositionalInt(args, "id", 1);
|
|
1356
|
+
ensureNoExtra(args);
|
|
1357
|
+
return { kind: "alerts-get", json, id };
|
|
1358
|
+
}
|
|
1359
|
+
if (sub === "history") {
|
|
1360
|
+
const { deviceId, limit } = parseLogOptions(args);
|
|
1361
|
+
return { kind: "alerts-history", json, deviceId, limit };
|
|
1362
|
+
}
|
|
1363
|
+
throw new UsageError(`Unknown alerts subcommand: ${sub ?? "(none)"} (expected list|get|history)`);
|
|
1364
|
+
}
|
|
1365
|
+
function parseEvents(args, json) {
|
|
1366
|
+
const sub = args.shift();
|
|
1367
|
+
if (sub === "list") {
|
|
1368
|
+
const { deviceId, limit } = parseLogOptions(args);
|
|
1369
|
+
return { kind: "events-list", json, deviceId, limit };
|
|
1370
|
+
}
|
|
1371
|
+
throw new UsageError(`Unknown events subcommand: ${sub ?? "(none)"} (expected list)`);
|
|
1372
|
+
}
|
|
1373
|
+
function parseLogOptions(args) {
|
|
1374
|
+
let deviceId;
|
|
1375
|
+
let limit = 25;
|
|
1376
|
+
while (args.length) {
|
|
1377
|
+
const a = args.shift();
|
|
1378
|
+
if (a === "--device-id") {
|
|
1379
|
+
deviceId = requireInt(args.shift(), "--device-id", 1, Number.MAX_SAFE_INTEGER);
|
|
1380
|
+
} else if (a === "--limit") {
|
|
1381
|
+
limit = requireInt(args.shift(), "--limit", 1, 1e4);
|
|
1382
|
+
} else {
|
|
1383
|
+
throw new UsageError(a.startsWith("--") ? `Unknown option: ${a}` : `Unexpected argument: ${a}`);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
return { deviceId, limit };
|
|
1387
|
+
}
|
|
1388
|
+
function parseArgs(argv) {
|
|
1389
|
+
const args = [...argv];
|
|
1390
|
+
if (args.includes("-h") || args.includes("--help")) return { kind: "help" };
|
|
1391
|
+
if (args.includes("-v") || args.includes("--version")) return { kind: "version" };
|
|
1392
|
+
const cmd = args.shift();
|
|
1393
|
+
if (!cmd || cmd === "help") return { kind: "help" };
|
|
1394
|
+
if (cmd === "mcp") return { kind: "mcp" };
|
|
1395
|
+
const json = takeFlag(args, "--json");
|
|
1396
|
+
switch (cmd) {
|
|
1397
|
+
case "status":
|
|
1398
|
+
ensureNoExtra(args);
|
|
1399
|
+
return { kind: "status", json };
|
|
1400
|
+
case "devices":
|
|
1401
|
+
return parseDevices(args, json);
|
|
1402
|
+
case "ports":
|
|
1403
|
+
return parsePorts(args, json);
|
|
1404
|
+
case "alerts":
|
|
1405
|
+
return parseAlerts(args, json);
|
|
1406
|
+
case "events":
|
|
1407
|
+
return parseEvents(args, json);
|
|
1408
|
+
default:
|
|
1409
|
+
throw new UsageError(`Unknown command: ${cmd}`);
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
function asStr(v) {
|
|
1413
|
+
if (v === null || v === void 0) return "-";
|
|
1414
|
+
return String(v);
|
|
1415
|
+
}
|
|
1416
|
+
function num(v) {
|
|
1417
|
+
const n = typeof v === "number" ? v : Number(v);
|
|
1418
|
+
return Number.isFinite(n) ? n : 0;
|
|
1419
|
+
}
|
|
1420
|
+
function renderSystem(system) {
|
|
1421
|
+
const lines = ["LibreNMS system:"];
|
|
1422
|
+
const keys = [
|
|
1423
|
+
["local_hostname", "host"],
|
|
1424
|
+
["version", "version"],
|
|
1425
|
+
["db_schema", "db_schema"],
|
|
1426
|
+
["php_ver", "php"],
|
|
1427
|
+
["database_ver", "db_ver"],
|
|
1428
|
+
["rrdcached", "rrdcached"]
|
|
1429
|
+
];
|
|
1430
|
+
for (const [k, label] of keys) {
|
|
1431
|
+
if (system[k] !== void 0) lines.push(` ${label}: ${asStr(system[k])}`);
|
|
1432
|
+
}
|
|
1433
|
+
return lines.join("\n");
|
|
1434
|
+
}
|
|
1435
|
+
function renderDevices(devices) {
|
|
1436
|
+
if (!devices.length) return "No devices.";
|
|
1437
|
+
const lines = [`${devices.length} device(s):`];
|
|
1438
|
+
for (const d of devices) {
|
|
1439
|
+
const up = d.status === 1 || d.status === "1" ? "up" : "down";
|
|
1440
|
+
lines.push(` [${asStr(d.device_id)}] ${asStr(d.hostname)} ${up} os=${asStr(d.os)} hw=${asStr(d.hardware)}`);
|
|
1441
|
+
}
|
|
1442
|
+
return lines.join("\n");
|
|
1443
|
+
}
|
|
1444
|
+
function renderDevice(device) {
|
|
1445
|
+
if (!device) return "Device not found.";
|
|
1446
|
+
const lines = [`Device ${asStr(device.hostname)} [${asStr(device.device_id)}]`];
|
|
1447
|
+
for (const k of ["sysName", "os", "version", "hardware", "status", "uptime", "location"]) {
|
|
1448
|
+
if (device[k] !== void 0) lines.push(` ${k}: ${asStr(device[k])}`);
|
|
1449
|
+
}
|
|
1450
|
+
return lines.join("\n");
|
|
1451
|
+
}
|
|
1452
|
+
function renderPorts(ports) {
|
|
1453
|
+
if (!ports.length) return "No ports.";
|
|
1454
|
+
const lines = [`${ports.length} port(s):`];
|
|
1455
|
+
for (const p of ports) {
|
|
1456
|
+
lines.push(
|
|
1457
|
+
` ${asStr(p.ifName)} admin=${asStr(p.ifAdminStatus)} oper=${asStr(p.ifOperStatus)} errIn=${asStr(p.ifInErrors)} errOut=${asStr(p.ifOutErrors)} ${asStr(p.ifDescr)}`
|
|
1458
|
+
);
|
|
1459
|
+
}
|
|
1460
|
+
return lines.join("\n");
|
|
1461
|
+
}
|
|
1462
|
+
function renderPort(port) {
|
|
1463
|
+
if (!port) return "Port not found.";
|
|
1464
|
+
const lines = [`Port ${asStr(port.ifName)} [${asStr(port.port_id)}] on device ${asStr(port.device_id)}`];
|
|
1465
|
+
for (const k of ["ifAlias", "ifAdminStatus", "ifOperStatus", "ifSpeed", "ifInErrors", "ifOutErrors", "ifInOctets", "ifOutOctets"]) {
|
|
1466
|
+
if (port[k] !== void 0) lines.push(` ${k}: ${asStr(port[k])}`);
|
|
1467
|
+
}
|
|
1468
|
+
return lines.join("\n");
|
|
1469
|
+
}
|
|
1470
|
+
function renderPortHealth(metric, limit, top) {
|
|
1471
|
+
if (!top.length) return "No ports.";
|
|
1472
|
+
const lines = [`Top ${Math.min(limit, top.length)} ports by ${metric}:`];
|
|
1473
|
+
for (const p of top) {
|
|
1474
|
+
const util = num(p.ifSpeed) ? ((num(p.ifInOctets) + num(p.ifOutOctets)) / num(p.ifSpeed)).toFixed(4) : "-";
|
|
1475
|
+
lines.push(
|
|
1476
|
+
` dev=${asStr(p.device_id)} ${asStr(p.ifName)} errIn=${asStr(p.ifInErrors)} errOut=${asStr(p.ifOutErrors)} util=${util}`
|
|
1477
|
+
);
|
|
1478
|
+
}
|
|
1479
|
+
return lines.join("\n");
|
|
1480
|
+
}
|
|
1481
|
+
function renderAlerts(alerts) {
|
|
1482
|
+
if (!alerts.length) return "No alerts.";
|
|
1483
|
+
const lines = [`${alerts.length} alert(s):`];
|
|
1484
|
+
for (const a of alerts) {
|
|
1485
|
+
lines.push(
|
|
1486
|
+
` [${asStr(a.id)}] device=${asStr(a.hostname ?? a.device_id)} state=${asStr(a.state)} sev=${asStr(a.severity)} ${asStr(a.rule ?? a.name)}`
|
|
1487
|
+
);
|
|
1488
|
+
}
|
|
1489
|
+
return lines.join("\n");
|
|
1490
|
+
}
|
|
1491
|
+
function renderAlert(alert) {
|
|
1492
|
+
if (!alert) return "Alert not found.";
|
|
1493
|
+
const lines = [`Alert ${asStr(alert.id)}`];
|
|
1494
|
+
for (const k of ["hostname", "device_id", "rule", "name", "severity", "state", "timestamp", "alerted"]) {
|
|
1495
|
+
if (alert[k] !== void 0) lines.push(` ${k}: ${asStr(alert[k])}`);
|
|
1496
|
+
}
|
|
1497
|
+
return lines.join("\n");
|
|
1498
|
+
}
|
|
1499
|
+
function renderLogs(label, logs) {
|
|
1500
|
+
if (!logs.length) return `No ${label} entries.`;
|
|
1501
|
+
const lines = [`${logs.length} ${label} entr${logs.length === 1 ? "y" : "ies"}:`];
|
|
1502
|
+
for (const l of logs) {
|
|
1503
|
+
const ts = asStr(l.datetime ?? l.timestamp ?? l.time_logged);
|
|
1504
|
+
const dev = asStr(l.hostname ?? l.device_id);
|
|
1505
|
+
const msg = asStr(l.message ?? l.details ?? l.rule);
|
|
1506
|
+
lines.push(` ${ts} device=${dev} ${msg}`);
|
|
1507
|
+
}
|
|
1508
|
+
return lines.join("\n");
|
|
1509
|
+
}
|
|
1510
|
+
async function run(argv, deps) {
|
|
1511
|
+
let parsed;
|
|
1512
|
+
try {
|
|
1513
|
+
parsed = parseArgs(argv);
|
|
1514
|
+
} catch (error) {
|
|
1515
|
+
deps.err(error instanceof Error ? error.message : String(error));
|
|
1516
|
+
deps.err("");
|
|
1517
|
+
deps.err(HELP);
|
|
1518
|
+
return 2;
|
|
1519
|
+
}
|
|
1520
|
+
if (parsed.kind === "help") {
|
|
1521
|
+
deps.out(HELP);
|
|
1522
|
+
return 0;
|
|
1523
|
+
}
|
|
1524
|
+
if (parsed.kind === "version") {
|
|
1525
|
+
deps.out(VERSION);
|
|
1526
|
+
return 0;
|
|
1527
|
+
}
|
|
1528
|
+
if (parsed.kind === "mcp") {
|
|
1529
|
+
await deps.serve();
|
|
1530
|
+
return 0;
|
|
1531
|
+
}
|
|
1532
|
+
const client = deps.makeClient();
|
|
1533
|
+
try {
|
|
1534
|
+
switch (parsed.kind) {
|
|
1535
|
+
case "status": {
|
|
1536
|
+
const r = await client.get("/system");
|
|
1537
|
+
const system = r.system?.[0] ?? null;
|
|
1538
|
+
deps.out(parsed.json ? JSON.stringify({ system }, null, 2) : system ? renderSystem(system) : "No system data.");
|
|
1539
|
+
return system ? 0 : 1;
|
|
1540
|
+
}
|
|
1541
|
+
case "devices-list": {
|
|
1542
|
+
const path = parsed.type ? `/devices?type=${encodeURIComponent(parsed.type)}` : "/devices";
|
|
1543
|
+
const r = await client.get(path);
|
|
1544
|
+
const devices = r.devices ?? [];
|
|
1545
|
+
deps.out(parsed.json ? JSON.stringify({ devices }, null, 2) : renderDevices(devices));
|
|
1546
|
+
return 0;
|
|
1547
|
+
}
|
|
1548
|
+
case "devices-get": {
|
|
1549
|
+
const r = await client.get(`/devices/${encodeURIComponent(parsed.hostname)}`);
|
|
1550
|
+
const device = r.devices?.[0] ?? null;
|
|
1551
|
+
deps.out(parsed.json ? JSON.stringify({ device }, null, 2) : renderDevice(device));
|
|
1552
|
+
return device ? 0 : 1;
|
|
1553
|
+
}
|
|
1554
|
+
case "ports-list": {
|
|
1555
|
+
const columns = "ifName,ifAdminStatus,ifOperStatus,ifInErrors,ifOutErrors,ifSpeed,ifDescr";
|
|
1556
|
+
const r = await client.get(
|
|
1557
|
+
`/devices/${encodeURIComponent(parsed.hostname)}/ports?columns=${columns}`
|
|
1558
|
+
);
|
|
1559
|
+
const ports = r.ports ?? [];
|
|
1560
|
+
deps.out(parsed.json ? JSON.stringify({ ports }, null, 2) : renderPorts(ports));
|
|
1561
|
+
return 0;
|
|
1562
|
+
}
|
|
1563
|
+
case "ports-get": {
|
|
1564
|
+
const r = await client.get(`/ports/${encodeURIComponent(parsed.portId)}`);
|
|
1565
|
+
const port = r.port?.[0] ?? null;
|
|
1566
|
+
deps.out(parsed.json ? JSON.stringify({ port }, null, 2) : renderPort(port));
|
|
1567
|
+
return port ? 0 : 1;
|
|
1568
|
+
}
|
|
1569
|
+
case "ports-health": {
|
|
1570
|
+
const columns = "device_id,ifName,ifInErrors,ifOutErrors,ifSpeed,ifInOctets,ifOutOctets";
|
|
1571
|
+
const r = await client.get(`/ports?columns=${columns}`);
|
|
1572
|
+
const ports = r.ports ?? [];
|
|
1573
|
+
const metric = parsed.metric;
|
|
1574
|
+
const sorted = ports.slice().sort((a, b) => {
|
|
1575
|
+
if (metric === "errors_in") return num(b.ifInErrors) - num(a.ifInErrors);
|
|
1576
|
+
if (metric === "errors_out") return num(b.ifOutErrors) - num(a.ifOutErrors);
|
|
1577
|
+
const aUtil = num(a.ifSpeed) ? (num(a.ifInOctets) + num(a.ifOutOctets)) / num(a.ifSpeed) : 0;
|
|
1578
|
+
const bUtil = num(b.ifSpeed) ? (num(b.ifInOctets) + num(b.ifOutOctets)) / num(b.ifSpeed) : 0;
|
|
1579
|
+
return bUtil - aUtil;
|
|
1580
|
+
});
|
|
1581
|
+
const top = sorted.slice(0, parsed.limit);
|
|
1582
|
+
deps.out(
|
|
1583
|
+
parsed.json ? JSON.stringify({ metric, limit: parsed.limit, top }, null, 2) : renderPortHealth(metric, parsed.limit, top)
|
|
1584
|
+
);
|
|
1585
|
+
return 0;
|
|
1586
|
+
}
|
|
1587
|
+
case "alerts-list": {
|
|
1588
|
+
const path = parsed.state !== void 0 ? `/alerts?state=${encodeURIComponent(parsed.state)}` : "/alerts";
|
|
1589
|
+
const r = await client.get(path);
|
|
1590
|
+
const alerts = r.alerts ?? [];
|
|
1591
|
+
deps.out(parsed.json ? JSON.stringify({ alerts }, null, 2) : renderAlerts(alerts));
|
|
1592
|
+
return 0;
|
|
1593
|
+
}
|
|
1594
|
+
case "alerts-get": {
|
|
1595
|
+
const r = await client.get(`/alerts/${encodeURIComponent(parsed.id)}`);
|
|
1596
|
+
const alert = r.alerts?.[0] ?? null;
|
|
1597
|
+
deps.out(parsed.json ? JSON.stringify({ alert }, null, 2) : renderAlert(alert));
|
|
1598
|
+
return alert ? 0 : 1;
|
|
1599
|
+
}
|
|
1600
|
+
case "alerts-history": {
|
|
1601
|
+
const path = parsed.deviceId !== void 0 ? `/logs/alertlog/${encodeURIComponent(parsed.deviceId)}?limit=${encodeURIComponent(parsed.limit)}` : `/logs/alertlog?limit=${encodeURIComponent(parsed.limit)}`;
|
|
1602
|
+
const r = await client.get(path);
|
|
1603
|
+
const logs = r.logs ?? [];
|
|
1604
|
+
deps.out(parsed.json ? JSON.stringify({ count: logs.length, logs }, null, 2) : renderLogs("alert-log", logs));
|
|
1605
|
+
return 0;
|
|
1606
|
+
}
|
|
1607
|
+
case "events-list": {
|
|
1608
|
+
const path = parsed.deviceId !== void 0 ? `/logs/eventlog/${encodeURIComponent(parsed.deviceId)}?limit=${encodeURIComponent(parsed.limit)}` : `/logs/eventlog?limit=${encodeURIComponent(parsed.limit)}`;
|
|
1609
|
+
const r = await client.get(path);
|
|
1610
|
+
const logs = r.logs ?? [];
|
|
1611
|
+
deps.out(parsed.json ? JSON.stringify({ count: logs.length, logs }, null, 2) : renderLogs("event-log", logs));
|
|
1612
|
+
return 0;
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
} catch (error) {
|
|
1616
|
+
if (error instanceof ValidationError) {
|
|
1617
|
+
deps.err(redact(error.message));
|
|
1618
|
+
return 2;
|
|
1619
|
+
}
|
|
1620
|
+
deps.err(redact(boundaryErrorMessage(error)));
|
|
1621
|
+
return 1;
|
|
1622
|
+
}
|
|
1623
|
+
return 0;
|
|
1624
|
+
}
|
|
1625
|
+
var isEntrypoint = (() => {
|
|
1626
|
+
const arg = process.argv[1];
|
|
1627
|
+
if (typeof arg !== "string") return false;
|
|
1628
|
+
try {
|
|
1629
|
+
return import.meta.url === pathToFileURL(realpathSync(arg)).href;
|
|
1630
|
+
} catch {
|
|
1631
|
+
return false;
|
|
1632
|
+
}
|
|
1633
|
+
})();
|
|
1634
|
+
if (isEntrypoint) {
|
|
1635
|
+
run(process.argv.slice(2), {
|
|
1636
|
+
out: (s) => process.stdout.write(`${s}
|
|
1637
|
+
`),
|
|
1638
|
+
err: (s) => process.stderr.write(`${s}
|
|
1639
|
+
`),
|
|
1640
|
+
makeClient: () => new LibreNmsClient(resolveConfig(process.env)),
|
|
1641
|
+
serve
|
|
1642
|
+
}).then((code) => {
|
|
1643
|
+
process.exitCode = code;
|
|
1644
|
+
}).catch((error) => {
|
|
1645
|
+
process.stderr.write(`${redact(boundaryErrorMessage(error))}
|
|
1646
|
+
`);
|
|
1647
|
+
process.exitCode = 1;
|
|
1648
|
+
});
|
|
1649
|
+
}
|
|
1650
|
+
export {
|
|
1651
|
+
HELP,
|
|
1652
|
+
UsageError,
|
|
1653
|
+
VERSION,
|
|
1654
|
+
parseArgs,
|
|
1655
|
+
run
|
|
1656
|
+
};
|