@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/mcp-bin.js
ADDED
|
@@ -0,0 +1,1206 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// mcp-server.ts
|
|
4
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
5
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
6
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
7
|
+
|
|
8
|
+
// src/config.ts
|
|
9
|
+
import { Effect as Effect6 } from "effect";
|
|
10
|
+
|
|
11
|
+
// node_modules/@lidless-labs/effect-operator-kit/dist/index.js
|
|
12
|
+
import { Data } from "effect";
|
|
13
|
+
import { Effect } from "effect";
|
|
14
|
+
import { Effect as Effect2 } from "effect";
|
|
15
|
+
import { Duration, Effect as Effect3, Schedule } from "effect";
|
|
16
|
+
import { Cause, Effect as Effect4, Exit } from "effect";
|
|
17
|
+
import { Cause as Cause2, Effect as Effect5 } from "effect";
|
|
18
|
+
var ConfigError = class extends Data.TaggedError("ConfigError") {
|
|
19
|
+
};
|
|
20
|
+
var AuthError = class extends Data.TaggedError("AuthError") {
|
|
21
|
+
};
|
|
22
|
+
var ForbiddenError = class extends Data.TaggedError("ForbiddenError") {
|
|
23
|
+
};
|
|
24
|
+
var NotFoundError = class extends Data.TaggedError("NotFoundError") {
|
|
25
|
+
};
|
|
26
|
+
var TimeoutError = class extends Data.TaggedError("TimeoutError") {
|
|
27
|
+
};
|
|
28
|
+
var TransportError = class extends Data.TaggedError("TransportError") {
|
|
29
|
+
};
|
|
30
|
+
var ParseError = class extends Data.TaggedError("ParseError") {
|
|
31
|
+
};
|
|
32
|
+
var UnexpectedStatusError = class extends Data.TaggedError("UnexpectedStatusError") {
|
|
33
|
+
};
|
|
34
|
+
var fromProcessEnv = (env) => ({
|
|
35
|
+
get: (key) => (env ?? process.env)[key]
|
|
36
|
+
});
|
|
37
|
+
var isBlank = (raw) => raw === void 0 || raw.trim() === "";
|
|
38
|
+
var failConfig = (partial) => Effect.fail(new ConfigError(partial));
|
|
39
|
+
var readRaw = (env, key) => env.get(key);
|
|
40
|
+
var TRUE_TOKENS = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
|
|
41
|
+
var FALSE_TOKENS = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
|
|
42
|
+
var parseBooleanEnv = (env, key, fallback) => {
|
|
43
|
+
const raw = readRaw(env, key);
|
|
44
|
+
if (isBlank(raw)) {
|
|
45
|
+
return Effect.succeed(fallback);
|
|
46
|
+
}
|
|
47
|
+
const token = raw.trim().toLowerCase();
|
|
48
|
+
if (TRUE_TOKENS.has(token)) {
|
|
49
|
+
return Effect.succeed(true);
|
|
50
|
+
}
|
|
51
|
+
if (FALSE_TOKENS.has(token)) {
|
|
52
|
+
return Effect.succeed(false);
|
|
53
|
+
}
|
|
54
|
+
return failConfig({
|
|
55
|
+
key,
|
|
56
|
+
value: raw,
|
|
57
|
+
message: `${key} must be a boolean (true/false, 1/0, yes/no, on/off)`
|
|
58
|
+
});
|
|
59
|
+
};
|
|
60
|
+
var parseTimeoutEnv = (env, key, opts) => {
|
|
61
|
+
const raw = readRaw(env, key);
|
|
62
|
+
if (isBlank(raw)) {
|
|
63
|
+
return Effect.succeed(opts.fallbackMs);
|
|
64
|
+
}
|
|
65
|
+
const parsed = Number(raw.trim());
|
|
66
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
67
|
+
return failConfig({
|
|
68
|
+
key,
|
|
69
|
+
value: raw,
|
|
70
|
+
message: `${key} must be a positive timeout`
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
const unit = opts.unit ?? "s";
|
|
74
|
+
const ms = unit === "ms" ? parsed : parsed * 1e3;
|
|
75
|
+
if (opts.minMs !== void 0 && ms < opts.minMs) {
|
|
76
|
+
return failConfig({
|
|
77
|
+
key,
|
|
78
|
+
value: raw,
|
|
79
|
+
message: `${key} must be at least ${opts.minMs}ms`
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if (opts.maxMs !== void 0 && ms > opts.maxMs) {
|
|
83
|
+
return failConfig({
|
|
84
|
+
key,
|
|
85
|
+
value: raw,
|
|
86
|
+
message: `${key} must be at most ${opts.maxMs}ms`
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
return Effect.succeed(ms);
|
|
90
|
+
};
|
|
91
|
+
var SECRET_PATTERNS = [
|
|
92
|
+
/(authorization:\s*)(basic|bearer)\s+[a-z0-9._~+/=-]+/gi,
|
|
93
|
+
/\b(basic|bearer)\s+[a-z0-9._~+/=-]+/gi,
|
|
94
|
+
/(authorization:\s*)(?:token|digest|hawk|oauth|apikey)\s+\S+/gi,
|
|
95
|
+
/(x-n8n-api-key|x-auth-token|x-emby-token|x-api-key)\s*:\s*\S+/gi,
|
|
96
|
+
/(https?:\/\/)([^@\s/]+)@/gi,
|
|
97
|
+
/([?&](?:access_token|refresh_token|client_secret|id_token|x-api-key|\w+_(?:token|secret)|password|token|secret|api[_-]?key|key)=)[^&\s]+/gi,
|
|
98
|
+
/\beyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\b/g
|
|
99
|
+
];
|
|
100
|
+
var MAX_LENGTH = 500;
|
|
101
|
+
var redactString = (message, secrets = []) => {
|
|
102
|
+
let sanitized = message;
|
|
103
|
+
for (const secret of secrets) {
|
|
104
|
+
if (secret) {
|
|
105
|
+
sanitized = sanitized.split(secret).join("[REDACTED]");
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
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]");
|
|
109
|
+
return sanitized.length > MAX_LENGTH ? `${sanitized.slice(0, MAX_LENGTH)}...` : sanitized;
|
|
110
|
+
};
|
|
111
|
+
var defaultRedact = (value) => redactString(value);
|
|
112
|
+
var DEFAULT_SUCCESS_STATUSES = Array.from({ length: 100 }, (_, i) => 200 + i);
|
|
113
|
+
function redactBody(text, redact2) {
|
|
114
|
+
return (redact2 ?? defaultRedact)(text);
|
|
115
|
+
}
|
|
116
|
+
function mergeHeaders(...sources) {
|
|
117
|
+
const merged = new Headers();
|
|
118
|
+
for (const source of sources) {
|
|
119
|
+
if (!source) continue;
|
|
120
|
+
const headers = new Headers(source);
|
|
121
|
+
headers.forEach((value, key) => merged.set(key, value));
|
|
122
|
+
}
|
|
123
|
+
return merged;
|
|
124
|
+
}
|
|
125
|
+
function resolveExpectedStatuses(req) {
|
|
126
|
+
return req.expectedStatuses ?? DEFAULT_SUCCESS_STATUSES;
|
|
127
|
+
}
|
|
128
|
+
function isExpectedStatus(status, expected) {
|
|
129
|
+
return expected.includes(status);
|
|
130
|
+
}
|
|
131
|
+
function resolveBodyEncoding(req) {
|
|
132
|
+
if (req.bodyEncoding !== void 0) return req.bodyEncoding;
|
|
133
|
+
return req.body !== void 0 ? "json" : "none";
|
|
134
|
+
}
|
|
135
|
+
function setContentTypeIfAbsent(headers, contentType) {
|
|
136
|
+
if (!headers.has("content-type")) {
|
|
137
|
+
headers.set("content-type", contentType);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function buildRequestBody(req, headers) {
|
|
141
|
+
const encoding = resolveBodyEncoding(req);
|
|
142
|
+
switch (encoding) {
|
|
143
|
+
case "none":
|
|
144
|
+
return void 0;
|
|
145
|
+
case "json":
|
|
146
|
+
setContentTypeIfAbsent(headers, "application/json");
|
|
147
|
+
return JSON.stringify(req.body);
|
|
148
|
+
case "text":
|
|
149
|
+
setContentTypeIfAbsent(headers, "text/plain");
|
|
150
|
+
return String(req.body);
|
|
151
|
+
case "form": {
|
|
152
|
+
setContentTypeIfAbsent(
|
|
153
|
+
headers,
|
|
154
|
+
"application/x-www-form-urlencoded"
|
|
155
|
+
);
|
|
156
|
+
const params = new URLSearchParams();
|
|
157
|
+
if (req.body && typeof req.body === "object") {
|
|
158
|
+
for (const [key, value] of Object.entries(
|
|
159
|
+
req.body
|
|
160
|
+
)) {
|
|
161
|
+
params.set(key, String(value));
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return params.toString();
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function mapUnexpectedStatus(req, status, bodyText, expectedStatuses, redact2) {
|
|
169
|
+
const redacted = redactBody(bodyText, redact2);
|
|
170
|
+
const mapperInput = {
|
|
171
|
+
status,
|
|
172
|
+
method: req.method,
|
|
173
|
+
path: req.path,
|
|
174
|
+
bodyText: redacted,
|
|
175
|
+
expectedStatuses
|
|
176
|
+
};
|
|
177
|
+
if (req.statusMapper) {
|
|
178
|
+
const custom = req.statusMapper(mapperInput);
|
|
179
|
+
if (custom !== null) return custom;
|
|
180
|
+
}
|
|
181
|
+
const base = {
|
|
182
|
+
method: req.method,
|
|
183
|
+
path: req.path,
|
|
184
|
+
status,
|
|
185
|
+
body: redacted
|
|
186
|
+
};
|
|
187
|
+
switch (status) {
|
|
188
|
+
case 401:
|
|
189
|
+
return new AuthError(base);
|
|
190
|
+
case 403:
|
|
191
|
+
return new ForbiddenError(base);
|
|
192
|
+
case 404:
|
|
193
|
+
return new NotFoundError(base);
|
|
194
|
+
default:
|
|
195
|
+
return new UnexpectedStatusError({
|
|
196
|
+
method: req.method,
|
|
197
|
+
path: req.path,
|
|
198
|
+
status,
|
|
199
|
+
body: redacted,
|
|
200
|
+
expected: expectedStatuses
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
function parseResponseBody(req, bodyText, redact2) {
|
|
205
|
+
const responseType = req.responseType ?? "json";
|
|
206
|
+
if (responseType === "none") {
|
|
207
|
+
return Effect2.succeed(void 0);
|
|
208
|
+
}
|
|
209
|
+
if (responseType === "text") {
|
|
210
|
+
return Effect2.succeed(bodyText);
|
|
211
|
+
}
|
|
212
|
+
if (bodyText.length === 0) {
|
|
213
|
+
return Effect2.succeed(void 0);
|
|
214
|
+
}
|
|
215
|
+
return Effect2.try({
|
|
216
|
+
try: () => JSON.parse(bodyText),
|
|
217
|
+
catch: (cause) => new ParseError({
|
|
218
|
+
path: req.path,
|
|
219
|
+
body: redactBody(bodyText, redact2),
|
|
220
|
+
message: "Failed to parse JSON response",
|
|
221
|
+
cause
|
|
222
|
+
})
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
function fetchWithTimeout(ctx, url, init, timeoutMs, method, path) {
|
|
226
|
+
const fetchImpl = ctx.fetch ?? globalThis.fetch;
|
|
227
|
+
return Effect2.async((resume) => {
|
|
228
|
+
const controller = new AbortController();
|
|
229
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
230
|
+
const finish = (effect) => {
|
|
231
|
+
clearTimeout(timeoutId);
|
|
232
|
+
resume(effect);
|
|
233
|
+
};
|
|
234
|
+
void fetchImpl(url, { ...init, signal: controller.signal }).then((response) => finish(Effect2.succeed(response))).catch((cause) => {
|
|
235
|
+
if (cause instanceof Error && cause.name === "AbortError") {
|
|
236
|
+
finish(
|
|
237
|
+
Effect2.fail(new TimeoutError({ method, path, timeoutMs }))
|
|
238
|
+
);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
finish(
|
|
242
|
+
Effect2.fail(new TransportError({ method, path, cause }))
|
|
243
|
+
);
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
var buildUrl = (baseUrl, path, query) => {
|
|
248
|
+
if (path.includes("\\")) {
|
|
249
|
+
throw new TypeError("buildUrl: path must not contain backslash");
|
|
250
|
+
}
|
|
251
|
+
const url = new URL(path, baseUrl);
|
|
252
|
+
if (url.username || url.password) {
|
|
253
|
+
throw new TypeError("buildUrl: path must not contain URL userinfo");
|
|
254
|
+
}
|
|
255
|
+
if (url.origin !== baseUrl.origin) {
|
|
256
|
+
throw new TypeError(
|
|
257
|
+
`buildUrl: path "${path}" resolves to a different origin (${url.origin}) than baseUrl (${baseUrl.origin})`
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
if (query) {
|
|
261
|
+
for (const [key, value] of Object.entries(query)) {
|
|
262
|
+
if (value === null || value === void 0) continue;
|
|
263
|
+
if (Array.isArray(value)) {
|
|
264
|
+
for (const item of value) {
|
|
265
|
+
if (item === null || item === void 0) continue;
|
|
266
|
+
url.searchParams.append(key, String(item));
|
|
267
|
+
}
|
|
268
|
+
} else {
|
|
269
|
+
url.searchParams.set(key, String(value));
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return url;
|
|
274
|
+
};
|
|
275
|
+
function buildHeaders(ctx, req) {
|
|
276
|
+
const auth = ctx.auth;
|
|
277
|
+
if (!auth) {
|
|
278
|
+
return Effect2.succeed(mergeHeaders(ctx.defaultHeaders, req.headers));
|
|
279
|
+
}
|
|
280
|
+
return Effect2.gen(function* () {
|
|
281
|
+
let headers = mergeHeaders(ctx.defaultHeaders);
|
|
282
|
+
headers = yield* auth.apply(headers);
|
|
283
|
+
return mergeHeaders(headers, req.headers);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
var sendRequest = (ctx, req) => {
|
|
287
|
+
const url = buildUrl(ctx.baseUrl, req.path, req.query);
|
|
288
|
+
const timeoutMs = req.timeoutMs ?? ctx.timeoutMs;
|
|
289
|
+
const expectedStatuses = resolveExpectedStatuses(req);
|
|
290
|
+
return buildHeaders(ctx, req).pipe(
|
|
291
|
+
Effect2.flatMap((headers) => {
|
|
292
|
+
const body = buildRequestBody(req, headers);
|
|
293
|
+
const init = {
|
|
294
|
+
method: req.method,
|
|
295
|
+
headers,
|
|
296
|
+
...body !== void 0 ? { body } : {}
|
|
297
|
+
};
|
|
298
|
+
return fetchWithTimeout(
|
|
299
|
+
ctx,
|
|
300
|
+
url,
|
|
301
|
+
init,
|
|
302
|
+
timeoutMs,
|
|
303
|
+
req.method,
|
|
304
|
+
req.path
|
|
305
|
+
).pipe(
|
|
306
|
+
Effect2.flatMap(
|
|
307
|
+
(response) => Effect2.tryPromise({
|
|
308
|
+
try: () => response.text(),
|
|
309
|
+
catch: (cause) => new TransportError({
|
|
310
|
+
method: req.method,
|
|
311
|
+
path: req.path,
|
|
312
|
+
cause
|
|
313
|
+
})
|
|
314
|
+
}).pipe(
|
|
315
|
+
Effect2.flatMap((bodyText) => {
|
|
316
|
+
if (!isExpectedStatus(response.status, expectedStatuses)) {
|
|
317
|
+
return Effect2.fail(
|
|
318
|
+
mapUnexpectedStatus(
|
|
319
|
+
req,
|
|
320
|
+
response.status,
|
|
321
|
+
bodyText,
|
|
322
|
+
expectedStatuses,
|
|
323
|
+
ctx.redact
|
|
324
|
+
)
|
|
325
|
+
);
|
|
326
|
+
}
|
|
327
|
+
return parseResponseBody(req, bodyText, ctx.redact).pipe(
|
|
328
|
+
Effect2.map((parsedBody) => ({
|
|
329
|
+
status: response.status,
|
|
330
|
+
headers: response.headers,
|
|
331
|
+
bodyText,
|
|
332
|
+
body: parsedBody
|
|
333
|
+
}))
|
|
334
|
+
);
|
|
335
|
+
})
|
|
336
|
+
)
|
|
337
|
+
)
|
|
338
|
+
);
|
|
339
|
+
})
|
|
340
|
+
);
|
|
341
|
+
};
|
|
342
|
+
var defaultShouldRetry = (error) => {
|
|
343
|
+
switch (error._tag) {
|
|
344
|
+
case "TransportError":
|
|
345
|
+
case "TimeoutError":
|
|
346
|
+
return true;
|
|
347
|
+
case "UnexpectedStatusError":
|
|
348
|
+
return error.status >= 500;
|
|
349
|
+
default:
|
|
350
|
+
return false;
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
var DEFAULT_POLICY_FIELDS = {
|
|
354
|
+
maxAttempts: 3,
|
|
355
|
+
initialDelayMs: 100,
|
|
356
|
+
maxDelayMs: 5e3,
|
|
357
|
+
factor: 2,
|
|
358
|
+
jitter: true,
|
|
359
|
+
shouldRetry: defaultShouldRetry
|
|
360
|
+
};
|
|
361
|
+
var noRetry = {
|
|
362
|
+
enabled: false,
|
|
363
|
+
...DEFAULT_POLICY_FIELDS,
|
|
364
|
+
shouldRetry: () => false
|
|
365
|
+
};
|
|
366
|
+
var exponentialRetry = (opts) => ({
|
|
367
|
+
enabled: opts.enabled ?? true,
|
|
368
|
+
maxAttempts: opts.maxAttempts ?? DEFAULT_POLICY_FIELDS.maxAttempts,
|
|
369
|
+
initialDelayMs: opts.initialDelayMs ?? DEFAULT_POLICY_FIELDS.initialDelayMs,
|
|
370
|
+
maxDelayMs: opts.maxDelayMs ?? DEFAULT_POLICY_FIELDS.maxDelayMs,
|
|
371
|
+
factor: opts.factor ?? DEFAULT_POLICY_FIELDS.factor,
|
|
372
|
+
jitter: opts.jitter ?? DEFAULT_POLICY_FIELDS.jitter,
|
|
373
|
+
shouldRetry: opts.shouldRetry ?? DEFAULT_POLICY_FIELDS.shouldRetry
|
|
374
|
+
});
|
|
375
|
+
var buildSchedule = (policy) => {
|
|
376
|
+
const base = Schedule.exponential(`${policy.initialDelayMs} millis`, policy.factor);
|
|
377
|
+
const withJitter = policy.jitter ? base.pipe(Schedule.jittered) : base;
|
|
378
|
+
const capped = withJitter.pipe(
|
|
379
|
+
Schedule.modifyDelay((_out, duration) => {
|
|
380
|
+
const ms = Duration.toMillis(duration);
|
|
381
|
+
return ms > policy.maxDelayMs ? `${policy.maxDelayMs} millis` : duration;
|
|
382
|
+
})
|
|
383
|
+
);
|
|
384
|
+
return capped.pipe(Schedule.whileInput((error) => policy.shouldRetry(error)));
|
|
385
|
+
};
|
|
386
|
+
var withRetry = (effect, policy = noRetry) => {
|
|
387
|
+
if (!policy.enabled || policy.maxAttempts <= 1) {
|
|
388
|
+
return effect;
|
|
389
|
+
}
|
|
390
|
+
const retries = Math.max(0, policy.maxAttempts - 1);
|
|
391
|
+
return Effect3.retry(effect, {
|
|
392
|
+
times: retries,
|
|
393
|
+
while: (error) => policy.shouldRetry(error),
|
|
394
|
+
schedule: buildSchedule(policy)
|
|
395
|
+
});
|
|
396
|
+
};
|
|
397
|
+
var ok = (details) => ({
|
|
398
|
+
content: [{ type: "text", text: JSON.stringify(details, null, 2) }],
|
|
399
|
+
details
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
// src/config.ts
|
|
403
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
404
|
+
var ConfigError2 = class extends Error {
|
|
405
|
+
constructor(message) {
|
|
406
|
+
super(message);
|
|
407
|
+
this.name = "ConfigError";
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
function runConfigEffect(effect) {
|
|
411
|
+
const result = Effect6.runSync(Effect6.either(effect));
|
|
412
|
+
if (result._tag === "Left") {
|
|
413
|
+
throw new ConfigError2(result.left.message);
|
|
414
|
+
}
|
|
415
|
+
return result.right;
|
|
416
|
+
}
|
|
417
|
+
function parseTlsInsecure(env) {
|
|
418
|
+
const raw = env.get("LIBRENMS_TLS_INSECURE");
|
|
419
|
+
if (!raw) return false;
|
|
420
|
+
if (["true", "1", "yes"].includes(raw.toLowerCase())) {
|
|
421
|
+
return runConfigEffect(parseBooleanEnv(env, "LIBRENMS_TLS_INSECURE", false));
|
|
422
|
+
}
|
|
423
|
+
return false;
|
|
424
|
+
}
|
|
425
|
+
function parseRequestTimeoutMs(env) {
|
|
426
|
+
return runConfigEffect(
|
|
427
|
+
parseTimeoutEnv(env, "LIBRENMS_REQUEST_TIMEOUT_MS", {
|
|
428
|
+
fallbackMs: DEFAULT_REQUEST_TIMEOUT_MS,
|
|
429
|
+
minMs: 1e3,
|
|
430
|
+
unit: "ms"
|
|
431
|
+
})
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
function resolveConfig(env) {
|
|
435
|
+
const reader = fromProcessEnv(env);
|
|
436
|
+
const url = env.LIBRENMS_URL;
|
|
437
|
+
const token = env.LIBRENMS_TOKEN;
|
|
438
|
+
if (!url) throw new ConfigError2("LIBRENMS_URL is required");
|
|
439
|
+
if (!token) throw new ConfigError2("LIBRENMS_TOKEN is required");
|
|
440
|
+
return {
|
|
441
|
+
url: url.replace(/\/+$/, ""),
|
|
442
|
+
token,
|
|
443
|
+
tlsInsecure: parseTlsInsecure(reader),
|
|
444
|
+
requestTimeoutMs: parseRequestTimeoutMs(reader)
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// src/error-message.ts
|
|
449
|
+
function boundaryErrorMessage(error) {
|
|
450
|
+
return error instanceof Error ? error.message : String(error);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// src/librenms-client.ts
|
|
454
|
+
import { Effect as Effect7 } from "effect";
|
|
455
|
+
import { Agent as UndiciAgent } from "undici";
|
|
456
|
+
var LibreNmsClientError = class extends Error {
|
|
457
|
+
constructor(status, message) {
|
|
458
|
+
super(`LibreNMS ${status}: ${message}`);
|
|
459
|
+
this.status = status;
|
|
460
|
+
this.name = "LibreNmsClientError";
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
var LibreNmsUnreachableError = class extends Error {
|
|
464
|
+
constructor(cause) {
|
|
465
|
+
super(`LibreNMS unreachable: ${cause}`);
|
|
466
|
+
this.name = "LibreNmsUnreachableError";
|
|
467
|
+
}
|
|
468
|
+
};
|
|
469
|
+
var LibreNmsClient = class {
|
|
470
|
+
constructor(cfg, opts = {}) {
|
|
471
|
+
this.cfg = cfg;
|
|
472
|
+
this.retryDelayMs = opts.retryDelayMs ?? 1e3;
|
|
473
|
+
this.fetchImpl = opts.fetch ?? fetch;
|
|
474
|
+
if (cfg.tlsInsecure && cfg.url.startsWith("https://")) {
|
|
475
|
+
this.dispatcher = new UndiciAgent({ connect: { rejectUnauthorized: false } });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
retryDelayMs;
|
|
479
|
+
fetchImpl;
|
|
480
|
+
// Node's global fetch (undici) ignores node:https.Agent. To actually skip
|
|
481
|
+
// cert verification for self-signed LibreNMS hosts we pass an undici Agent
|
|
482
|
+
// via the `dispatcher` init option.
|
|
483
|
+
dispatcher;
|
|
484
|
+
async get(path) {
|
|
485
|
+
return this.request("GET", path);
|
|
486
|
+
}
|
|
487
|
+
async post(path, body) {
|
|
488
|
+
return this.request("POST", path, body);
|
|
489
|
+
}
|
|
490
|
+
async put(path, body) {
|
|
491
|
+
return this.request("PUT", path, body);
|
|
492
|
+
}
|
|
493
|
+
async delete(path) {
|
|
494
|
+
return this.request("DELETE", path);
|
|
495
|
+
}
|
|
496
|
+
async request(method, path, body) {
|
|
497
|
+
const baseUrl = new URL(`${this.cfg.url}/`);
|
|
498
|
+
const requestPath = `api/v0${path}`;
|
|
499
|
+
const auth = {
|
|
500
|
+
apply: (headers) => {
|
|
501
|
+
headers.set("x-auth-token", this.cfg.token);
|
|
502
|
+
return Effect7.succeed(headers);
|
|
503
|
+
}
|
|
504
|
+
};
|
|
505
|
+
const req = {
|
|
506
|
+
method,
|
|
507
|
+
path: requestPath,
|
|
508
|
+
body,
|
|
509
|
+
bodyEncoding: body !== void 0 ? "json" : "none",
|
|
510
|
+
statusMapper: ({ status, method: mappedMethod, path: mappedPath, bodyText, expectedStatuses }) => new UnexpectedStatusError({
|
|
511
|
+
method: mappedMethod,
|
|
512
|
+
path: mappedPath,
|
|
513
|
+
status,
|
|
514
|
+
body: bodyText,
|
|
515
|
+
expected: expectedStatuses
|
|
516
|
+
})
|
|
517
|
+
};
|
|
518
|
+
const ctx = {
|
|
519
|
+
baseUrl,
|
|
520
|
+
auth,
|
|
521
|
+
timeoutMs: this.cfg.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
522
|
+
fetch: this.fetchWithDispatcher,
|
|
523
|
+
redact: (value) => value
|
|
524
|
+
};
|
|
525
|
+
let result;
|
|
526
|
+
try {
|
|
527
|
+
result = await Effect7.runPromise(
|
|
528
|
+
Effect7.either(
|
|
529
|
+
withRetry(
|
|
530
|
+
sendRequest(ctx, req),
|
|
531
|
+
exponentialRetry({
|
|
532
|
+
maxAttempts: 2,
|
|
533
|
+
initialDelayMs: this.retryDelayMs,
|
|
534
|
+
maxDelayMs: this.retryDelayMs,
|
|
535
|
+
factor: 1,
|
|
536
|
+
jitter: false,
|
|
537
|
+
shouldRetry: shouldRetryLibreNmsRequest
|
|
538
|
+
})
|
|
539
|
+
)
|
|
540
|
+
)
|
|
541
|
+
);
|
|
542
|
+
} catch (error) {
|
|
543
|
+
throw new LibreNmsUnreachableError(boundaryErrorMessage(error));
|
|
544
|
+
}
|
|
545
|
+
if (result._tag === "Right") {
|
|
546
|
+
return result.right.body;
|
|
547
|
+
}
|
|
548
|
+
throw mapLibreNmsRequestError(result.left);
|
|
549
|
+
}
|
|
550
|
+
fetchWithDispatcher = (input, init = {}) => {
|
|
551
|
+
if (!this.dispatcher) return this.fetchImpl(input, init);
|
|
552
|
+
return this.fetchImpl(input, { ...init, dispatcher: this.dispatcher });
|
|
553
|
+
};
|
|
554
|
+
};
|
|
555
|
+
function shouldRetryLibreNmsRequest(error) {
|
|
556
|
+
if (error instanceof TransportError) return true;
|
|
557
|
+
if (error instanceof ParseError) return true;
|
|
558
|
+
if (error instanceof UnexpectedStatusError) return error.status >= 500;
|
|
559
|
+
return false;
|
|
560
|
+
}
|
|
561
|
+
function mapLibreNmsRequestError(error) {
|
|
562
|
+
if (error instanceof UnexpectedStatusError) {
|
|
563
|
+
if (error.status >= 500) return new LibreNmsUnreachableError(`HTTP ${error.status}`);
|
|
564
|
+
return new LibreNmsClientError(error.status, responseErrorMessage(error.body));
|
|
565
|
+
}
|
|
566
|
+
if (error instanceof TimeoutError) {
|
|
567
|
+
return new LibreNmsUnreachableError(
|
|
568
|
+
`${error.method} ${error.path} timed out after ${error.timeoutMs}ms`
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
if (error instanceof TransportError) {
|
|
572
|
+
const cause = error.cause;
|
|
573
|
+
return new LibreNmsUnreachableError(boundaryErrorMessage(cause));
|
|
574
|
+
}
|
|
575
|
+
if (error instanceof ParseError) {
|
|
576
|
+
return new LibreNmsUnreachableError(boundaryErrorMessage(error.cause ?? error.message));
|
|
577
|
+
}
|
|
578
|
+
return new LibreNmsUnreachableError(boundaryErrorMessage(error));
|
|
579
|
+
}
|
|
580
|
+
function responseErrorMessage(bodyText) {
|
|
581
|
+
try {
|
|
582
|
+
return JSON.parse(bodyText).message ?? bodyText;
|
|
583
|
+
} catch {
|
|
584
|
+
return bodyText;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// src/security.ts
|
|
589
|
+
var SECRETS = /* @__PURE__ */ new Set();
|
|
590
|
+
var BASE64_TOKEN_RE = /[A-Za-z0-9+/=]{12,}/g;
|
|
591
|
+
function registerSecret(s) {
|
|
592
|
+
if (s && s.length > 0) SECRETS.add(s);
|
|
593
|
+
}
|
|
594
|
+
function maskString(s) {
|
|
595
|
+
let out = s;
|
|
596
|
+
for (const secret of SECRETS) {
|
|
597
|
+
if (out.includes(secret)) out = out.split(secret).join("REDACTED");
|
|
598
|
+
}
|
|
599
|
+
out = out.replace(BASE64_TOKEN_RE, (token) => {
|
|
600
|
+
try {
|
|
601
|
+
const decoded = Buffer.from(token, "base64").toString("utf8");
|
|
602
|
+
for (const secret of SECRETS) {
|
|
603
|
+
if (decoded.includes(secret)) return "REDACTED";
|
|
604
|
+
}
|
|
605
|
+
} catch {
|
|
606
|
+
}
|
|
607
|
+
return token;
|
|
608
|
+
});
|
|
609
|
+
return out;
|
|
610
|
+
}
|
|
611
|
+
function redact(value) {
|
|
612
|
+
if (typeof value === "string") return maskString(value);
|
|
613
|
+
if (Array.isArray(value)) return value.map(redact);
|
|
614
|
+
if (value && typeof value === "object") {
|
|
615
|
+
const out = {};
|
|
616
|
+
for (const [k, v] of Object.entries(value)) out[k] = redact(v);
|
|
617
|
+
return out;
|
|
618
|
+
}
|
|
619
|
+
return value;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// src/validate.ts
|
|
623
|
+
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
624
|
+
var ValidationError = class extends Error {
|
|
625
|
+
constructor(message) {
|
|
626
|
+
super(message);
|
|
627
|
+
this.name = "ValidationError";
|
|
628
|
+
}
|
|
629
|
+
};
|
|
630
|
+
var compiledCache = /* @__PURE__ */ new WeakMap();
|
|
631
|
+
function getChecker(schema) {
|
|
632
|
+
let checker = compiledCache.get(schema);
|
|
633
|
+
if (!checker) {
|
|
634
|
+
checker = TypeCompiler.Compile(schema);
|
|
635
|
+
compiledCache.set(schema, checker);
|
|
636
|
+
}
|
|
637
|
+
return checker;
|
|
638
|
+
}
|
|
639
|
+
function validateToolArgs(schema, toolName, args) {
|
|
640
|
+
const checker = getChecker(schema);
|
|
641
|
+
if (checker.Check(args)) return;
|
|
642
|
+
const first = checker.Errors(args).First();
|
|
643
|
+
const where = first?.path ? ` at ${first.path}` : "";
|
|
644
|
+
const detail = first ? `${first.message}${where}` : "schema mismatch";
|
|
645
|
+
throw new ValidationError(
|
|
646
|
+
`Invalid arguments for ${toolName}: ${detail}`
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// src/tools/librenms_status.ts
|
|
651
|
+
import { Type } from "@sinclair/typebox";
|
|
652
|
+
|
|
653
|
+
// src/tools/_util.ts
|
|
654
|
+
function jsonToolResult(payload) {
|
|
655
|
+
const r = ok(payload);
|
|
656
|
+
return { content: r.content };
|
|
657
|
+
}
|
|
658
|
+
function safeInt(value, label, opts = {}) {
|
|
659
|
+
const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
|
|
660
|
+
if (!Number.isInteger(n)) {
|
|
661
|
+
throw new Error(`${label} must be an integer, got: ${String(value)}`);
|
|
662
|
+
}
|
|
663
|
+
const min = opts.min ?? 1;
|
|
664
|
+
if (n < min) throw new Error(`${label} must be >= ${min}, got: ${n}`);
|
|
665
|
+
if (opts.max !== void 0 && n > opts.max) {
|
|
666
|
+
throw new Error(`${label} must be <= ${opts.max}, got: ${n}`);
|
|
667
|
+
}
|
|
668
|
+
return n;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// src/tools/librenms_status.ts
|
|
672
|
+
var Schema = Type.Object({}, { additionalProperties: false });
|
|
673
|
+
function createLibrenmsStatusTool(getClient) {
|
|
674
|
+
return {
|
|
675
|
+
name: "librenms_status",
|
|
676
|
+
label: "librenms: status",
|
|
677
|
+
description: "LibreNMS system health (version, totals, last poll) via GET /api/v0/system.",
|
|
678
|
+
parameters: Schema,
|
|
679
|
+
execute: async () => {
|
|
680
|
+
const client = getClient();
|
|
681
|
+
const r = await client.get("/system");
|
|
682
|
+
return jsonToolResult({ system: r.system?.[0] ?? null });
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// src/tools/librenms_list_devices.ts
|
|
688
|
+
import { Type as Type2 } from "@sinclair/typebox";
|
|
689
|
+
var Schema2 = Type2.Object(
|
|
690
|
+
{
|
|
691
|
+
type: Type2.Optional(
|
|
692
|
+
Type2.Union(
|
|
693
|
+
[
|
|
694
|
+
Type2.Literal("all"),
|
|
695
|
+
Type2.Literal("up"),
|
|
696
|
+
Type2.Literal("down"),
|
|
697
|
+
Type2.Literal("ignored"),
|
|
698
|
+
Type2.Literal("disabled")
|
|
699
|
+
],
|
|
700
|
+
{ description: "Device filter type. Default 'all'." }
|
|
701
|
+
)
|
|
702
|
+
)
|
|
703
|
+
},
|
|
704
|
+
{ additionalProperties: false }
|
|
705
|
+
);
|
|
706
|
+
function createLibrenmsListDevicesTool(getClient) {
|
|
707
|
+
return {
|
|
708
|
+
name: "librenms_list_devices",
|
|
709
|
+
label: "librenms: list devices",
|
|
710
|
+
description: "List devices monitored by LibreNMS via GET /api/v0/devices. Optional type filter (all|up|down|ignored|disabled).",
|
|
711
|
+
parameters: Schema2,
|
|
712
|
+
execute: async (_id, raw) => {
|
|
713
|
+
const args = raw ?? {};
|
|
714
|
+
const path = args.type ? `/devices?type=${encodeURIComponent(args.type)}` : "/devices";
|
|
715
|
+
const client = getClient();
|
|
716
|
+
const r = await client.get(path);
|
|
717
|
+
return jsonToolResult({ devices: r.devices ?? [] });
|
|
718
|
+
}
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// src/tools/librenms_get_device.ts
|
|
723
|
+
import { Type as Type3 } from "@sinclair/typebox";
|
|
724
|
+
var Schema3 = Type3.Object(
|
|
725
|
+
{
|
|
726
|
+
hostname: Type3.String({
|
|
727
|
+
description: "Device hostname or IP as configured in LibreNMS."
|
|
728
|
+
})
|
|
729
|
+
},
|
|
730
|
+
{ additionalProperties: false }
|
|
731
|
+
);
|
|
732
|
+
function createLibrenmsGetDeviceTool(getClient) {
|
|
733
|
+
return {
|
|
734
|
+
name: "librenms_get_device",
|
|
735
|
+
label: "librenms: get device",
|
|
736
|
+
description: "Fetch a single device by hostname via GET /api/v0/devices/{hostname}.",
|
|
737
|
+
parameters: Schema3,
|
|
738
|
+
execute: async (_id, raw) => {
|
|
739
|
+
const args = raw;
|
|
740
|
+
const client = getClient();
|
|
741
|
+
const r = await client.get(`/devices/${encodeURIComponent(args.hostname)}`);
|
|
742
|
+
return jsonToolResult({ device: r.devices?.[0] ?? null });
|
|
743
|
+
}
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// src/tools/librenms_list_ports.ts
|
|
748
|
+
import { Type as Type4 } from "@sinclair/typebox";
|
|
749
|
+
var Schema4 = Type4.Object(
|
|
750
|
+
{
|
|
751
|
+
hostname: Type4.String({
|
|
752
|
+
description: "Device hostname or IP as configured in LibreNMS."
|
|
753
|
+
})
|
|
754
|
+
},
|
|
755
|
+
{ additionalProperties: false }
|
|
756
|
+
);
|
|
757
|
+
var COLUMNS = "ifName,ifAdminStatus,ifOperStatus,ifInErrors,ifOutErrors,ifSpeed,ifDescr";
|
|
758
|
+
function createLibrenmsListPortsTool(getClient) {
|
|
759
|
+
return {
|
|
760
|
+
name: "librenms_list_ports",
|
|
761
|
+
label: "librenms: list ports",
|
|
762
|
+
description: "List ports on a device via GET /api/v0/devices/{hostname}/ports with a fixed column set (name, status, errors, speed, descr).",
|
|
763
|
+
parameters: Schema4,
|
|
764
|
+
execute: async (_id, raw) => {
|
|
765
|
+
const args = raw;
|
|
766
|
+
const client = getClient();
|
|
767
|
+
const r = await client.get(`/devices/${encodeURIComponent(args.hostname)}/ports?columns=${COLUMNS}`);
|
|
768
|
+
return jsonToolResult({ ports: r.ports ?? [] });
|
|
769
|
+
}
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
// src/tools/librenms_port_health.ts
|
|
774
|
+
import { Type as Type5 } from "@sinclair/typebox";
|
|
775
|
+
var Schema5 = Type5.Object(
|
|
776
|
+
{
|
|
777
|
+
limit: Type5.Optional(
|
|
778
|
+
Type5.Integer({
|
|
779
|
+
minimum: 1,
|
|
780
|
+
description: "Number of top ports to return. Default 10."
|
|
781
|
+
})
|
|
782
|
+
),
|
|
783
|
+
metric: Type5.Optional(
|
|
784
|
+
Type5.Union(
|
|
785
|
+
[
|
|
786
|
+
Type5.Literal("errors_in"),
|
|
787
|
+
Type5.Literal("errors_out"),
|
|
788
|
+
Type5.Literal("utilization")
|
|
789
|
+
],
|
|
790
|
+
{ description: "Ranking metric. Default 'errors_in'." }
|
|
791
|
+
)
|
|
792
|
+
)
|
|
793
|
+
},
|
|
794
|
+
{ additionalProperties: false }
|
|
795
|
+
);
|
|
796
|
+
var COLUMNS2 = "device_id,ifName,ifInErrors,ifOutErrors,ifSpeed,ifInOctets,ifOutOctets";
|
|
797
|
+
function createLibrenmsPortHealthTool(getClient) {
|
|
798
|
+
return {
|
|
799
|
+
name: "librenms_port_health",
|
|
800
|
+
label: "librenms: port health",
|
|
801
|
+
description: "Rank ports by errors_in (default), errors_out, or utilization via GET /api/v0/ports with client-side sort.",
|
|
802
|
+
parameters: Schema5,
|
|
803
|
+
execute: async (_id, raw) => {
|
|
804
|
+
const args = raw ?? {};
|
|
805
|
+
const limit = args.limit ?? 10;
|
|
806
|
+
const metric = args.metric ?? "errors_in";
|
|
807
|
+
const client = getClient();
|
|
808
|
+
const r = await client.get(`/ports?columns=${COLUMNS2}`);
|
|
809
|
+
const ports = r.ports ?? [];
|
|
810
|
+
const sorted = ports.slice().sort((a, b) => {
|
|
811
|
+
if (metric === "errors_in") {
|
|
812
|
+
return (b.ifInErrors ?? 0) - (a.ifInErrors ?? 0);
|
|
813
|
+
}
|
|
814
|
+
if (metric === "errors_out") {
|
|
815
|
+
return (b.ifOutErrors ?? 0) - (a.ifOutErrors ?? 0);
|
|
816
|
+
}
|
|
817
|
+
const aUtil = a.ifSpeed ? ((a.ifInOctets ?? 0) + (a.ifOutOctets ?? 0)) / a.ifSpeed : 0;
|
|
818
|
+
const bUtil = b.ifSpeed ? ((b.ifInOctets ?? 0) + (b.ifOutOctets ?? 0)) / b.ifSpeed : 0;
|
|
819
|
+
return bUtil - aUtil;
|
|
820
|
+
});
|
|
821
|
+
return jsonToolResult({ metric, limit, top: sorted.slice(0, limit) });
|
|
822
|
+
}
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// src/tools/librenms_list_alerts.ts
|
|
827
|
+
import { Type as Type6 } from "@sinclair/typebox";
|
|
828
|
+
var Schema6 = Type6.Object(
|
|
829
|
+
{
|
|
830
|
+
state: Type6.Optional(
|
|
831
|
+
Type6.Union(
|
|
832
|
+
[Type6.Literal(0), Type6.Literal(1), Type6.Literal(2)],
|
|
833
|
+
{ description: "Alert state filter: 0=ok, 1=active, 2=ack." }
|
|
834
|
+
)
|
|
835
|
+
)
|
|
836
|
+
},
|
|
837
|
+
{ additionalProperties: false }
|
|
838
|
+
);
|
|
839
|
+
function createLibrenmsListAlertsTool(getClient) {
|
|
840
|
+
return {
|
|
841
|
+
name: "librenms_list_alerts",
|
|
842
|
+
label: "librenms: list alerts",
|
|
843
|
+
description: "List alerts via GET /api/v0/alerts. Optional state filter (0=ok, 1=active, 2=ack).",
|
|
844
|
+
parameters: Schema6,
|
|
845
|
+
execute: async (_id, raw) => {
|
|
846
|
+
const args = raw ?? {};
|
|
847
|
+
const path = args.state !== void 0 ? `/alerts?state=${encodeURIComponent(args.state)}` : "/alerts";
|
|
848
|
+
const client = getClient();
|
|
849
|
+
const r = await client.get(path);
|
|
850
|
+
return jsonToolResult({ alerts: r.alerts ?? [] });
|
|
851
|
+
}
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
// src/tools/librenms_get_alert.ts
|
|
856
|
+
import { Type as Type7 } from "@sinclair/typebox";
|
|
857
|
+
var Schema7 = Type7.Object(
|
|
858
|
+
{
|
|
859
|
+
id: Type7.Integer({ minimum: 1, description: "Alert id." })
|
|
860
|
+
},
|
|
861
|
+
{ additionalProperties: false }
|
|
862
|
+
);
|
|
863
|
+
function createLibrenmsGetAlertTool(getClient) {
|
|
864
|
+
return {
|
|
865
|
+
name: "librenms_get_alert",
|
|
866
|
+
label: "librenms: get alert",
|
|
867
|
+
description: "Fetch a single alert by id via GET /api/v0/alerts/{id}.",
|
|
868
|
+
parameters: Schema7,
|
|
869
|
+
execute: async (_id, raw) => {
|
|
870
|
+
const args = raw;
|
|
871
|
+
const id = safeInt(args.id, "id");
|
|
872
|
+
const client = getClient();
|
|
873
|
+
const r = await client.get(`/alerts/${encodeURIComponent(id)}`);
|
|
874
|
+
return jsonToolResult({ alert: r.alerts?.[0] ?? null });
|
|
875
|
+
}
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
// src/tools/librenms_alert_history.ts
|
|
880
|
+
import { Type as Type8 } from "@sinclair/typebox";
|
|
881
|
+
var Schema8 = Type8.Object(
|
|
882
|
+
{
|
|
883
|
+
device_id: Type8.Optional(
|
|
884
|
+
Type8.Integer({
|
|
885
|
+
minimum: 1,
|
|
886
|
+
description: "Optional device id to scope the alert log."
|
|
887
|
+
})
|
|
888
|
+
),
|
|
889
|
+
limit: Type8.Optional(
|
|
890
|
+
Type8.Integer({
|
|
891
|
+
minimum: 1,
|
|
892
|
+
description: "Max number of log entries. Default 25."
|
|
893
|
+
})
|
|
894
|
+
)
|
|
895
|
+
},
|
|
896
|
+
{ additionalProperties: false }
|
|
897
|
+
);
|
|
898
|
+
function createLibrenmsAlertHistoryTool(getClient) {
|
|
899
|
+
return {
|
|
900
|
+
name: "librenms_alert_history",
|
|
901
|
+
label: "librenms: alert history",
|
|
902
|
+
description: "Recent alert log entries via GET /api/v0/logs/alertlog (optionally scoped to a device_id).",
|
|
903
|
+
parameters: Schema8,
|
|
904
|
+
execute: async (_id, raw) => {
|
|
905
|
+
const args = raw ?? {};
|
|
906
|
+
const limit = safeInt(args.limit ?? 25, "limit");
|
|
907
|
+
const path = args.device_id !== void 0 ? `/logs/alertlog/${encodeURIComponent(
|
|
908
|
+
safeInt(args.device_id, "device_id")
|
|
909
|
+
)}?limit=${encodeURIComponent(limit)}` : `/logs/alertlog?limit=${encodeURIComponent(limit)}`;
|
|
910
|
+
const client = getClient();
|
|
911
|
+
const r = await client.get(path);
|
|
912
|
+
return jsonToolResult({
|
|
913
|
+
count: r.logs?.length ?? 0,
|
|
914
|
+
logs: r.logs ?? []
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// src/tools/librenms_ack_alert.ts
|
|
921
|
+
import { Type as Type9 } from "@sinclair/typebox";
|
|
922
|
+
|
|
923
|
+
// src/gates.ts
|
|
924
|
+
var WriteGateError = class extends Error {
|
|
925
|
+
constructor(message) {
|
|
926
|
+
super(message);
|
|
927
|
+
this.name = "WriteGateError";
|
|
928
|
+
}
|
|
929
|
+
};
|
|
930
|
+
function assertConfirmedWrite(args, toolName) {
|
|
931
|
+
if (args.confirm !== true) {
|
|
932
|
+
throw new WriteGateError(`${toolName} is a write operation. Pass {"confirm": true} to proceed.`);
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
// src/tools/librenms_ack_alert.ts
|
|
937
|
+
var Schema9 = Type9.Object(
|
|
938
|
+
{
|
|
939
|
+
id: Type9.Integer({ minimum: 1, description: "Alert id to acknowledge." }),
|
|
940
|
+
note: Type9.Optional(
|
|
941
|
+
Type9.String({ description: "Optional acknowledgement note." })
|
|
942
|
+
),
|
|
943
|
+
until_clear: Type9.Optional(
|
|
944
|
+
Type9.Boolean({
|
|
945
|
+
description: "When true, the ack persists until the alert clears (default LibreNMS behavior: ack until next state change)."
|
|
946
|
+
})
|
|
947
|
+
),
|
|
948
|
+
confirm: Type9.Boolean({
|
|
949
|
+
description: "Must be true to write. Tier-2 safe-write gate."
|
|
950
|
+
})
|
|
951
|
+
},
|
|
952
|
+
{ additionalProperties: false }
|
|
953
|
+
);
|
|
954
|
+
var NAME = "librenms_ack_alert";
|
|
955
|
+
function createLibrenmsAckAlertTool(getClient) {
|
|
956
|
+
return {
|
|
957
|
+
name: NAME,
|
|
958
|
+
label: "librenms: ack alert",
|
|
959
|
+
description: "Acknowledge an active alert by id via PUT /api/v0/alerts/{id}. Tier-2 write; requires confirm:true.",
|
|
960
|
+
parameters: Schema9,
|
|
961
|
+
execute: async (_id, raw) => {
|
|
962
|
+
assertConfirmedWrite(raw, NAME);
|
|
963
|
+
const args = raw;
|
|
964
|
+
const id = safeInt(args.id, "id");
|
|
965
|
+
const client = getClient();
|
|
966
|
+
const body = {};
|
|
967
|
+
if (args.note !== void 0) body.note = args.note;
|
|
968
|
+
if (args.until_clear !== void 0) body.until_clear = args.until_clear;
|
|
969
|
+
const r = await client.put(`/alerts/${encodeURIComponent(id)}`, body);
|
|
970
|
+
return jsonToolResult({ alert_id: id, acked: true, response: r });
|
|
971
|
+
}
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
// src/tools/librenms_set_maintenance.ts
|
|
976
|
+
import { Type as Type10 } from "@sinclair/typebox";
|
|
977
|
+
var DURATION_RE = /^\d+:\d{2}$/;
|
|
978
|
+
var START_RE = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
|
|
979
|
+
var Schema10 = Type10.Object(
|
|
980
|
+
{
|
|
981
|
+
hostname: Type10.String({
|
|
982
|
+
description: "Device hostname or IP as configured in LibreNMS."
|
|
983
|
+
}),
|
|
984
|
+
duration: Type10.String({
|
|
985
|
+
description: "Maintenance duration. LibreNMS format `H:i`, e.g. `2:00` for 2 hours or `0:30` for 30 minutes."
|
|
986
|
+
}),
|
|
987
|
+
title: Type10.Optional(
|
|
988
|
+
Type10.String({ description: "Maintenance window title." })
|
|
989
|
+
),
|
|
990
|
+
notes: Type10.Optional(Type10.String({ description: "Free-text notes." })),
|
|
991
|
+
start: Type10.Optional(
|
|
992
|
+
Type10.String({
|
|
993
|
+
description: "Start time. LibreNMS format `Y-m-d H:i:00`, e.g. `2026-05-17 14:30:00`. Default: server now."
|
|
994
|
+
})
|
|
995
|
+
),
|
|
996
|
+
confirm: Type10.Boolean({
|
|
997
|
+
description: "Must be true to write. Tier-2 safe-write gate."
|
|
998
|
+
})
|
|
999
|
+
},
|
|
1000
|
+
{ additionalProperties: false }
|
|
1001
|
+
);
|
|
1002
|
+
var NAME2 = "librenms_set_maintenance";
|
|
1003
|
+
function createLibrenmsSetMaintenanceTool(getClient) {
|
|
1004
|
+
return {
|
|
1005
|
+
name: NAME2,
|
|
1006
|
+
label: "librenms: set maintenance",
|
|
1007
|
+
description: "Put a device into a maintenance window (suppresses alerts) via POST /api/v0/devices/{hostname}/maintenance. Tier-2 write; requires confirm:true.",
|
|
1008
|
+
parameters: Schema10,
|
|
1009
|
+
execute: async (_id, raw) => {
|
|
1010
|
+
assertConfirmedWrite(raw, NAME2);
|
|
1011
|
+
const args = raw;
|
|
1012
|
+
if (!DURATION_RE.test(args.duration)) {
|
|
1013
|
+
throw new Error(
|
|
1014
|
+
`duration must be H:i format (e.g. "2:00" or "0:30"), got: ${args.duration}`
|
|
1015
|
+
);
|
|
1016
|
+
}
|
|
1017
|
+
if (args.start && !START_RE.test(args.start)) {
|
|
1018
|
+
throw new Error(
|
|
1019
|
+
`start must be Y-m-d H:i:00 format (e.g. "2026-05-17 14:30:00"), got: ${args.start}`
|
|
1020
|
+
);
|
|
1021
|
+
}
|
|
1022
|
+
const client = getClient();
|
|
1023
|
+
const body = { duration: args.duration };
|
|
1024
|
+
if (args.title) body.title = args.title;
|
|
1025
|
+
if (args.notes) body.notes = args.notes;
|
|
1026
|
+
if (args.start) body.start = args.start;
|
|
1027
|
+
const r = await client.post(
|
|
1028
|
+
`/devices/${encodeURIComponent(args.hostname)}/maintenance`,
|
|
1029
|
+
body
|
|
1030
|
+
);
|
|
1031
|
+
return jsonToolResult({ hostname: args.hostname, maintenance: r });
|
|
1032
|
+
}
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
// src/tools/librenms_get_port.ts
|
|
1037
|
+
import { Type as Type11 } from "@sinclair/typebox";
|
|
1038
|
+
var Schema11 = Type11.Object(
|
|
1039
|
+
{
|
|
1040
|
+
port_id: Type11.Integer({
|
|
1041
|
+
minimum: 1,
|
|
1042
|
+
description: "LibreNMS internal port id (from librenms_list_ports response rows)."
|
|
1043
|
+
})
|
|
1044
|
+
},
|
|
1045
|
+
{ additionalProperties: false }
|
|
1046
|
+
);
|
|
1047
|
+
function createLibrenmsGetPortTool(getClient) {
|
|
1048
|
+
return {
|
|
1049
|
+
name: "librenms_get_port",
|
|
1050
|
+
label: "librenms: get port",
|
|
1051
|
+
description: "Single-port detail via GET /api/v0/ports/{port_id}. Returns full column set (admin/oper state, traffic + error counters, ifAlias, etc.).",
|
|
1052
|
+
parameters: Schema11,
|
|
1053
|
+
execute: async (_id, raw) => {
|
|
1054
|
+
const args = raw;
|
|
1055
|
+
const portId = safeInt(args.port_id, "port_id");
|
|
1056
|
+
const client = getClient();
|
|
1057
|
+
const r = await client.get(`/ports/${encodeURIComponent(portId)}`);
|
|
1058
|
+
return jsonToolResult({ port: r.port?.[0] ?? null });
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
// src/tools/librenms_event_log.ts
|
|
1064
|
+
import { Type as Type12 } from "@sinclair/typebox";
|
|
1065
|
+
var Schema12 = Type12.Object(
|
|
1066
|
+
{
|
|
1067
|
+
device_id: Type12.Optional(
|
|
1068
|
+
Type12.Integer({
|
|
1069
|
+
minimum: 1,
|
|
1070
|
+
description: "Optional device id to scope the event log."
|
|
1071
|
+
})
|
|
1072
|
+
),
|
|
1073
|
+
limit: Type12.Optional(
|
|
1074
|
+
Type12.Integer({
|
|
1075
|
+
minimum: 1,
|
|
1076
|
+
description: "Max number of log entries. Default 25."
|
|
1077
|
+
})
|
|
1078
|
+
)
|
|
1079
|
+
},
|
|
1080
|
+
{ additionalProperties: false }
|
|
1081
|
+
);
|
|
1082
|
+
function createLibrenmsEventLogTool(getClient) {
|
|
1083
|
+
return {
|
|
1084
|
+
name: "librenms_event_log",
|
|
1085
|
+
label: "librenms: event log",
|
|
1086
|
+
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.",
|
|
1087
|
+
parameters: Schema12,
|
|
1088
|
+
execute: async (_id, raw) => {
|
|
1089
|
+
const args = raw ?? {};
|
|
1090
|
+
const limit = safeInt(args.limit ?? 25, "limit");
|
|
1091
|
+
const path = args.device_id !== void 0 ? `/logs/eventlog/${encodeURIComponent(
|
|
1092
|
+
safeInt(args.device_id, "device_id")
|
|
1093
|
+
)}?limit=${encodeURIComponent(limit)}` : `/logs/eventlog?limit=${encodeURIComponent(limit)}`;
|
|
1094
|
+
const client = getClient();
|
|
1095
|
+
const r = await client.get(path);
|
|
1096
|
+
return jsonToolResult({
|
|
1097
|
+
count: r.logs?.length ?? 0,
|
|
1098
|
+
logs: r.logs ?? []
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
};
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
// src/tools/librenms_unmute_alert.ts
|
|
1105
|
+
import { Type as Type13 } from "@sinclair/typebox";
|
|
1106
|
+
var Schema13 = Type13.Object(
|
|
1107
|
+
{
|
|
1108
|
+
id: Type13.Integer({ minimum: 1, description: "Alert id to unmute." }),
|
|
1109
|
+
note: Type13.Optional(
|
|
1110
|
+
Type13.String({
|
|
1111
|
+
description: "Optional note appended to the alert audit trail (LibreNMS prefixes it with the API user + timestamp)."
|
|
1112
|
+
})
|
|
1113
|
+
),
|
|
1114
|
+
confirm: Type13.Boolean({
|
|
1115
|
+
description: "Must be true to write. Tier-2 safe-write gate."
|
|
1116
|
+
})
|
|
1117
|
+
},
|
|
1118
|
+
{ additionalProperties: false }
|
|
1119
|
+
);
|
|
1120
|
+
var NAME3 = "librenms_unmute_alert";
|
|
1121
|
+
function createLibrenmsUnmuteAlertTool(getClient) {
|
|
1122
|
+
return {
|
|
1123
|
+
name: NAME3,
|
|
1124
|
+
label: "librenms: unmute alert",
|
|
1125
|
+
description: "Unmute an alert by id via PUT /api/v0/alerts/unmute/{id} (companion to librenms_ack_alert). Tier-2 write; requires confirm:true.",
|
|
1126
|
+
parameters: Schema13,
|
|
1127
|
+
execute: async (_id, raw) => {
|
|
1128
|
+
assertConfirmedWrite(raw, NAME3);
|
|
1129
|
+
const args = raw;
|
|
1130
|
+
const id = safeInt(args.id, "id");
|
|
1131
|
+
const client = getClient();
|
|
1132
|
+
const body = {};
|
|
1133
|
+
if (args.note !== void 0) body.note = args.note;
|
|
1134
|
+
const r = await client.put(`/alerts/unmute/${encodeURIComponent(id)}`, body);
|
|
1135
|
+
return jsonToolResult({ alert_id: id, unmuted: true, response: r });
|
|
1136
|
+
}
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
// mcp-server.ts
|
|
1141
|
+
function createServer() {
|
|
1142
|
+
const cfg = resolveConfig(process.env);
|
|
1143
|
+
registerSecret(cfg.token);
|
|
1144
|
+
const getClient = () => new LibreNmsClient(cfg);
|
|
1145
|
+
const tools = [
|
|
1146
|
+
createLibrenmsStatusTool(getClient),
|
|
1147
|
+
createLibrenmsListDevicesTool(getClient),
|
|
1148
|
+
createLibrenmsGetDeviceTool(getClient),
|
|
1149
|
+
createLibrenmsListPortsTool(getClient),
|
|
1150
|
+
createLibrenmsPortHealthTool(getClient),
|
|
1151
|
+
createLibrenmsListAlertsTool(getClient),
|
|
1152
|
+
createLibrenmsGetAlertTool(getClient),
|
|
1153
|
+
createLibrenmsAlertHistoryTool(getClient),
|
|
1154
|
+
createLibrenmsAckAlertTool(getClient),
|
|
1155
|
+
createLibrenmsSetMaintenanceTool(getClient),
|
|
1156
|
+
createLibrenmsGetPortTool(getClient),
|
|
1157
|
+
createLibrenmsEventLogTool(getClient),
|
|
1158
|
+
createLibrenmsUnmuteAlertTool(getClient)
|
|
1159
|
+
];
|
|
1160
|
+
const toolMap = new Map(tools.map((t) => [t.name, t]));
|
|
1161
|
+
const server = new Server({ name: "librenms-mcp", version: "0.2.2" }, { capabilities: { tools: {} } });
|
|
1162
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
1163
|
+
tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.parameters }))
|
|
1164
|
+
}));
|
|
1165
|
+
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
1166
|
+
const t = toolMap.get(req.params.name);
|
|
1167
|
+
if (!t) {
|
|
1168
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: `unknown tool: ${req.params.name}` }) }], isError: true };
|
|
1169
|
+
}
|
|
1170
|
+
try {
|
|
1171
|
+
const args = req.params.arguments ?? {};
|
|
1172
|
+
validateToolArgs(t.parameters, t.name, args);
|
|
1173
|
+
return await t.execute(req.params.name, args);
|
|
1174
|
+
} catch (e) {
|
|
1175
|
+
return mcpErrorResult(e);
|
|
1176
|
+
}
|
|
1177
|
+
});
|
|
1178
|
+
return server;
|
|
1179
|
+
}
|
|
1180
|
+
function mcpErrorResult(error) {
|
|
1181
|
+
const msg = redact(boundaryErrorMessage(error));
|
|
1182
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: msg }) }], isError: true };
|
|
1183
|
+
}
|
|
1184
|
+
async function serve() {
|
|
1185
|
+
const server = createServer();
|
|
1186
|
+
const transport = new StdioServerTransport();
|
|
1187
|
+
const __send = transport.send.bind(transport);
|
|
1188
|
+
transport.send = (message) => {
|
|
1189
|
+
const tools = message?.result?.tools;
|
|
1190
|
+
if (Array.isArray(tools)) {
|
|
1191
|
+
for (const t of tools) {
|
|
1192
|
+
if (t?.inputSchema) delete t.inputSchema.$schema;
|
|
1193
|
+
if (t?.outputSchema) delete t.outputSchema.$schema;
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
return __send(message);
|
|
1197
|
+
};
|
|
1198
|
+
await server.connect(transport);
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
// mcp-bin.ts
|
|
1202
|
+
serve().catch((error) => {
|
|
1203
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
1204
|
+
console.error(`librenms-mcp fatal: ${msg}`);
|
|
1205
|
+
process.exit(1);
|
|
1206
|
+
});
|