@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/index.js
CHANGED
|
@@ -4,29 +4,452 @@
|
|
|
4
4
|
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
5
5
|
|
|
6
6
|
// src/config.ts
|
|
7
|
-
|
|
7
|
+
import { Effect as Effect6 } from "effect";
|
|
8
|
+
|
|
9
|
+
// node_modules/@lidless-labs/effect-operator-kit/dist/index.js
|
|
10
|
+
import { Data } from "effect";
|
|
11
|
+
import { Effect } from "effect";
|
|
12
|
+
import { Effect as Effect2 } from "effect";
|
|
13
|
+
import { Duration, Effect as Effect3, Schedule } from "effect";
|
|
14
|
+
import { Cause, Effect as Effect4, Exit } from "effect";
|
|
15
|
+
import { Cause as Cause2, Effect as Effect5 } from "effect";
|
|
16
|
+
var ConfigError = class extends Data.TaggedError("ConfigError") {
|
|
17
|
+
};
|
|
18
|
+
var AuthError = class extends Data.TaggedError("AuthError") {
|
|
19
|
+
};
|
|
20
|
+
var ForbiddenError = class extends Data.TaggedError("ForbiddenError") {
|
|
21
|
+
};
|
|
22
|
+
var NotFoundError = class extends Data.TaggedError("NotFoundError") {
|
|
23
|
+
};
|
|
24
|
+
var TimeoutError = class extends Data.TaggedError("TimeoutError") {
|
|
25
|
+
};
|
|
26
|
+
var TransportError = class extends Data.TaggedError("TransportError") {
|
|
27
|
+
};
|
|
28
|
+
var ParseError = class extends Data.TaggedError("ParseError") {
|
|
29
|
+
};
|
|
30
|
+
var UnexpectedStatusError = class extends Data.TaggedError("UnexpectedStatusError") {
|
|
31
|
+
};
|
|
32
|
+
var fromProcessEnv = (env) => ({
|
|
33
|
+
get: (key) => (env ?? process.env)[key]
|
|
34
|
+
});
|
|
35
|
+
var isBlank = (raw) => raw === void 0 || raw.trim() === "";
|
|
36
|
+
var failConfig = (partial) => Effect.fail(new ConfigError(partial));
|
|
37
|
+
var readRaw = (env, key) => env.get(key);
|
|
38
|
+
var TRUE_TOKENS = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
|
|
39
|
+
var FALSE_TOKENS = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
|
|
40
|
+
var parseBooleanEnv = (env, key, fallback) => {
|
|
41
|
+
const raw = readRaw(env, key);
|
|
42
|
+
if (isBlank(raw)) {
|
|
43
|
+
return Effect.succeed(fallback);
|
|
44
|
+
}
|
|
45
|
+
const token = raw.trim().toLowerCase();
|
|
46
|
+
if (TRUE_TOKENS.has(token)) {
|
|
47
|
+
return Effect.succeed(true);
|
|
48
|
+
}
|
|
49
|
+
if (FALSE_TOKENS.has(token)) {
|
|
50
|
+
return Effect.succeed(false);
|
|
51
|
+
}
|
|
52
|
+
return failConfig({
|
|
53
|
+
key,
|
|
54
|
+
value: raw,
|
|
55
|
+
message: `${key} must be a boolean (true/false, 1/0, yes/no, on/off)`
|
|
56
|
+
});
|
|
57
|
+
};
|
|
58
|
+
var parseTimeoutEnv = (env, key, opts) => {
|
|
59
|
+
const raw = readRaw(env, key);
|
|
60
|
+
if (isBlank(raw)) {
|
|
61
|
+
return Effect.succeed(opts.fallbackMs);
|
|
62
|
+
}
|
|
63
|
+
const parsed = Number(raw.trim());
|
|
64
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
65
|
+
return failConfig({
|
|
66
|
+
key,
|
|
67
|
+
value: raw,
|
|
68
|
+
message: `${key} must be a positive timeout`
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
const unit = opts.unit ?? "s";
|
|
72
|
+
const ms = unit === "ms" ? parsed : parsed * 1e3;
|
|
73
|
+
if (opts.minMs !== void 0 && ms < opts.minMs) {
|
|
74
|
+
return failConfig({
|
|
75
|
+
key,
|
|
76
|
+
value: raw,
|
|
77
|
+
message: `${key} must be at least ${opts.minMs}ms`
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
if (opts.maxMs !== void 0 && ms > opts.maxMs) {
|
|
81
|
+
return failConfig({
|
|
82
|
+
key,
|
|
83
|
+
value: raw,
|
|
84
|
+
message: `${key} must be at most ${opts.maxMs}ms`
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
return Effect.succeed(ms);
|
|
88
|
+
};
|
|
89
|
+
var SECRET_PATTERNS = [
|
|
90
|
+
/(authorization:\s*)(basic|bearer)\s+[a-z0-9._~+/=-]+/gi,
|
|
91
|
+
/\b(basic|bearer)\s+[a-z0-9._~+/=-]+/gi,
|
|
92
|
+
/(authorization:\s*)(?:token|digest|hawk|oauth|apikey)\s+\S+/gi,
|
|
93
|
+
/(x-n8n-api-key|x-auth-token|x-emby-token|x-api-key)\s*:\s*\S+/gi,
|
|
94
|
+
/(https?:\/\/)([^@\s/]+)@/gi,
|
|
95
|
+
/([?&](?:access_token|refresh_token|client_secret|id_token|x-api-key|\w+_(?:token|secret)|password|token|secret|api[_-]?key|key)=)[^&\s]+/gi,
|
|
96
|
+
/\beyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\b/g
|
|
97
|
+
];
|
|
98
|
+
var MAX_LENGTH = 500;
|
|
99
|
+
var redactString = (message, secrets = []) => {
|
|
100
|
+
let sanitized = message;
|
|
101
|
+
for (const secret of secrets) {
|
|
102
|
+
if (secret) {
|
|
103
|
+
sanitized = sanitized.split(secret).join("[REDACTED]");
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
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]");
|
|
107
|
+
return sanitized.length > MAX_LENGTH ? `${sanitized.slice(0, MAX_LENGTH)}...` : sanitized;
|
|
108
|
+
};
|
|
109
|
+
var defaultRedact = (value) => redactString(value);
|
|
110
|
+
var DEFAULT_SUCCESS_STATUSES = Array.from({ length: 100 }, (_, i) => 200 + i);
|
|
111
|
+
function redactBody(text, redact2) {
|
|
112
|
+
return (redact2 ?? defaultRedact)(text);
|
|
113
|
+
}
|
|
114
|
+
function mergeHeaders(...sources) {
|
|
115
|
+
const merged = new Headers();
|
|
116
|
+
for (const source of sources) {
|
|
117
|
+
if (!source) continue;
|
|
118
|
+
const headers = new Headers(source);
|
|
119
|
+
headers.forEach((value, key) => merged.set(key, value));
|
|
120
|
+
}
|
|
121
|
+
return merged;
|
|
122
|
+
}
|
|
123
|
+
function resolveExpectedStatuses(req) {
|
|
124
|
+
return req.expectedStatuses ?? DEFAULT_SUCCESS_STATUSES;
|
|
125
|
+
}
|
|
126
|
+
function isExpectedStatus(status, expected) {
|
|
127
|
+
return expected.includes(status);
|
|
128
|
+
}
|
|
129
|
+
function resolveBodyEncoding(req) {
|
|
130
|
+
if (req.bodyEncoding !== void 0) return req.bodyEncoding;
|
|
131
|
+
return req.body !== void 0 ? "json" : "none";
|
|
132
|
+
}
|
|
133
|
+
function setContentTypeIfAbsent(headers, contentType) {
|
|
134
|
+
if (!headers.has("content-type")) {
|
|
135
|
+
headers.set("content-type", contentType);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function buildRequestBody(req, headers) {
|
|
139
|
+
const encoding = resolveBodyEncoding(req);
|
|
140
|
+
switch (encoding) {
|
|
141
|
+
case "none":
|
|
142
|
+
return void 0;
|
|
143
|
+
case "json":
|
|
144
|
+
setContentTypeIfAbsent(headers, "application/json");
|
|
145
|
+
return JSON.stringify(req.body);
|
|
146
|
+
case "text":
|
|
147
|
+
setContentTypeIfAbsent(headers, "text/plain");
|
|
148
|
+
return String(req.body);
|
|
149
|
+
case "form": {
|
|
150
|
+
setContentTypeIfAbsent(
|
|
151
|
+
headers,
|
|
152
|
+
"application/x-www-form-urlencoded"
|
|
153
|
+
);
|
|
154
|
+
const params = new URLSearchParams();
|
|
155
|
+
if (req.body && typeof req.body === "object") {
|
|
156
|
+
for (const [key, value] of Object.entries(
|
|
157
|
+
req.body
|
|
158
|
+
)) {
|
|
159
|
+
params.set(key, String(value));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return params.toString();
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function mapUnexpectedStatus(req, status, bodyText, expectedStatuses, redact2) {
|
|
167
|
+
const redacted = redactBody(bodyText, redact2);
|
|
168
|
+
const mapperInput = {
|
|
169
|
+
status,
|
|
170
|
+
method: req.method,
|
|
171
|
+
path: req.path,
|
|
172
|
+
bodyText: redacted,
|
|
173
|
+
expectedStatuses
|
|
174
|
+
};
|
|
175
|
+
if (req.statusMapper) {
|
|
176
|
+
const custom = req.statusMapper(mapperInput);
|
|
177
|
+
if (custom !== null) return custom;
|
|
178
|
+
}
|
|
179
|
+
const base = {
|
|
180
|
+
method: req.method,
|
|
181
|
+
path: req.path,
|
|
182
|
+
status,
|
|
183
|
+
body: redacted
|
|
184
|
+
};
|
|
185
|
+
switch (status) {
|
|
186
|
+
case 401:
|
|
187
|
+
return new AuthError(base);
|
|
188
|
+
case 403:
|
|
189
|
+
return new ForbiddenError(base);
|
|
190
|
+
case 404:
|
|
191
|
+
return new NotFoundError(base);
|
|
192
|
+
default:
|
|
193
|
+
return new UnexpectedStatusError({
|
|
194
|
+
method: req.method,
|
|
195
|
+
path: req.path,
|
|
196
|
+
status,
|
|
197
|
+
body: redacted,
|
|
198
|
+
expected: expectedStatuses
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
function parseResponseBody(req, bodyText, redact2) {
|
|
203
|
+
const responseType = req.responseType ?? "json";
|
|
204
|
+
if (responseType === "none") {
|
|
205
|
+
return Effect2.succeed(void 0);
|
|
206
|
+
}
|
|
207
|
+
if (responseType === "text") {
|
|
208
|
+
return Effect2.succeed(bodyText);
|
|
209
|
+
}
|
|
210
|
+
if (bodyText.length === 0) {
|
|
211
|
+
return Effect2.succeed(void 0);
|
|
212
|
+
}
|
|
213
|
+
return Effect2.try({
|
|
214
|
+
try: () => JSON.parse(bodyText),
|
|
215
|
+
catch: (cause) => new ParseError({
|
|
216
|
+
path: req.path,
|
|
217
|
+
body: redactBody(bodyText, redact2),
|
|
218
|
+
message: "Failed to parse JSON response",
|
|
219
|
+
cause
|
|
220
|
+
})
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
function fetchWithTimeout(ctx, url, init, timeoutMs, method, path) {
|
|
224
|
+
const fetchImpl = ctx.fetch ?? globalThis.fetch;
|
|
225
|
+
return Effect2.async((resume) => {
|
|
226
|
+
const controller = new AbortController();
|
|
227
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
228
|
+
const finish = (effect) => {
|
|
229
|
+
clearTimeout(timeoutId);
|
|
230
|
+
resume(effect);
|
|
231
|
+
};
|
|
232
|
+
void fetchImpl(url, { ...init, signal: controller.signal }).then((response) => finish(Effect2.succeed(response))).catch((cause) => {
|
|
233
|
+
if (cause instanceof Error && cause.name === "AbortError") {
|
|
234
|
+
finish(
|
|
235
|
+
Effect2.fail(new TimeoutError({ method, path, timeoutMs }))
|
|
236
|
+
);
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
finish(
|
|
240
|
+
Effect2.fail(new TransportError({ method, path, cause }))
|
|
241
|
+
);
|
|
242
|
+
});
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
var buildUrl = (baseUrl, path, query) => {
|
|
246
|
+
if (path.includes("\\")) {
|
|
247
|
+
throw new TypeError("buildUrl: path must not contain backslash");
|
|
248
|
+
}
|
|
249
|
+
const url = new URL(path, baseUrl);
|
|
250
|
+
if (url.username || url.password) {
|
|
251
|
+
throw new TypeError("buildUrl: path must not contain URL userinfo");
|
|
252
|
+
}
|
|
253
|
+
if (url.origin !== baseUrl.origin) {
|
|
254
|
+
throw new TypeError(
|
|
255
|
+
`buildUrl: path "${path}" resolves to a different origin (${url.origin}) than baseUrl (${baseUrl.origin})`
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
if (query) {
|
|
259
|
+
for (const [key, value] of Object.entries(query)) {
|
|
260
|
+
if (value === null || value === void 0) continue;
|
|
261
|
+
if (Array.isArray(value)) {
|
|
262
|
+
for (const item of value) {
|
|
263
|
+
if (item === null || item === void 0) continue;
|
|
264
|
+
url.searchParams.append(key, String(item));
|
|
265
|
+
}
|
|
266
|
+
} else {
|
|
267
|
+
url.searchParams.set(key, String(value));
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return url;
|
|
272
|
+
};
|
|
273
|
+
function buildHeaders(ctx, req) {
|
|
274
|
+
const auth = ctx.auth;
|
|
275
|
+
if (!auth) {
|
|
276
|
+
return Effect2.succeed(mergeHeaders(ctx.defaultHeaders, req.headers));
|
|
277
|
+
}
|
|
278
|
+
return Effect2.gen(function* () {
|
|
279
|
+
let headers = mergeHeaders(ctx.defaultHeaders);
|
|
280
|
+
headers = yield* auth.apply(headers);
|
|
281
|
+
return mergeHeaders(headers, req.headers);
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
var sendRequest = (ctx, req) => {
|
|
285
|
+
const url = buildUrl(ctx.baseUrl, req.path, req.query);
|
|
286
|
+
const timeoutMs = req.timeoutMs ?? ctx.timeoutMs;
|
|
287
|
+
const expectedStatuses = resolveExpectedStatuses(req);
|
|
288
|
+
return buildHeaders(ctx, req).pipe(
|
|
289
|
+
Effect2.flatMap((headers) => {
|
|
290
|
+
const body = buildRequestBody(req, headers);
|
|
291
|
+
const init = {
|
|
292
|
+
method: req.method,
|
|
293
|
+
headers,
|
|
294
|
+
...body !== void 0 ? { body } : {}
|
|
295
|
+
};
|
|
296
|
+
return fetchWithTimeout(
|
|
297
|
+
ctx,
|
|
298
|
+
url,
|
|
299
|
+
init,
|
|
300
|
+
timeoutMs,
|
|
301
|
+
req.method,
|
|
302
|
+
req.path
|
|
303
|
+
).pipe(
|
|
304
|
+
Effect2.flatMap(
|
|
305
|
+
(response) => Effect2.tryPromise({
|
|
306
|
+
try: () => response.text(),
|
|
307
|
+
catch: (cause) => new TransportError({
|
|
308
|
+
method: req.method,
|
|
309
|
+
path: req.path,
|
|
310
|
+
cause
|
|
311
|
+
})
|
|
312
|
+
}).pipe(
|
|
313
|
+
Effect2.flatMap((bodyText) => {
|
|
314
|
+
if (!isExpectedStatus(response.status, expectedStatuses)) {
|
|
315
|
+
return Effect2.fail(
|
|
316
|
+
mapUnexpectedStatus(
|
|
317
|
+
req,
|
|
318
|
+
response.status,
|
|
319
|
+
bodyText,
|
|
320
|
+
expectedStatuses,
|
|
321
|
+
ctx.redact
|
|
322
|
+
)
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
return parseResponseBody(req, bodyText, ctx.redact).pipe(
|
|
326
|
+
Effect2.map((parsedBody) => ({
|
|
327
|
+
status: response.status,
|
|
328
|
+
headers: response.headers,
|
|
329
|
+
bodyText,
|
|
330
|
+
body: parsedBody
|
|
331
|
+
}))
|
|
332
|
+
);
|
|
333
|
+
})
|
|
334
|
+
)
|
|
335
|
+
)
|
|
336
|
+
);
|
|
337
|
+
})
|
|
338
|
+
);
|
|
339
|
+
};
|
|
340
|
+
var defaultShouldRetry = (error) => {
|
|
341
|
+
switch (error._tag) {
|
|
342
|
+
case "TransportError":
|
|
343
|
+
case "TimeoutError":
|
|
344
|
+
return true;
|
|
345
|
+
case "UnexpectedStatusError":
|
|
346
|
+
return error.status >= 500;
|
|
347
|
+
default:
|
|
348
|
+
return false;
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
var DEFAULT_POLICY_FIELDS = {
|
|
352
|
+
maxAttempts: 3,
|
|
353
|
+
initialDelayMs: 100,
|
|
354
|
+
maxDelayMs: 5e3,
|
|
355
|
+
factor: 2,
|
|
356
|
+
jitter: true,
|
|
357
|
+
shouldRetry: defaultShouldRetry
|
|
358
|
+
};
|
|
359
|
+
var noRetry = {
|
|
360
|
+
enabled: false,
|
|
361
|
+
...DEFAULT_POLICY_FIELDS,
|
|
362
|
+
shouldRetry: () => false
|
|
363
|
+
};
|
|
364
|
+
var exponentialRetry = (opts) => ({
|
|
365
|
+
enabled: opts.enabled ?? true,
|
|
366
|
+
maxAttempts: opts.maxAttempts ?? DEFAULT_POLICY_FIELDS.maxAttempts,
|
|
367
|
+
initialDelayMs: opts.initialDelayMs ?? DEFAULT_POLICY_FIELDS.initialDelayMs,
|
|
368
|
+
maxDelayMs: opts.maxDelayMs ?? DEFAULT_POLICY_FIELDS.maxDelayMs,
|
|
369
|
+
factor: opts.factor ?? DEFAULT_POLICY_FIELDS.factor,
|
|
370
|
+
jitter: opts.jitter ?? DEFAULT_POLICY_FIELDS.jitter,
|
|
371
|
+
shouldRetry: opts.shouldRetry ?? DEFAULT_POLICY_FIELDS.shouldRetry
|
|
372
|
+
});
|
|
373
|
+
var buildSchedule = (policy) => {
|
|
374
|
+
const base = Schedule.exponential(`${policy.initialDelayMs} millis`, policy.factor);
|
|
375
|
+
const withJitter = policy.jitter ? base.pipe(Schedule.jittered) : base;
|
|
376
|
+
const capped = withJitter.pipe(
|
|
377
|
+
Schedule.modifyDelay((_out, duration) => {
|
|
378
|
+
const ms = Duration.toMillis(duration);
|
|
379
|
+
return ms > policy.maxDelayMs ? `${policy.maxDelayMs} millis` : duration;
|
|
380
|
+
})
|
|
381
|
+
);
|
|
382
|
+
return capped.pipe(Schedule.whileInput((error) => policy.shouldRetry(error)));
|
|
383
|
+
};
|
|
384
|
+
var withRetry = (effect, policy = noRetry) => {
|
|
385
|
+
if (!policy.enabled || policy.maxAttempts <= 1) {
|
|
386
|
+
return effect;
|
|
387
|
+
}
|
|
388
|
+
const retries = Math.max(0, policy.maxAttempts - 1);
|
|
389
|
+
return Effect3.retry(effect, {
|
|
390
|
+
times: retries,
|
|
391
|
+
while: (error) => policy.shouldRetry(error),
|
|
392
|
+
schedule: buildSchedule(policy)
|
|
393
|
+
});
|
|
394
|
+
};
|
|
395
|
+
var ok = (details) => ({
|
|
396
|
+
content: [{ type: "text", text: JSON.stringify(details, null, 2) }],
|
|
397
|
+
details
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
// src/config.ts
|
|
401
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
402
|
+
var ConfigError2 = class extends Error {
|
|
8
403
|
constructor(message) {
|
|
9
404
|
super(message);
|
|
10
405
|
this.name = "ConfigError";
|
|
11
406
|
}
|
|
12
407
|
};
|
|
13
|
-
function
|
|
14
|
-
|
|
15
|
-
|
|
408
|
+
function runConfigEffect(effect) {
|
|
409
|
+
const result = Effect6.runSync(Effect6.either(effect));
|
|
410
|
+
if (result._tag === "Left") {
|
|
411
|
+
throw new ConfigError2(result.left.message);
|
|
412
|
+
}
|
|
413
|
+
return result.right;
|
|
414
|
+
}
|
|
415
|
+
function parseTlsInsecure(env) {
|
|
416
|
+
const raw = env.get("LIBRENMS_TLS_INSECURE");
|
|
417
|
+
if (!raw) return false;
|
|
418
|
+
if (["true", "1", "yes"].includes(raw.toLowerCase())) {
|
|
419
|
+
return runConfigEffect(parseBooleanEnv(env, "LIBRENMS_TLS_INSECURE", false));
|
|
420
|
+
}
|
|
421
|
+
return false;
|
|
422
|
+
}
|
|
423
|
+
function parseRequestTimeoutMs(env) {
|
|
424
|
+
return runConfigEffect(
|
|
425
|
+
parseTimeoutEnv(env, "LIBRENMS_REQUEST_TIMEOUT_MS", {
|
|
426
|
+
fallbackMs: DEFAULT_REQUEST_TIMEOUT_MS,
|
|
427
|
+
minMs: 1e3,
|
|
428
|
+
unit: "ms"
|
|
429
|
+
})
|
|
430
|
+
);
|
|
16
431
|
}
|
|
17
432
|
function resolveConfig(env) {
|
|
433
|
+
const reader = fromProcessEnv(env);
|
|
18
434
|
const url = env.LIBRENMS_URL;
|
|
19
435
|
const token = env.LIBRENMS_TOKEN;
|
|
20
|
-
if (!url) throw new
|
|
21
|
-
if (!token) throw new
|
|
436
|
+
if (!url) throw new ConfigError2("LIBRENMS_URL is required");
|
|
437
|
+
if (!token) throw new ConfigError2("LIBRENMS_TOKEN is required");
|
|
22
438
|
return {
|
|
23
439
|
url: url.replace(/\/+$/, ""),
|
|
24
440
|
token,
|
|
25
|
-
tlsInsecure:
|
|
441
|
+
tlsInsecure: parseTlsInsecure(reader),
|
|
442
|
+
requestTimeoutMs: parseRequestTimeoutMs(reader)
|
|
26
443
|
};
|
|
27
444
|
}
|
|
28
445
|
|
|
446
|
+
// src/error-message.ts
|
|
447
|
+
function boundaryErrorMessage(error) {
|
|
448
|
+
return error instanceof Error ? error.message : String(error);
|
|
449
|
+
}
|
|
450
|
+
|
|
29
451
|
// src/librenms-client.ts
|
|
452
|
+
import { Effect as Effect7 } from "effect";
|
|
30
453
|
import { Agent as UndiciAgent } from "undici";
|
|
31
454
|
var LibreNmsClientError = class extends Error {
|
|
32
455
|
constructor(status, message) {
|
|
@@ -34,7 +457,6 @@ var LibreNmsClientError = class extends Error {
|
|
|
34
457
|
this.status = status;
|
|
35
458
|
this.name = "LibreNmsClientError";
|
|
36
459
|
}
|
|
37
|
-
status;
|
|
38
460
|
};
|
|
39
461
|
var LibreNmsUnreachableError = class extends Error {
|
|
40
462
|
constructor(cause) {
|
|
@@ -46,12 +468,13 @@ var LibreNmsClient = class {
|
|
|
46
468
|
constructor(cfg, opts = {}) {
|
|
47
469
|
this.cfg = cfg;
|
|
48
470
|
this.retryDelayMs = opts.retryDelayMs ?? 1e3;
|
|
471
|
+
this.fetchImpl = opts.fetch ?? fetch;
|
|
49
472
|
if (cfg.tlsInsecure && cfg.url.startsWith("https://")) {
|
|
50
473
|
this.dispatcher = new UndiciAgent({ connect: { rejectUnauthorized: false } });
|
|
51
474
|
}
|
|
52
475
|
}
|
|
53
|
-
cfg;
|
|
54
476
|
retryDelayMs;
|
|
477
|
+
fetchImpl;
|
|
55
478
|
// Node's global fetch (undici) ignores node:https.Agent. To actually skip
|
|
56
479
|
// cert verification for self-signed LibreNMS hosts we pass an undici Agent
|
|
57
480
|
// via the `dispatcher` init option.
|
|
@@ -69,47 +492,95 @@ var LibreNmsClient = class {
|
|
|
69
492
|
return this.request("DELETE", path);
|
|
70
493
|
}
|
|
71
494
|
async request(method, path, body) {
|
|
72
|
-
const
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
}
|
|
79
|
-
let lastErr;
|
|
80
|
-
for (let attempt = 0; attempt < 2; attempt++) {
|
|
81
|
-
try {
|
|
82
|
-
const init = { method, headers, body: bodyStr };
|
|
83
|
-
if (this.dispatcher) init.dispatcher = this.dispatcher;
|
|
84
|
-
const res = await fetch(url, init);
|
|
85
|
-
if (res.status >= 200 && res.status < 300) {
|
|
86
|
-
const text = await res.text();
|
|
87
|
-
if (!text) return void 0;
|
|
88
|
-
return JSON.parse(text);
|
|
89
|
-
}
|
|
90
|
-
if (res.status >= 500) {
|
|
91
|
-
lastErr = new LibreNmsUnreachableError(`HTTP ${res.status}`);
|
|
92
|
-
if (attempt === 0) await sleep(this.retryDelayMs);
|
|
93
|
-
continue;
|
|
94
|
-
}
|
|
95
|
-
const errText = await res.text();
|
|
96
|
-
let msg = errText;
|
|
97
|
-
try {
|
|
98
|
-
msg = JSON.parse(errText).message ?? errText;
|
|
99
|
-
} catch {
|
|
100
|
-
}
|
|
101
|
-
throw new LibreNmsClientError(res.status, msg);
|
|
102
|
-
} catch (e) {
|
|
103
|
-
if (e instanceof LibreNmsClientError) throw e;
|
|
104
|
-
lastErr = new LibreNmsUnreachableError(e.message);
|
|
105
|
-
if (attempt === 0) await sleep(this.retryDelayMs);
|
|
495
|
+
const baseUrl = new URL(`${this.cfg.url}/`);
|
|
496
|
+
const requestPath = `api/v0${path}`;
|
|
497
|
+
const auth = {
|
|
498
|
+
apply: (headers) => {
|
|
499
|
+
headers.set("x-auth-token", this.cfg.token);
|
|
500
|
+
return Effect7.succeed(headers);
|
|
106
501
|
}
|
|
502
|
+
};
|
|
503
|
+
const req = {
|
|
504
|
+
method,
|
|
505
|
+
path: requestPath,
|
|
506
|
+
body,
|
|
507
|
+
bodyEncoding: body !== void 0 ? "json" : "none",
|
|
508
|
+
statusMapper: ({ status, method: mappedMethod, path: mappedPath, bodyText, expectedStatuses }) => new UnexpectedStatusError({
|
|
509
|
+
method: mappedMethod,
|
|
510
|
+
path: mappedPath,
|
|
511
|
+
status,
|
|
512
|
+
body: bodyText,
|
|
513
|
+
expected: expectedStatuses
|
|
514
|
+
})
|
|
515
|
+
};
|
|
516
|
+
const ctx = {
|
|
517
|
+
baseUrl,
|
|
518
|
+
auth,
|
|
519
|
+
timeoutMs: this.cfg.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
520
|
+
fetch: this.fetchWithDispatcher,
|
|
521
|
+
redact: (value) => value
|
|
522
|
+
};
|
|
523
|
+
let result;
|
|
524
|
+
try {
|
|
525
|
+
result = await Effect7.runPromise(
|
|
526
|
+
Effect7.either(
|
|
527
|
+
withRetry(
|
|
528
|
+
sendRequest(ctx, req),
|
|
529
|
+
exponentialRetry({
|
|
530
|
+
maxAttempts: 2,
|
|
531
|
+
initialDelayMs: this.retryDelayMs,
|
|
532
|
+
maxDelayMs: this.retryDelayMs,
|
|
533
|
+
factor: 1,
|
|
534
|
+
jitter: false,
|
|
535
|
+
shouldRetry: shouldRetryLibreNmsRequest
|
|
536
|
+
})
|
|
537
|
+
)
|
|
538
|
+
)
|
|
539
|
+
);
|
|
540
|
+
} catch (error) {
|
|
541
|
+
throw new LibreNmsUnreachableError(boundaryErrorMessage(error));
|
|
542
|
+
}
|
|
543
|
+
if (result._tag === "Right") {
|
|
544
|
+
return result.right.body;
|
|
107
545
|
}
|
|
108
|
-
throw
|
|
546
|
+
throw mapLibreNmsRequestError(result.left);
|
|
109
547
|
}
|
|
548
|
+
fetchWithDispatcher = (input, init = {}) => {
|
|
549
|
+
if (!this.dispatcher) return this.fetchImpl(input, init);
|
|
550
|
+
return this.fetchImpl(input, { ...init, dispatcher: this.dispatcher });
|
|
551
|
+
};
|
|
110
552
|
};
|
|
111
|
-
function
|
|
112
|
-
|
|
553
|
+
function shouldRetryLibreNmsRequest(error) {
|
|
554
|
+
if (error instanceof TransportError) return true;
|
|
555
|
+
if (error instanceof ParseError) return true;
|
|
556
|
+
if (error instanceof UnexpectedStatusError) return error.status >= 500;
|
|
557
|
+
return false;
|
|
558
|
+
}
|
|
559
|
+
function mapLibreNmsRequestError(error) {
|
|
560
|
+
if (error instanceof UnexpectedStatusError) {
|
|
561
|
+
if (error.status >= 500) return new LibreNmsUnreachableError(`HTTP ${error.status}`);
|
|
562
|
+
return new LibreNmsClientError(error.status, responseErrorMessage(error.body));
|
|
563
|
+
}
|
|
564
|
+
if (error instanceof TimeoutError) {
|
|
565
|
+
return new LibreNmsUnreachableError(
|
|
566
|
+
`${error.method} ${error.path} timed out after ${error.timeoutMs}ms`
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
if (error instanceof TransportError) {
|
|
570
|
+
const cause = error.cause;
|
|
571
|
+
return new LibreNmsUnreachableError(boundaryErrorMessage(cause));
|
|
572
|
+
}
|
|
573
|
+
if (error instanceof ParseError) {
|
|
574
|
+
return new LibreNmsUnreachableError(boundaryErrorMessage(error.cause ?? error.message));
|
|
575
|
+
}
|
|
576
|
+
return new LibreNmsUnreachableError(boundaryErrorMessage(error));
|
|
577
|
+
}
|
|
578
|
+
function responseErrorMessage(bodyText) {
|
|
579
|
+
try {
|
|
580
|
+
return JSON.parse(bodyText).message ?? bodyText;
|
|
581
|
+
} catch {
|
|
582
|
+
return bodyText;
|
|
583
|
+
}
|
|
113
584
|
}
|
|
114
585
|
|
|
115
586
|
// src/security.ts
|
|
@@ -146,14 +617,53 @@ function redact(value) {
|
|
|
146
617
|
return value;
|
|
147
618
|
}
|
|
148
619
|
|
|
620
|
+
// src/validate.ts
|
|
621
|
+
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
622
|
+
var ValidationError = class extends Error {
|
|
623
|
+
constructor(message) {
|
|
624
|
+
super(message);
|
|
625
|
+
this.name = "ValidationError";
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
var compiledCache = /* @__PURE__ */ new WeakMap();
|
|
629
|
+
function getChecker(schema) {
|
|
630
|
+
let checker = compiledCache.get(schema);
|
|
631
|
+
if (!checker) {
|
|
632
|
+
checker = TypeCompiler.Compile(schema);
|
|
633
|
+
compiledCache.set(schema, checker);
|
|
634
|
+
}
|
|
635
|
+
return checker;
|
|
636
|
+
}
|
|
637
|
+
function validateToolArgs(schema, toolName, args) {
|
|
638
|
+
const checker = getChecker(schema);
|
|
639
|
+
if (checker.Check(args)) return;
|
|
640
|
+
const first = checker.Errors(args).First();
|
|
641
|
+
const where = first?.path ? ` at ${first.path}` : "";
|
|
642
|
+
const detail = first ? `${first.message}${where}` : "schema mismatch";
|
|
643
|
+
throw new ValidationError(
|
|
644
|
+
`Invalid arguments for ${toolName}: ${detail}`
|
|
645
|
+
);
|
|
646
|
+
}
|
|
647
|
+
|
|
149
648
|
// src/tools/librenms_status.ts
|
|
150
649
|
import { Type } from "@sinclair/typebox";
|
|
151
650
|
|
|
152
651
|
// src/tools/_util.ts
|
|
153
652
|
function jsonToolResult(payload) {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
653
|
+
const r = ok(payload);
|
|
654
|
+
return { content: r.content };
|
|
655
|
+
}
|
|
656
|
+
function safeInt(value, label, opts = {}) {
|
|
657
|
+
const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
|
|
658
|
+
if (!Number.isInteger(n)) {
|
|
659
|
+
throw new Error(`${label} must be an integer, got: ${String(value)}`);
|
|
660
|
+
}
|
|
661
|
+
const min = opts.min ?? 1;
|
|
662
|
+
if (n < min) throw new Error(`${label} must be >= ${min}, got: ${n}`);
|
|
663
|
+
if (opts.max !== void 0 && n > opts.max) {
|
|
664
|
+
throw new Error(`${label} must be <= ${opts.max}, got: ${n}`);
|
|
665
|
+
}
|
|
666
|
+
return n;
|
|
157
667
|
}
|
|
158
668
|
|
|
159
669
|
// src/tools/librenms_status.ts
|
|
@@ -199,7 +709,7 @@ function createLibrenmsListDevicesTool(getClient) {
|
|
|
199
709
|
parameters: Schema2,
|
|
200
710
|
execute: async (_id, raw) => {
|
|
201
711
|
const args = raw ?? {};
|
|
202
|
-
const path = args.type ? `/devices?type=${args.type}` : "/devices";
|
|
712
|
+
const path = args.type ? `/devices?type=${encodeURIComponent(args.type)}` : "/devices";
|
|
203
713
|
const client = getClient();
|
|
204
714
|
const r = await client.get(path);
|
|
205
715
|
return jsonToolResult({ devices: r.devices ?? [] });
|
|
@@ -332,7 +842,7 @@ function createLibrenmsListAlertsTool(getClient) {
|
|
|
332
842
|
parameters: Schema6,
|
|
333
843
|
execute: async (_id, raw) => {
|
|
334
844
|
const args = raw ?? {};
|
|
335
|
-
const path = args.state !== void 0 ? `/alerts?state=${args.state}` : "/alerts";
|
|
845
|
+
const path = args.state !== void 0 ? `/alerts?state=${encodeURIComponent(args.state)}` : "/alerts";
|
|
336
846
|
const client = getClient();
|
|
337
847
|
const r = await client.get(path);
|
|
338
848
|
return jsonToolResult({ alerts: r.alerts ?? [] });
|
|
@@ -356,8 +866,9 @@ function createLibrenmsGetAlertTool(getClient) {
|
|
|
356
866
|
parameters: Schema7,
|
|
357
867
|
execute: async (_id, raw) => {
|
|
358
868
|
const args = raw;
|
|
869
|
+
const id = safeInt(args.id, "id");
|
|
359
870
|
const client = getClient();
|
|
360
|
-
const r = await client.get(`/alerts/${
|
|
871
|
+
const r = await client.get(`/alerts/${encodeURIComponent(id)}`);
|
|
361
872
|
return jsonToolResult({ alert: r.alerts?.[0] ?? null });
|
|
362
873
|
}
|
|
363
874
|
};
|
|
@@ -390,8 +901,10 @@ function createLibrenmsAlertHistoryTool(getClient) {
|
|
|
390
901
|
parameters: Schema8,
|
|
391
902
|
execute: async (_id, raw) => {
|
|
392
903
|
const args = raw ?? {};
|
|
393
|
-
const limit = args.limit ?? 25;
|
|
394
|
-
const path = args.device_id ? `/logs/alertlog/${
|
|
904
|
+
const limit = safeInt(args.limit ?? 25, "limit");
|
|
905
|
+
const path = args.device_id !== void 0 ? `/logs/alertlog/${encodeURIComponent(
|
|
906
|
+
safeInt(args.device_id, "device_id")
|
|
907
|
+
)}?limit=${encodeURIComponent(limit)}` : `/logs/alertlog?limit=${encodeURIComponent(limit)}`;
|
|
395
908
|
const client = getClient();
|
|
396
909
|
const r = await client.get(path);
|
|
397
910
|
return jsonToolResult({
|
|
@@ -446,12 +959,13 @@ function createLibrenmsAckAlertTool(getClient) {
|
|
|
446
959
|
execute: async (_id, raw) => {
|
|
447
960
|
assertConfirmedWrite(raw, NAME);
|
|
448
961
|
const args = raw;
|
|
962
|
+
const id = safeInt(args.id, "id");
|
|
449
963
|
const client = getClient();
|
|
450
964
|
const body = {};
|
|
451
965
|
if (args.note !== void 0) body.note = args.note;
|
|
452
966
|
if (args.until_clear !== void 0) body.until_clear = args.until_clear;
|
|
453
|
-
const r = await client.put(`/alerts/${
|
|
454
|
-
return jsonToolResult({ alert_id:
|
|
967
|
+
const r = await client.put(`/alerts/${encodeURIComponent(id)}`, body);
|
|
968
|
+
return jsonToolResult({ alert_id: id, acked: true, response: r });
|
|
455
969
|
}
|
|
456
970
|
};
|
|
457
971
|
}
|
|
@@ -536,8 +1050,9 @@ function createLibrenmsGetPortTool(getClient) {
|
|
|
536
1050
|
parameters: Schema11,
|
|
537
1051
|
execute: async (_id, raw) => {
|
|
538
1052
|
const args = raw;
|
|
1053
|
+
const portId = safeInt(args.port_id, "port_id");
|
|
539
1054
|
const client = getClient();
|
|
540
|
-
const r = await client.get(`/ports/${
|
|
1055
|
+
const r = await client.get(`/ports/${encodeURIComponent(portId)}`);
|
|
541
1056
|
return jsonToolResult({ port: r.port?.[0] ?? null });
|
|
542
1057
|
}
|
|
543
1058
|
};
|
|
@@ -570,8 +1085,10 @@ function createLibrenmsEventLogTool(getClient) {
|
|
|
570
1085
|
parameters: Schema12,
|
|
571
1086
|
execute: async (_id, raw) => {
|
|
572
1087
|
const args = raw ?? {};
|
|
573
|
-
const limit = args.limit ?? 25;
|
|
574
|
-
const path = args.device_id ? `/logs/eventlog/${
|
|
1088
|
+
const limit = safeInt(args.limit ?? 25, "limit");
|
|
1089
|
+
const path = args.device_id !== void 0 ? `/logs/eventlog/${encodeURIComponent(
|
|
1090
|
+
safeInt(args.device_id, "device_id")
|
|
1091
|
+
)}?limit=${encodeURIComponent(limit)}` : `/logs/eventlog?limit=${encodeURIComponent(limit)}`;
|
|
575
1092
|
const client = getClient();
|
|
576
1093
|
const r = await client.get(path);
|
|
577
1094
|
return jsonToolResult({
|
|
@@ -608,11 +1125,12 @@ function createLibrenmsUnmuteAlertTool(getClient) {
|
|
|
608
1125
|
execute: async (_id, raw) => {
|
|
609
1126
|
assertConfirmedWrite(raw, NAME3);
|
|
610
1127
|
const args = raw;
|
|
1128
|
+
const id = safeInt(args.id, "id");
|
|
611
1129
|
const client = getClient();
|
|
612
1130
|
const body = {};
|
|
613
1131
|
if (args.note !== void 0) body.note = args.note;
|
|
614
|
-
const r = await client.put(`/alerts/unmute/${
|
|
615
|
-
return jsonToolResult({ alert_id:
|
|
1132
|
+
const r = await client.put(`/alerts/unmute/${encodeURIComponent(id)}`, body);
|
|
1133
|
+
return jsonToolResult({ alert_id: id, unmuted: true, response: r });
|
|
616
1134
|
}
|
|
617
1135
|
};
|
|
618
1136
|
}
|
|
@@ -624,14 +1142,18 @@ function withRedactedErrors(tool) {
|
|
|
624
1142
|
...tool,
|
|
625
1143
|
execute: async (id, args) => {
|
|
626
1144
|
try {
|
|
1145
|
+
validateToolArgs(tool.parameters, tool.name, args ?? {});
|
|
627
1146
|
return await orig(id, args);
|
|
628
1147
|
} catch (e) {
|
|
629
|
-
|
|
630
|
-
return { content: [{ type: "text", text: JSON.stringify({ error: msg }) }], isError: true };
|
|
1148
|
+
return pluginErrorResult(e);
|
|
631
1149
|
}
|
|
632
1150
|
}
|
|
633
1151
|
};
|
|
634
1152
|
}
|
|
1153
|
+
function pluginErrorResult(error) {
|
|
1154
|
+
const msg = redact(boundaryErrorMessage(error));
|
|
1155
|
+
return { content: [{ type: "text", text: JSON.stringify({ error: msg }) }], isError: true };
|
|
1156
|
+
}
|
|
635
1157
|
function makeFactory(cfg) {
|
|
636
1158
|
registerSecret(cfg.token);
|
|
637
1159
|
return () => new LibreNmsClient(cfg);
|
|
@@ -662,5 +1184,6 @@ var index_default = definePluginEntry({
|
|
|
662
1184
|
});
|
|
663
1185
|
export {
|
|
664
1186
|
index_default as default,
|
|
1187
|
+
pluginErrorResult,
|
|
665
1188
|
withRedactedErrors
|
|
666
1189
|
};
|