@solomonneas/librenms-mcp 0.2.1 → 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/dist/mcp-bin.js CHANGED
@@ -6,29 +6,452 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
6
6
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
7
7
 
8
8
  // src/config.ts
9
- var ConfigError = class extends Error {
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 {
10
405
  constructor(message) {
11
406
  super(message);
12
407
  this.name = "ConfigError";
13
408
  }
14
409
  };
15
- function isTruthy(value) {
16
- if (!value) return false;
17
- return ["true", "1", "yes"].includes(value.toLowerCase());
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
+ );
18
433
  }
19
434
  function resolveConfig(env) {
435
+ const reader = fromProcessEnv(env);
20
436
  const url = env.LIBRENMS_URL;
21
437
  const token = env.LIBRENMS_TOKEN;
22
- if (!url) throw new ConfigError("LIBRENMS_URL is required");
23
- if (!token) throw new ConfigError("LIBRENMS_TOKEN is required");
438
+ if (!url) throw new ConfigError2("LIBRENMS_URL is required");
439
+ if (!token) throw new ConfigError2("LIBRENMS_TOKEN is required");
24
440
  return {
25
441
  url: url.replace(/\/+$/, ""),
26
442
  token,
27
- tlsInsecure: isTruthy(env.LIBRENMS_TLS_INSECURE)
443
+ tlsInsecure: parseTlsInsecure(reader),
444
+ requestTimeoutMs: parseRequestTimeoutMs(reader)
28
445
  };
29
446
  }
30
447
 
448
+ // src/error-message.ts
449
+ function boundaryErrorMessage(error) {
450
+ return error instanceof Error ? error.message : String(error);
451
+ }
452
+
31
453
  // src/librenms-client.ts
454
+ import { Effect as Effect7 } from "effect";
32
455
  import { Agent as UndiciAgent } from "undici";
33
456
  var LibreNmsClientError = class extends Error {
34
457
  constructor(status, message) {
@@ -36,7 +459,6 @@ var LibreNmsClientError = class extends Error {
36
459
  this.status = status;
37
460
  this.name = "LibreNmsClientError";
38
461
  }
39
- status;
40
462
  };
41
463
  var LibreNmsUnreachableError = class extends Error {
42
464
  constructor(cause) {
@@ -48,12 +470,13 @@ var LibreNmsClient = class {
48
470
  constructor(cfg, opts = {}) {
49
471
  this.cfg = cfg;
50
472
  this.retryDelayMs = opts.retryDelayMs ?? 1e3;
473
+ this.fetchImpl = opts.fetch ?? fetch;
51
474
  if (cfg.tlsInsecure && cfg.url.startsWith("https://")) {
52
475
  this.dispatcher = new UndiciAgent({ connect: { rejectUnauthorized: false } });
53
476
  }
54
477
  }
55
- cfg;
56
478
  retryDelayMs;
479
+ fetchImpl;
57
480
  // Node's global fetch (undici) ignores node:https.Agent. To actually skip
58
481
  // cert verification for self-signed LibreNMS hosts we pass an undici Agent
59
482
  // via the `dispatcher` init option.
@@ -71,47 +494,95 @@ var LibreNmsClient = class {
71
494
  return this.request("DELETE", path);
72
495
  }
73
496
  async request(method, path, body) {
74
- const url = this.cfg.url + "/api/v0" + path;
75
- const headers = { "x-auth-token": this.cfg.token };
76
- let bodyStr;
77
- if (body !== void 0) {
78
- headers["content-type"] = "application/json";
79
- bodyStr = JSON.stringify(body);
80
- }
81
- let lastErr;
82
- for (let attempt = 0; attempt < 2; attempt++) {
83
- try {
84
- const init = { method, headers, body: bodyStr };
85
- if (this.dispatcher) init.dispatcher = this.dispatcher;
86
- const res = await fetch(url, init);
87
- if (res.status >= 200 && res.status < 300) {
88
- const text = await res.text();
89
- if (!text) return void 0;
90
- return JSON.parse(text);
91
- }
92
- if (res.status >= 500) {
93
- lastErr = new LibreNmsUnreachableError(`HTTP ${res.status}`);
94
- if (attempt === 0) await sleep(this.retryDelayMs);
95
- continue;
96
- }
97
- const errText = await res.text();
98
- let msg = errText;
99
- try {
100
- msg = JSON.parse(errText).message ?? errText;
101
- } catch {
102
- }
103
- throw new LibreNmsClientError(res.status, msg);
104
- } catch (e) {
105
- if (e instanceof LibreNmsClientError) throw e;
106
- lastErr = new LibreNmsUnreachableError(e.message);
107
- if (attempt === 0) await sleep(this.retryDelayMs);
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);
108
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;
109
547
  }
110
- throw lastErr ?? new LibreNmsUnreachableError("unknown");
548
+ throw mapLibreNmsRequestError(result.left);
111
549
  }
550
+ fetchWithDispatcher = (input, init = {}) => {
551
+ if (!this.dispatcher) return this.fetchImpl(input, init);
552
+ return this.fetchImpl(input, { ...init, dispatcher: this.dispatcher });
553
+ };
112
554
  };
113
- function sleep(ms) {
114
- return new Promise((r) => setTimeout(r, ms));
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
+ }
115
586
  }
116
587
 
117
588
  // src/security.ts
@@ -181,9 +652,8 @@ import { Type } from "@sinclair/typebox";
181
652
 
182
653
  // src/tools/_util.ts
183
654
  function jsonToolResult(payload) {
184
- return {
185
- content: [{ type: "text", text: JSON.stringify(payload, null, 2) }]
186
- };
655
+ const r = ok(payload);
656
+ return { content: r.content };
187
657
  }
188
658
  function safeInt(value, label, opts = {}) {
189
659
  const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
@@ -688,7 +1158,7 @@ function createServer() {
688
1158
  createLibrenmsUnmuteAlertTool(getClient)
689
1159
  ];
690
1160
  const toolMap = new Map(tools.map((t) => [t.name, t]));
691
- const server = new Server({ name: "librenms-mcp", version: "0.2.0" }, { capabilities: { tools: {} } });
1161
+ const server = new Server({ name: "librenms-mcp", version: "0.2.2" }, { capabilities: { tools: {} } });
692
1162
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
693
1163
  tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.parameters }))
694
1164
  }));
@@ -702,12 +1172,15 @@ function createServer() {
702
1172
  validateToolArgs(t.parameters, t.name, args);
703
1173
  return await t.execute(req.params.name, args);
704
1174
  } catch (e) {
705
- const msg = redact(e.message);
706
- return { content: [{ type: "text", text: JSON.stringify({ error: msg }) }], isError: true };
1175
+ return mcpErrorResult(e);
707
1176
  }
708
1177
  });
709
1178
  return server;
710
1179
  }
1180
+ function mcpErrorResult(error) {
1181
+ const msg = redact(boundaryErrorMessage(error));
1182
+ return { content: [{ type: "text", text: JSON.stringify({ error: msg }) }], isError: true };
1183
+ }
711
1184
  async function serve() {
712
1185
  const server = createServer();
713
1186
  const transport = new StdioServerTransport();