@thotischner/observability-mcp 3.9.7 → 3.9.9
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/connectors/loki.d.ts +14 -0
- package/dist/connectors/loki.js +48 -4
- package/dist/connectors/loki.test.js +164 -1
- package/dist/tools/query-logs.js +1 -1
- package/package.json +4 -4
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
import type { ObservabilityConnector } from "./interface.js";
|
|
2
2
|
import type { SourceConfig, ConnectorHealth, ServiceInfo, MetricDefinition, LogQuery, LogResult, LogAggregateQuery, LogAggregateResult, SignalType } from "../types.js";
|
|
3
|
+
/** Returned with every aggregate result. States the exclusion explicitly so
|
|
4
|
+
* counts aren't silently read as "all lines" (#611). */
|
|
5
|
+
export declare const AGGREGATE_NOTE: string;
|
|
6
|
+
/**
|
|
7
|
+
* Build the error for a non-2xx Loki response. Loki's body names the actual
|
|
8
|
+
* cause and usually the fix (e.g. "pipeline error: 'JSONParserErr' … Use a
|
|
9
|
+
* label filter to intentionally skip this error"); a bare "400 Bad Request"
|
|
10
|
+
* sent the #611 reporter chasing window length and label names first.
|
|
11
|
+
*
|
|
12
|
+
* The excerpt flows into server logs and back to the calling agent, so
|
|
13
|
+
* control characters and line breaks are collapsed (no forged log lines)
|
|
14
|
+
* and it is capped.
|
|
15
|
+
*/
|
|
16
|
+
export declare function lokiApiError(status: number, statusText: string, body: string): Error;
|
|
3
17
|
/** Escape a value for a double-quoted LogQL string literal. Backslash and
|
|
4
18
|
* quote first (breakout chars), then control chars — a raw newline/tab in
|
|
5
19
|
* a Go-style `"..."` literal is a parse error, so emit the escape sequence. */
|
package/dist/connectors/loki.js
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
import { buildTlsAgent } from "./tls.js";
|
|
2
2
|
const DEFAULT_SERVICE_LABELS = ["service_name", "service", "job", "app", "container"];
|
|
3
3
|
const LABEL_CACHE_TTL_MS = 60_000;
|
|
4
|
+
/** Returned with every aggregate result. States the exclusion explicitly so
|
|
5
|
+
* counts aren't silently read as "all lines" (#611). */
|
|
6
|
+
export const AGGREGATE_NOTE = "Aggregate mode: `limit` does not apply (results are grouped counts, not raw rows). " +
|
|
7
|
+
"Counts cover JSON-parseable lines only — lines that fail `| json` (plain-text startup output, stack traces) are excluded.";
|
|
8
|
+
/** Maximum characters of a backend error body carried into the error message. */
|
|
9
|
+
const ERROR_BODY_EXCERPT_CHARS = 300;
|
|
10
|
+
/**
|
|
11
|
+
* Build the error for a non-2xx Loki response. Loki's body names the actual
|
|
12
|
+
* cause and usually the fix (e.g. "pipeline error: 'JSONParserErr' … Use a
|
|
13
|
+
* label filter to intentionally skip this error"); a bare "400 Bad Request"
|
|
14
|
+
* sent the #611 reporter chasing window length and label names first.
|
|
15
|
+
*
|
|
16
|
+
* The excerpt flows into server logs and back to the calling agent, so
|
|
17
|
+
* control characters and line breaks are collapsed (no forged log lines)
|
|
18
|
+
* and it is capped.
|
|
19
|
+
*/
|
|
20
|
+
export function lokiApiError(status, statusText, body) {
|
|
21
|
+
const excerpt = String(body ?? "")
|
|
22
|
+
// C0, DEL and C1 (incl. NEL \x85 and the one-byte CSI \x9b, neither of
|
|
23
|
+
// which \s covers) so nothing in the excerpt can break a log line or
|
|
24
|
+
// drive a terminal.
|
|
25
|
+
.replace(/[\x00-\x1f\x7f-\x9f]+/g, " ")
|
|
26
|
+
.replace(/\s+/g, " ")
|
|
27
|
+
.trim();
|
|
28
|
+
const clipped = excerpt.length > ERROR_BODY_EXCERPT_CHARS
|
|
29
|
+
? `${excerpt.slice(0, ERROR_BODY_EXCERPT_CHARS)}…`
|
|
30
|
+
: excerpt;
|
|
31
|
+
return new Error(`Loki API error: ${status} ${statusText}${clipped ? ` — ${clipped}` : ""}`);
|
|
32
|
+
}
|
|
4
33
|
/** Escape a value for a double-quoted LogQL string literal. Backslash and
|
|
5
34
|
* quote first (breakout chars), then control chars — a raw newline/tab in
|
|
6
35
|
* a Go-style `"..."` literal is a parse error, so emit the escape sequence. */
|
|
@@ -254,7 +283,16 @@ export class LokiConnector {
|
|
|
254
283
|
const service = this.escapeLogQLValue(rawValue);
|
|
255
284
|
// Same stream + pipeline prefix as queryLogs (reuses the Q-LOG1 unit),
|
|
256
285
|
// minus the level filter (aggregation groups, it doesn't level-filter).
|
|
257
|
-
|
|
286
|
+
//
|
|
287
|
+
// `| __error__=""` directly after the parser is required, not cosmetic
|
|
288
|
+
// (#611): Loki rejects a *metric* query with HTTP 400 as soon as a single
|
|
289
|
+
// line in the window fails `| json` (startup banner, library
|
|
290
|
+
// console.log, stack trace), whereas stream queries just tag such lines
|
|
291
|
+
// with __error__ — which is why plain query_logs kept working and only
|
|
292
|
+
// aggregate broke. Dropping the unparseable lines is the only sane
|
|
293
|
+
// reading for grouped counts anyway: they carry none of the extracted
|
|
294
|
+
// labels being grouped by. The result note tells the caller.
|
|
295
|
+
let pipeline = `{${matchedLabel}="${service}"} | json | __error__=""`;
|
|
258
296
|
pipeline += logqlLabelFilters(params.labels);
|
|
259
297
|
if (params.query) {
|
|
260
298
|
pipeline += ` |~ \`${this.escapeLogQLRegex(params.query)}\``;
|
|
@@ -293,7 +331,7 @@ export class LokiConnector {
|
|
|
293
331
|
step: mode === "range" ? step : undefined,
|
|
294
332
|
mode,
|
|
295
333
|
series,
|
|
296
|
-
note:
|
|
334
|
+
note: AGGREGATE_NOTE,
|
|
297
335
|
};
|
|
298
336
|
}
|
|
299
337
|
// --- Private helpers ---
|
|
@@ -388,8 +426,14 @@ export class LokiConnector {
|
|
|
388
426
|
...this.fetchOptions(),
|
|
389
427
|
signal: controller.signal,
|
|
390
428
|
});
|
|
391
|
-
if (!res.ok)
|
|
392
|
-
|
|
429
|
+
if (!res.ok) {
|
|
430
|
+
// Loki answers errors in text/plain. An HTML body is a reverse proxy's
|
|
431
|
+
// error page — no explanation worth relaying, and it can name internal
|
|
432
|
+
// upstream hosts or server versions — so keep the bare status line.
|
|
433
|
+
const isHtml = /text\/html/i.test(res.headers?.get?.("content-type") ?? "");
|
|
434
|
+
const body = isHtml ? "" : await res.text().catch(() => "");
|
|
435
|
+
throw lokiApiError(res.status, res.statusText, body);
|
|
436
|
+
}
|
|
393
437
|
return res.json();
|
|
394
438
|
}
|
|
395
439
|
catch (err) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { describe, it } from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import { LokiConnector, logqlLabelFilters, levelFromStatus, escapeLogQLValue, buildAggregateLogQL, parseDurationSeconds, defaultBucketSeconds, } from "./loki.js";
|
|
3
|
+
import { LokiConnector, logqlLabelFilters, levelFromStatus, escapeLogQLValue, buildAggregateLogQL, parseDurationSeconds, defaultBucketSeconds, lokiApiError, AGGREGATE_NOTE, } from "./loki.js";
|
|
4
4
|
const proto = LokiConnector.prototype;
|
|
5
5
|
function jsonRes(obj) {
|
|
6
6
|
return { ok: true, status: 200, statusText: "OK", json: async () => obj, text: async () => "" };
|
|
@@ -369,3 +369,166 @@ describe("LokiConnector", () => {
|
|
|
369
369
|
});
|
|
370
370
|
});
|
|
371
371
|
});
|
|
372
|
+
describe("#611: aggregate skips lines that fail | json", () => {
|
|
373
|
+
async function captureAggregate(params) {
|
|
374
|
+
const conn = new LokiConnector();
|
|
375
|
+
await conn.connect({ name: "loki", type: "loki", url: "http://loki:3100", enabled: true });
|
|
376
|
+
let logql = "";
|
|
377
|
+
const orig = globalThis.fetch;
|
|
378
|
+
globalThis.fetch = (async (url) => {
|
|
379
|
+
const u = String(url);
|
|
380
|
+
if (u.includes("/label/") && u.includes("/values"))
|
|
381
|
+
return jsonRes({ data: [params.service] });
|
|
382
|
+
if (u.includes("/query")) {
|
|
383
|
+
logql = decodeURIComponent((u.match(/query=([^&]+)/) || [])[1] || "");
|
|
384
|
+
return u.includes("/query_range")
|
|
385
|
+
? jsonRes({ data: { resultType: "matrix", result: [] } })
|
|
386
|
+
: jsonRes({ data: { resultType: "vector", result: [] } });
|
|
387
|
+
}
|
|
388
|
+
return jsonRes({ data: [] });
|
|
389
|
+
});
|
|
390
|
+
try {
|
|
391
|
+
const res = await conn.queryLogAggregate(params);
|
|
392
|
+
return { logql, res };
|
|
393
|
+
}
|
|
394
|
+
finally {
|
|
395
|
+
globalThis.fetch = orig;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
it("produces exactly the LogQL the reporter verified returns HTTP 200", async () => {
|
|
399
|
+
// Issue #611 repro: topk by status over 48h. Without the __error__ filter
|
|
400
|
+
// Loki answered 400 JSONParserErr; with it, the same query returned counts.
|
|
401
|
+
const { logql } = await captureAggregate({
|
|
402
|
+
service: "web-app", duration: "48h", op: "topk", by: ["status"], k: 20,
|
|
403
|
+
});
|
|
404
|
+
assert.equal(logql, 'topk(20, sum by (status) (count_over_time({service_name="web-app"} | json | __error__="" [172800s])))');
|
|
405
|
+
});
|
|
406
|
+
for (const op of ["sum", "topk", "count_over_time"]) {
|
|
407
|
+
it(`${op}: error filter sits directly after the parser, before label and line filters`, async () => {
|
|
408
|
+
const { logql } = await captureAggregate({
|
|
409
|
+
service: "app", duration: "6h", op, by: ["status"], labels: { method: "GET" }, query: "checkout",
|
|
410
|
+
});
|
|
411
|
+
assert.ok(logql.includes('{service_name="app"} | json | __error__="" | method="GET" |~ `checkout`'), logql);
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
it("result note states that non-JSON lines are excluded", async () => {
|
|
415
|
+
const { res } = await captureAggregate({ service: "app", duration: "1h", op: "sum", by: ["status"] });
|
|
416
|
+
assert.equal(res.note, AGGREGATE_NOTE);
|
|
417
|
+
assert.match(res.note, /JSON-parseable lines only/);
|
|
418
|
+
assert.match(res.note, /limit/); // the pre-existing guidance is kept
|
|
419
|
+
});
|
|
420
|
+
it("stream queries (plain query_logs) are left untouched — non-JSON lines stay visible there", async () => {
|
|
421
|
+
const conn = new LokiConnector();
|
|
422
|
+
await conn.connect({ name: "loki", type: "loki", url: "http://loki:3100", enabled: true });
|
|
423
|
+
let logql = "";
|
|
424
|
+
const orig = globalThis.fetch;
|
|
425
|
+
globalThis.fetch = (async (url) => {
|
|
426
|
+
const u = String(url);
|
|
427
|
+
if (u.includes("/label/") && u.includes("/values"))
|
|
428
|
+
return jsonRes({ data: ["app"] });
|
|
429
|
+
if (u.includes("/query_range")) {
|
|
430
|
+
logql = decodeURIComponent((u.match(/query=([^&]+)/) || [])[1] || "");
|
|
431
|
+
return jsonRes({ data: { result: [] } });
|
|
432
|
+
}
|
|
433
|
+
return jsonRes({ data: [] });
|
|
434
|
+
});
|
|
435
|
+
try {
|
|
436
|
+
await conn.queryLogs({ service: "app", duration: "5m" });
|
|
437
|
+
}
|
|
438
|
+
finally {
|
|
439
|
+
globalThis.fetch = orig;
|
|
440
|
+
}
|
|
441
|
+
assert.ok(logql.includes("| json"), `stream query was never issued: ${logql}`);
|
|
442
|
+
assert.ok(!logql.includes("__error__"), logql);
|
|
443
|
+
});
|
|
444
|
+
});
|
|
445
|
+
describe("#611: Loki error responses keep Loki's explanation", () => {
|
|
446
|
+
const lokiBody = "pipeline error: 'JSONParserErr' for series: '{__error__=\"JSONParserErr\", " +
|
|
447
|
+
"__error_details__=\"Value looks like object, but can't find closing '}' symbol\"}'.\n" +
|
|
448
|
+
"Use a label filter to intentionally skip this error. (e.g | __error__!=\"JSONParserErr\").";
|
|
449
|
+
it("includes the body excerpt after the status line", () => {
|
|
450
|
+
const err = lokiApiError(400, "Bad Request", lokiBody);
|
|
451
|
+
assert.match(err.message, /^Loki API error: 400 Bad Request — pipeline error: 'JSONParserErr'/);
|
|
452
|
+
assert.match(err.message, /Use a label filter/);
|
|
453
|
+
});
|
|
454
|
+
it("collapses line breaks and control characters so the message can't forge log lines", () => {
|
|
455
|
+
const err = lokiApiError(400, "Bad Request", "first\r\nINFO forged line\tx\u0000y");
|
|
456
|
+
assert.doesNotMatch(err.message, /[\r\n\t\u0000]/);
|
|
457
|
+
assert.match(err.message, /first INFO forged line x y$/);
|
|
458
|
+
});
|
|
459
|
+
it("also strips C1 controls that \\s misses (NEL, one-byte CSI)", () => {
|
|
460
|
+
const err = lokiApiError(400, "Bad Request", "a\u0085FORGED\u009b31mred");
|
|
461
|
+
assert.doesNotMatch(err.message, /[\u0080-\u009f]/);
|
|
462
|
+
assert.match(err.message, /— a FORGED 31mred$/);
|
|
463
|
+
});
|
|
464
|
+
it("caps the excerpt at 300 characters", () => {
|
|
465
|
+
const err = lokiApiError(500, "Internal Server Error", "x".repeat(5000));
|
|
466
|
+
const excerpt = err.message.split(" — ")[1];
|
|
467
|
+
assert.equal(excerpt, "x".repeat(300) + "…");
|
|
468
|
+
});
|
|
469
|
+
it("empty body keeps the bare status line", () => {
|
|
470
|
+
assert.equal(lokiApiError(502, "Bad Gateway", "").message, "Loki API error: 502 Bad Gateway");
|
|
471
|
+
assert.equal(lokiApiError(502, "Bad Gateway", " \n ").message, "Loki API error: 502 Bad Gateway");
|
|
472
|
+
});
|
|
473
|
+
it("queryLogAggregate surfaces Loki's reason instead of a bare 400", async () => {
|
|
474
|
+
const conn = new LokiConnector();
|
|
475
|
+
await conn.connect({ name: "loki", type: "loki", url: "http://loki:3100", enabled: true });
|
|
476
|
+
const orig = globalThis.fetch;
|
|
477
|
+
globalThis.fetch = (async (url) => {
|
|
478
|
+
const u = String(url);
|
|
479
|
+
if (u.includes("/label/") && u.includes("/values"))
|
|
480
|
+
return jsonRes({ data: ["app"] });
|
|
481
|
+
if (u.includes("/query")) {
|
|
482
|
+
return { ok: false, status: 400, statusText: "Bad Request", json: async () => ({}), text: async () => lokiBody };
|
|
483
|
+
}
|
|
484
|
+
return jsonRes({ data: [] });
|
|
485
|
+
});
|
|
486
|
+
try {
|
|
487
|
+
await assert.rejects(conn.queryLogAggregate({ service: "app", duration: "1h", op: "sum", by: ["status"] }), /Loki API error: 400 Bad Request — pipeline error: 'JSONParserErr'/);
|
|
488
|
+
}
|
|
489
|
+
finally {
|
|
490
|
+
globalThis.fetch = orig;
|
|
491
|
+
}
|
|
492
|
+
});
|
|
493
|
+
it("an HTML error page from a proxy is not relayed (may name internal upstreams)", async () => {
|
|
494
|
+
const conn = new LokiConnector();
|
|
495
|
+
await conn.connect({ name: "loki", type: "loki", url: "http://loki:3100", enabled: true });
|
|
496
|
+
let bodyRead = false;
|
|
497
|
+
const orig = globalThis.fetch;
|
|
498
|
+
globalThis.fetch = (async (url) => {
|
|
499
|
+
const u = String(url);
|
|
500
|
+
if (u.includes("/label/") && u.includes("/values"))
|
|
501
|
+
return jsonRes({ data: ["app"] });
|
|
502
|
+
return {
|
|
503
|
+
ok: false, status: 502, statusText: "Bad Gateway",
|
|
504
|
+
headers: new Headers({ "content-type": "text/html; charset=utf-8" }),
|
|
505
|
+
json: async () => ({}),
|
|
506
|
+
text: async () => { bodyRead = true; return "<html><body>upstream loki-internal-7.corp:3100 nginx/1.25.3</body></html>"; },
|
|
507
|
+
};
|
|
508
|
+
});
|
|
509
|
+
try {
|
|
510
|
+
await assert.rejects(conn.queryLogAggregate({ service: "app", duration: "1h", op: "sum", by: ["status"] }), (e) => e.message === "Loki API error: 502 Bad Gateway");
|
|
511
|
+
assert.equal(bodyRead, false);
|
|
512
|
+
}
|
|
513
|
+
finally {
|
|
514
|
+
globalThis.fetch = orig;
|
|
515
|
+
}
|
|
516
|
+
});
|
|
517
|
+
it("a body that cannot be read still yields the status line", async () => {
|
|
518
|
+
const conn = new LokiConnector();
|
|
519
|
+
await conn.connect({ name: "loki", type: "loki", url: "http://loki:3100", enabled: true });
|
|
520
|
+
const orig = globalThis.fetch;
|
|
521
|
+
globalThis.fetch = (async (url) => {
|
|
522
|
+
const u = String(url);
|
|
523
|
+
if (u.includes("/label/") && u.includes("/values"))
|
|
524
|
+
return jsonRes({ data: ["app"] });
|
|
525
|
+
return { ok: false, status: 503, statusText: "Service Unavailable", json: async () => ({}), text: async () => { throw new Error("stream reset"); } };
|
|
526
|
+
});
|
|
527
|
+
try {
|
|
528
|
+
await assert.rejects(conn.queryLogAggregate({ service: "app", duration: "1h", op: "sum", by: ["status"] }), (e) => e.message === "Loki API error: 503 Service Unavailable");
|
|
529
|
+
}
|
|
530
|
+
finally {
|
|
531
|
+
globalThis.fetch = orig;
|
|
532
|
+
}
|
|
533
|
+
});
|
|
534
|
+
});
|
package/dist/tools/query-logs.js
CHANGED
|
@@ -33,7 +33,7 @@ export const queryLogsDefinition = {
|
|
|
33
33
|
},
|
|
34
34
|
aggregate: {
|
|
35
35
|
type: "object",
|
|
36
|
-
description: "Server-side aggregation — returns grouped counts, not raw rows, so you get a number instead of a haystack. op: 'count_over_time' (time series of counts per bucket), 'sum' (total per group over the window), 'topk' (top-k groups by total). Example: {\"op\":\"topk\",\"by\":[\"url\"],\"k\":10} for the busiest paths. Honours `labels`/`query` filters.",
|
|
36
|
+
description: "Server-side aggregation — returns grouped counts, not raw rows, so you get a number instead of a haystack. op: 'count_over_time' (time series of counts per bucket), 'sum' (total per group over the window), 'topk' (top-k groups by total). Example: {\"op\":\"topk\",\"by\":[\"url\"],\"k\":10} for the busiest paths. Honours `labels`/`query` filters. Counts only JSON-parseable lines; plain-text lines (startup output, stack traces) are skipped rather than failing the query.",
|
|
37
37
|
properties: {
|
|
38
38
|
op: { type: "string", enum: ["count_over_time", "sum", "topk"] },
|
|
39
39
|
by: { type: "array", items: { type: "string" }, description: "Group-by label names (required for topk)." },
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@thotischner/observability-mcp",
|
|
3
|
-
"version": "3.9.
|
|
3
|
+
"version": "3.9.9",
|
|
4
4
|
"description": "Unified observability gateway for AI agents — one MCP server for Prometheus, Loki, and any backend",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -62,10 +62,10 @@
|
|
|
62
62
|
"@kubernetes/client-node": "^1.4.0",
|
|
63
63
|
"@modelcontextprotocol/sdk": "^1.12.0",
|
|
64
64
|
"@opentelemetry/api": "^1.9.0",
|
|
65
|
-
"@opentelemetry/auto-instrumentations-node": "^0.
|
|
66
|
-
"@opentelemetry/exporter-trace-otlp-http": "^0.
|
|
65
|
+
"@opentelemetry/auto-instrumentations-node": "^0.80.0",
|
|
66
|
+
"@opentelemetry/exporter-trace-otlp-http": "^0.222.0",
|
|
67
67
|
"@opentelemetry/resources": "^2.2.0",
|
|
68
|
-
"@opentelemetry/sdk-node": "^0.
|
|
68
|
+
"@opentelemetry/sdk-node": "^0.222.0",
|
|
69
69
|
"@opentelemetry/semantic-conventions": "^1.40.0",
|
|
70
70
|
"express": "^5.2.1",
|
|
71
71
|
"express-rate-limit": "^8.5.2",
|