@thotischner/observability-mcp 3.2.1 → 3.3.0

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.
@@ -375,3 +375,56 @@ test("E2E tools/call: every registered tool dispatches over MCP and returns a Ca
375
375
  assert.ok(Array.isArray(r.content), `tool ${name} must return content[]`);
376
376
  }
377
377
  });
378
+ test("E2E tools/list: every builtin tool advertises ToolAnnotations (readOnlyHint)", opts, async () => {
379
+ // AX hardening: all 12 builtin tools are read-only; clients (e.g. Claude)
380
+ // use these hints for auto-approve decisions, so they must be advertised
381
+ // over the live transport — not just present in the registration source.
382
+ const session = await newSession();
383
+ const { response } = await jsonRpc("tools/list", {}, { id: 2, session });
384
+ const r = response.result;
385
+ const tools = r.tools ?? [];
386
+ assert.ok(tools.length >= 12, `expected >=12 tools, got ${tools.length}`);
387
+ // Federated tools (namespaced `<prefix>.<tool>`) proxy upstream metadata and
388
+ // may legitimately lack annotations — only the builtin set is asserted.
389
+ const builtin = tools.filter((t) => t.name && !t.name.includes("."));
390
+ for (const t of builtin) {
391
+ assert.equal(t.annotations?.readOnlyHint, true, `tool ${t.name} must advertise annotations.readOnlyHint=true`);
392
+ assert.ok(t.annotations?.title, `tool ${t.name} must advertise annotations.title`);
393
+ }
394
+ });
395
+ test("E2E: builtin resource agent-usage-guide is listed and readable", opts, async () => {
396
+ // AX: the agent usage guide ships as an MCP resource so clients can pull
397
+ // it into context without a web fetch. Assert list + read over the wire.
398
+ const session = await newSession();
399
+ const list = await jsonRpc("resources/list", {}, { id: 10, session });
400
+ const resources = list.response.result?.resources ?? [];
401
+ assert.ok(resources.some((r) => r.uri === "omcp://guide/agent-usage"), `agent-usage-guide resource must be listed, got ${JSON.stringify(resources.map((r) => r.uri))}`);
402
+ const read = await jsonRpc("resources/read", { uri: "omcp://guide/agent-usage" }, { id: 11, session });
403
+ const contents = read.response.result?.contents ?? [];
404
+ assert.ok((contents[0]?.text ?? "").includes("Triage recipe"), "guide text must round-trip");
405
+ });
406
+ test("E2E: builtin prompts triage-incident + write-postmortem are listed and resolvable", opts, async () => {
407
+ const session = await newSession();
408
+ const list = await jsonRpc("prompts/list", {}, { id: 12, session });
409
+ const prompts = list.response.result?.prompts ?? [];
410
+ for (const name of ["triage-incident", "write-postmortem"]) {
411
+ assert.ok(prompts.some((p) => p.name === name), `prompt ${name} must be listed`);
412
+ }
413
+ const got = await jsonRpc("prompts/get", { name: "triage-incident", arguments: { service: "ci-probe" } }, { id: 13, session });
414
+ const msgs = got.response.result?.messages ?? [];
415
+ assert.ok((msgs[0]?.content?.text ?? "").includes('"ci-probe"'), "prompt must interpolate the service arg");
416
+ });
417
+ test("E2E: /llms.txt is served and reflects the canonical tool registry", opts, async () => {
418
+ // llms.txt convention: LLM-readable summary at the server root. Generated
419
+ // from registry-names.ts, so this also guards against registry drift.
420
+ const base = URL_ENV.replace(/\/mcp\/?$/, "");
421
+ const res = await fetch(`${base}/llms.txt`);
422
+ assert.equal(res.status, 200);
423
+ assert.match(res.headers.get("content-type") ?? "", /text\/plain/);
424
+ const text = await res.text();
425
+ assert.match(text, /^# observability-mcp/, "must start with the llms.txt H1");
426
+ for (const name of ["query_logs", "query_metrics", "enrich_ips", "get_blast_radius"]) {
427
+ assert.ok(text.includes(`- ${name} (`), `tool ${name} must be listed`);
428
+ }
429
+ assert.ok(text.includes("for-agents"), "must link the for-agents guide");
430
+ });
package/dist/index.js CHANGED
@@ -393,15 +393,95 @@ async function main() {
393
393
  }
394
394
  return mcpServer.prompt(name, ...rest);
395
395
  });
396
- // Suppress unused-warn kept for the moment registrations land.
397
- void registerResource;
398
- void registerPrompt;
396
+ // --- Builtin resources + prompts (agent experience) -------------------
397
+ // The usage guide is the distilled, agent-validated workflow from issue
398
+ // #415 — served as an MCP resource so a client can pull it into context
399
+ // without a web fetch. Prompts compose the existing read-only tools into
400
+ // the two flows agents run most.
401
+ registerResource("agent-usage-guide", "omcp://guide/agent-usage", {
402
+ description: "How to use this gateway effectively as an agent: the proven filter→aggregate→enrich triage recipe, signal-vs-silence behaviours, and the operator flags that unlock optional tools.",
403
+ mimeType: "text/markdown",
404
+ }, async (uri) => ({
405
+ contents: [
406
+ {
407
+ uri: uri.toString(),
408
+ mimeType: "text/markdown",
409
+ text: [
410
+ "# Agent usage guide (observability-mcp)",
411
+ "",
412
+ "All tools are read-only (`readOnlyHint: true`). The golden rule:",
413
+ "**filter and aggregate server-side — ask for numbers, not haystacks.**",
414
+ "",
415
+ "## Triage recipe (agent-validated, issue #415)",
416
+ '1. `query_logs` with `labels` (exact-match field filters, e.g. {"environment":"prod"})',
417
+ ' and `aggregate` ({"op":"topk","by":["ip"],"k":10} or {"op":"count_over_time","step":"15m"})',
418
+ " — pushed down to LogQL, returns a handful of numbers instead of thousands of rows.",
419
+ "2. `enrich_ips` with the IPs from step 1 — offline geo/ASN/hosting-flag lookup",
420
+ " (bot-vs-human signal). Requires OMCP_IP_ENRICH_FILE on the operator side.",
421
+ '3. `query_metrics` with `labels` ({"route":"/checkout"}) and `groupBy` to scope a',
422
+ " curated metric to the slice you care about.",
423
+ "",
424
+ "## Incident flow",
425
+ "`detect_anomalies` (fleet scan) → `get_service_health` (one-service verdict) →",
426
+ "`get_blast_radius` (shared-host impact) → `generate_postmortem` (markdown report).",
427
+ "",
428
+ "## When something is empty or refused",
429
+ "The gateway explains itself: no topology connector → explicit note; no trace",
430
+ "backend → explicit error; `raw_query` disabled → message naming OMCP_RAW_QUERY=on;",
431
+ "redacted values → a `_redacted` count in the result. Relay flag names to your",
432
+ "operator verbatim — the messages are written to be forwarded.",
433
+ "",
434
+ "## Report findings",
435
+ "Structured agent reports drive releases here (see issue #415). File one:",
436
+ "https://github.com/ThoTischner/observability-mcp/issues/new?template=agent-report.yml",
437
+ "Full guide: https://thotischner.github.io/observability-mcp/for-agents/",
438
+ ].join("\n"),
439
+ },
440
+ ],
441
+ }));
442
+ registerPrompt("triage-incident", "Guided incident triage for one service: health verdict, anomaly scan, blast radius, and the log slice that matters.", { service: z.string().describe("Service name as returned by list_services") }, ({ service }) => ({
443
+ messages: [
444
+ {
445
+ role: "user",
446
+ content: {
447
+ type: "text",
448
+ text: [
449
+ `Triage the service "${service}" using the observability-mcp tools, in this order:`,
450
+ `1. get_service_health {"service":"${service}"} — the current verdict and why.`,
451
+ `2. detect_anomalies {"service":"${service}","duration":"1h"} — what is statistically off.`,
452
+ `3. get_blast_radius {"resource":"${service}"} — who else fails if its host fails.`,
453
+ `4. query_logs {"service":"${service}","level":"error","aggregate":{"op":"count_over_time","step":"5m"},"duration":"1h"} — error-volume shape over time; drill into raw rows only for the spike window.`,
454
+ "Then summarise: current state, most likely cause, blast radius, and the next diagnostic step. Prefer aggregated queries over raw log dumps.",
455
+ ].join("\n"),
456
+ },
457
+ },
458
+ ],
459
+ }));
460
+ registerPrompt("write-postmortem", "Generate and refine a post-incident report for one service over a window.", {
461
+ service: z.string().describe("Service name as returned by list_services"),
462
+ duration: z.string().optional().describe("Look-back window, e.g. '1h', '6h'. Default '1h'."),
463
+ }, ({ service, duration }) => ({
464
+ messages: [
465
+ {
466
+ role: "user",
467
+ content: {
468
+ type: "text",
469
+ text: [
470
+ `Produce a post-mortem for "${service}" over the last ${duration || "1h"}:`,
471
+ `1. generate_postmortem {"service":"${service}","duration":"${duration || "1h"}"} — the stitched report (anomaly timeline, blast radius, traces, log highlights).`,
472
+ `2. Verify its claims: get_anomaly_history {"service":"${service}","duration":"${duration || "1h"}"} for the score timeline, and query_logs with an aggregate for the error shape.`,
473
+ "3. Rewrite the result as a blameless post-mortem: summary, impact, timeline, root-cause hypothesis (with confidence), follow-ups. Mark any section the gateway reported as missing data instead of inventing content.",
474
+ ].join("\n"),
475
+ },
476
+ },
477
+ ],
478
+ }));
399
479
  registerTool("list_sources", [
400
480
  "List the configured observability backends (Prometheus, Loki, and any connector) and whether each is currently reachable.",
401
481
  "When to use: call this first to learn which source names exist and are healthy before passing `source` to other tools, or to debug why a query returns no data.",
402
482
  "Behavior: read-only, no side effects. Returns one entry per source with its name, type, signal types (metrics/logs), and a live up/down status (the backend URL is intentionally not exposed — it may carry embedded credentials). Never throws for an unreachable backend — the backend is reported as down instead.",
403
483
  "Related: use `list_services` to see what is monitored within these sources.",
404
- ].join(" "), {}, async () => {
484
+ ].join(" "), {}, { title: "List Sources", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, async () => {
405
485
  await enforceEntitledAccess(ctx, { tool: "list_sources" });
406
486
  return withToolMetrics("list_sources", () => listSourcesHandler(registry, ctx));
407
487
  });
@@ -415,7 +495,7 @@ async function main() {
415
495
  .string()
416
496
  .optional()
417
497
  .describe("Optional case-insensitive substring to narrow the result to matching service names (e.g. 'payment'). Omit to list every discovered service."),
418
- }, async (args) => {
498
+ }, { title: "List Services", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, async (args) => {
419
499
  await enforceEntitledAccess(ctx, { tool: "list_services" });
420
500
  const result = await withToolMetrics("list_services", () => listServicesHandler(registry, args, ctx));
421
501
  return enrichToolServicesText(result, ctx);
@@ -458,7 +538,7 @@ async function main() {
458
538
  .string()
459
539
  .optional()
460
540
  .describe("Optional escape hatch: a verbatim PromQL expression, run as-is over the range — for ad-hoc queries the curated `metric` catalog can't express (any series, any function, broken down by any label). When set, `metric`/`service`/`groupBy`/`labels` are ignored. DISABLED by default; the operator must enable the raw-query capability (OMCP_RAW_QUERY=on) or the call is refused. Still tenant-scoped and source-allow-listed."),
461
- }, async (args) => {
541
+ }, { title: "Query Metrics", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, async (args) => {
462
542
  await enforceEntitledAccess(ctx, { tool: "query_metrics", source: args?.source, service: args?.service });
463
543
  const result = await withToolMetrics("query_metrics", () => queryMetricsHandler(registry, args, ctx, { allowRawQuery: RAW_QUERY_ENABLED }));
464
544
  return chargeTokenBudget(result, ctx, "query_metrics");
@@ -525,7 +605,7 @@ async function main() {
525
605
  .string()
526
606
  .optional()
527
607
  .describe("Optional escape hatch: a verbatim LogQL log query, run as-is — for selectors/pipelines the curated params can't express. When set, `service`/`labels`/`level`/`query` are ignored and it is mutually exclusive with `aggregate` (express aggregation in the LogQL itself). DISABLED by default; the operator must enable the raw-query capability (OMCP_RAW_QUERY=on) or the call is refused. Redaction still applies to the returned log lines."),
528
- }, async (args) => {
608
+ }, { title: "Query Logs", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, async (args) => {
529
609
  await enforceEntitledAccess(ctx, { tool: "query_logs", source: args?.source, service: args?.service });
530
610
  const result = await withToolMetrics("query_logs", () => queryLogsHandler(registry, args, ctx, { allowRawQuery: RAW_QUERY_ENABLED }));
531
611
  // Redact PII / secrets from the log payload before it crosses the
@@ -565,7 +645,7 @@ async function main() {
565
645
  service: z.string().describe("Service name to filter on."),
566
646
  duration: z.string().optional().describe("Rolling window, e.g. '1h', '24h'. Default '1h'."),
567
647
  method: z.string().optional().describe("Filter by detector method ('mad' / 'seasonality' / 'correlator'). Optional."),
568
- }, async (args) => {
648
+ }, { title: "Anomaly History", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, async (args) => {
569
649
  await enforceEntitledAccess(ctx, { tool: "get_anomaly_history", service: args?.service });
570
650
  const result = await withToolMetrics("get_anomaly_history", () => getAnomalyHistoryHandler(registry, args, ctx));
571
651
  return chargeTokenBudget(result, ctx, "get_anomaly_history");
@@ -580,7 +660,7 @@ async function main() {
580
660
  service: z.string().describe("Suspected root-cause service."),
581
661
  duration: z.string().optional().describe("Window length, e.g. '1h', '6h'. Default '1h'."),
582
662
  format: z.enum(["markdown", "json"]).optional().describe("'markdown' (default) or 'json'."),
583
- }, async (args) => {
663
+ }, { title: "Generate Postmortem", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, async (args) => {
584
664
  await enforceEntitledAccess(ctx, { tool: "generate_postmortem", service: args?.service });
585
665
  const result = await withToolMetrics("generate_postmortem", () => generatePostmortemHandler(registry, args, ctx));
586
666
  return chargeTokenBudget(result, ctx, "generate_postmortem");
@@ -597,7 +677,7 @@ async function main() {
597
677
  filter: z.string().optional().describe("Backend-native filter (TraceQL on Tempo, tag query on Jaeger). Optional."),
598
678
  limit: z.number().int().positive().optional().describe("Soft cap on returned trace summaries. Default 50."),
599
679
  errorsOnly: z.boolean().optional().describe("If true, only traces with at least one error span."),
600
- }, async (args) => {
680
+ }, { title: "Query Traces", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, async (args) => {
601
681
  await enforceEntitledAccess(ctx, { tool: "query_traces", service: args?.service });
602
682
  const result = await withToolMetrics("query_traces", () => queryTracesHandler(registry, args, ctx));
603
683
  return chargeTokenBudget(result, ctx, "query_traces");
@@ -611,7 +691,7 @@ async function main() {
611
691
  service: z
612
692
  .string()
613
693
  .describe("Required. Exact, case-sensitive service name exactly as returned by `list_services` (e.g. 'payment-service')."),
614
- }, async (args) => {
694
+ }, { title: "Service Health", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, async (args) => {
615
695
  await enforceEntitledAccess(ctx, { tool: "get_service_health", service: args?.service });
616
696
  const result = await withToolMetrics("get_service_health", () => getServiceHealthHandler(registry, args, ctx));
617
697
  const enriched = enrichToolHealthText(result, String(args?.service ?? ""), ctx);
@@ -635,7 +715,7 @@ async function main() {
635
715
  .enum(["low", "medium", "high"])
636
716
  .optional()
637
717
  .describe("Optional. Detection threshold: 'low' flags only strong deviations (>3σ), 'medium' is balanced (>2σ), 'high' is most sensitive and noisier (>1.5σ). Default: 'medium'."),
638
- }, async (args) => {
718
+ }, { title: "Detect Anomalies", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, async (args) => {
639
719
  await enforceEntitledAccess(ctx, { tool: "detect_anomalies", source: args?.source, service: args?.service });
640
720
  // P1: pass the anomaly-history sink so detected scores flow
641
721
  // into the TSDB and `get_anomaly_history` returns real data.
@@ -666,7 +746,7 @@ async function main() {
666
746
  .max(5000)
667
747
  .optional()
668
748
  .describe("Optional. Maximum resources to return; edges are trimmed to the kept set. Default 500, max 5000."),
669
- }, async (args) => {
749
+ }, { title: "Topology Graph", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, async (args) => {
670
750
  await enforceEntitledAccess(ctx, { tool: "get_topology", source: args?.source });
671
751
  return withToolMetrics("get_topology", () => getTopologyHandler(registry, args, ctx));
672
752
  });
@@ -679,7 +759,7 @@ async function main() {
679
759
  resource: z
680
760
  .string()
681
761
  .describe("Required. Resource to evaluate. Accepts the canonical id (e.g. 'k8s:pod:default/checkout-7f89d'), the exact resource name (e.g. 'checkout-7f89d'), or a unique substring of either."),
682
- }, async (args) => {
762
+ }, { title: "Blast Radius", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, async (args) => {
683
763
  await enforceEntitledAccess(ctx, { tool: "get_blast_radius" });
684
764
  return withToolMetrics("get_blast_radius", () => getBlastRadiusHandler(registry, args, ctx));
685
765
  });
@@ -692,7 +772,7 @@ async function main() {
692
772
  ips: z
693
773
  .array(z.string())
694
774
  .describe("Required. IPv4 address strings to enrich (e.g. ['203.0.113.5','198.51.100.9']). Max 1000 per call; invalid entries are returned with found=false rather than failing the batch."),
695
- }, async (args) => {
775
+ }, { title: "Enrich IPs", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, async (args) => {
696
776
  await enforceEntitledAccess(ctx, { tool: "enrich_ips" });
697
777
  return withToolMetrics("enrich_ips", async () => enrichIpsHandler(ipEnrichment, args, ctx));
698
778
  });
@@ -1195,6 +1275,41 @@ async function main() {
1195
1275
  // enough to skip the request-counter middleware.
1196
1276
  let ready = false;
1197
1277
  app.get("/healthz", (_req, res) => res.type("text").send("ok"));
1278
+ // /llms.txt — the llms.txt convention (llmstxt.org): a plain-text,
1279
+ // LLM-friendly summary of what this server is and how to use it. The
1280
+ // primary audience of this gateway IS an LLM agent, so the gateway
1281
+ // serves its own. Tool list is generated from the canonical registry
1282
+ // (registry-names.ts) so it can't drift from the real surface.
1283
+ const LLMS_TXT = [
1284
+ "# observability-mcp",
1285
+ "",
1286
+ `> Unified observability gateway for AI agents (v${SERVER_VERSION}). One MCP server`,
1287
+ "> for Prometheus, Loki, and any backend via pluggable connectors — with",
1288
+ "> server-side filtering/aggregation so agents get numbers, not haystacks.",
1289
+ "",
1290
+ "MCP endpoint: POST /mcp (Streamable HTTP) · also stdio (--stdio) and WebSocket (/mcp/ws).",
1291
+ "All tools are read-only and advertise MCP ToolAnnotations (readOnlyHint: true).",
1292
+ "MCP resource omcp://guide/agent-usage carries the agent usage guide;",
1293
+ "prompts triage-incident and write-postmortem compose the tools into workflows.",
1294
+ "",
1295
+ "## Tools",
1296
+ "",
1297
+ ...REGISTERED_TOOLS.map((t) => `- ${t.name} (${t.category}): ${t.summary}`),
1298
+ "",
1299
+ "## Connect",
1300
+ "",
1301
+ " claude mcp add observability --transport http http://localhost:3000/mcp",
1302
+ "",
1303
+ "## Docs",
1304
+ "",
1305
+ "- For agents (start here): https://thotischner.github.io/observability-mcp/for-agents/",
1306
+ "- Documentation site: https://thotischner.github.io/observability-mcp/",
1307
+ "- Report a finding (agent-report template): https://github.com/ThoTischner/observability-mcp/issues/new?template=agent-report.yml",
1308
+ "- Discussions (agent collaboration welcome): https://github.com/ThoTischner/observability-mcp/discussions",
1309
+ "- Source: https://github.com/ThoTischner/observability-mcp",
1310
+ "",
1311
+ ].join("\n");
1312
+ app.get("/llms.txt", (_req, res) => res.type("text/plain; charset=utf-8").send(LLMS_TXT));
1198
1313
  // Procurement-time probe: the MCP spec revisions and transports the
1199
1314
  // gateway supports. Static today — kept as a separate endpoint so a
1200
1315
  // discovery tool / RFP probe / catalog scanner can resolve our
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thotischner/observability-mcp",
3
- "version": "3.2.1",
3
+ "version": "3.3.0",
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",