@thotischner/observability-mcp 3.9.15 → 3.9.17

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.
@@ -93,9 +93,9 @@ export declare function enterprisePolicyView(): {
93
93
  data: any;
94
94
  error?: undefined;
95
95
  } | {
96
+ data?: undefined;
96
97
  configured: true;
97
98
  error: string;
98
- data?: undefined;
99
99
  };
100
100
  /** The loaded product catalog (read-only view). */
101
101
  export declare function enterpriseCatalogView(): {
@@ -107,14 +107,14 @@ export declare function enterpriseCatalogView(): {
107
107
  data: any;
108
108
  error?: undefined;
109
109
  } | {
110
+ data?: undefined;
110
111
  configured: true;
111
112
  error: string;
112
- data?: undefined;
113
113
  };
114
114
  /** Recent audit decisions + a tamper-evidence check over the whole log. */
115
115
  export declare function enterpriseAuditTail(limit?: number): Promise<{
116
- configured: false;
117
116
  error?: undefined;
117
+ configured: false;
118
118
  total?: undefined;
119
119
  chain?: undefined;
120
120
  entries?: undefined;
@@ -125,11 +125,11 @@ export declare function enterpriseAuditTail(limit?: number): Promise<{
125
125
  chain?: undefined;
126
126
  entries?: undefined;
127
127
  } | {
128
+ error?: undefined;
128
129
  configured: true;
129
130
  total: number;
130
131
  chain: unknown;
131
132
  entries: unknown[];
132
- error?: undefined;
133
133
  }>;
134
134
  export declare const ADMIN_CAP = "enterprise:admin";
135
135
  /** Structural validation — never trust a PUT body. */
package/dist/index.js CHANGED
@@ -47,6 +47,7 @@ import { isValidConnectorName, installTarball } from "./connectors/install.js";
47
47
  import { PluginVerificationError } from "./connectors/verify.js";
48
48
  import { selfRegistry, withToolMetrics, apiRequests, mcpActiveSessions, auditDlqDepth, recordInspectEvent } from "./metrics/self.js";
49
49
  import { initOtel } from "./observability/otel.js";
50
+ import { installShutdown, isShuttingDown, onShutdown } from "./util/shutdown.js";
50
51
  import { WebSocketServerTransport } from "./transport/websocket.js";
51
52
  import { HookRegistry } from "./sdk/hooks.js";
52
53
  import { InspectStore, ModeController, bootMode, createInspectRecorder, createInspectEnforcer, buildFlowGraph, durationToSeconds, ProfileStore } from "./inspect/index.js";
@@ -1216,11 +1217,7 @@ async function main() {
1216
1217
  sinks: auditSinks,
1217
1218
  });
1218
1219
  await mgmtAudit.bootstrap();
1219
- process.on("SIGTERM", () => {
1220
- mgmtAudit
1221
- .flushSinks()
1222
- .catch((err) => console.warn("AuditLog flushSinks failed:", err));
1223
- });
1220
+ onShutdown("audit sinks", () => mgmtAudit.flushSinks());
1224
1221
  const audit = (resource, action) => buildAuditMiddleware({ audit: mgmtAudit, resource, action });
1225
1222
  // Q20 — CSP violation report sink. Unauthenticated browser POST (exempt
1226
1223
  // from CSRF via csrfCfg.skip), tightly rate-limited so a misbehaving or
@@ -1320,9 +1317,7 @@ async function main() {
1320
1317
  if (anomalyHistory.isEnabled()) {
1321
1318
  console.log("AnomalyHistory: TSDB sink enabled (OMCP_ANOMALY_HISTORY_REMOTE_WRITE set)");
1322
1319
  }
1323
- process.on("SIGTERM", () => {
1324
- void anomalyHistory.stop().catch(() => undefined);
1325
- });
1320
+ onShutdown("anomaly history", () => anomalyHistory.stop());
1326
1321
  // Federation registry — populated from OMCP_FEDERATION_UPSTREAMS at
1327
1322
  // boot. Each upstream connects, fetches tools/list, and exposes its
1328
1323
  // tools under `<prefix>.<upstream-tool-name>` on the gateway's
@@ -1343,11 +1338,7 @@ async function main() {
1343
1338
  if (federationRegistry.list().length > 0) {
1344
1339
  console.log("federation: %d upstream(s) configured: %s", federationRegistry.list().length, federationRegistry.list().map((u) => `${u.name}=${u.url}`).join(", "));
1345
1340
  }
1346
- process.on("SIGTERM", () => {
1347
- federationRegistry
1348
- .closeAll()
1349
- .catch((err) => console.warn("federation closeAll failed:", err));
1350
- });
1341
+ onShutdown("federation upstreams", () => federationRegistry.closeAll());
1351
1342
  // Service catalog: optional operator-curated ownership / criticality /
1352
1343
  // on-call metadata, keyed on the service name list_services returns.
1353
1344
  // No file ⇒ empty catalog, enrichment is a no-op (anonymous demos
@@ -1457,7 +1448,7 @@ async function main() {
1457
1448
  });
1458
1449
  });
1459
1450
  app.get("/readyz", (_req, res) => {
1460
- if (ready)
1451
+ if (ready && !isShuttingDown())
1461
1452
  return res.type("text").send("ok");
1462
1453
  return res.status(503).type("text").send("starting");
1463
1454
  });
@@ -3533,6 +3524,9 @@ async function main() {
3533
3524
  .getAll()
3534
3525
  .map((c) => c.name)
3535
3526
  .join(", ")}`);
3527
+ // No HTTP listener here, but the audit / history / federation hooks
3528
+ // registered above still need flushing when the client stops us.
3529
+ installShutdown();
3536
3530
  return;
3537
3531
  }
3538
3532
  // MCP Streamable HTTP transport — stateful sessions
@@ -3614,11 +3608,7 @@ async function main() {
3614
3608
  // Flush on graceful shutdown so the debounce-window of pending
3615
3609
  // charges isn't dropped on `kubectl rollout restart` etc. The
3616
3610
  // process keeps running while we wait — the snapshot is small.
3617
- for (const sig of ["SIGTERM", "SIGINT"]) {
3618
- process.once(sig, () => {
3619
- void tokenBudget.flushNow().catch(() => { });
3620
- });
3621
- }
3611
+ onShutdown("token budget", () => tokenBudget.flushNow());
3622
3612
  // Bearer/X-API-Key on every /mcp request; resolve the principal + its
3623
3613
  // coarse source allow-list into the RequestContext.
3624
3614
  async function gateCtx(req, res) {
@@ -3928,6 +3918,7 @@ async function main() {
3928
3918
  console.log(` Web UI: http://localhost:${PORT}`);
3929
3919
  console.log(` Connectors: ${registry.getAll().map((c) => c.name).join(", ")}`);
3930
3920
  });
3921
+ installShutdown({ server: httpServer });
3931
3922
  // Mount the WebSocket MCP transport. One McpServer instance per
3932
3923
  // accepted socket; per-connection state is carried in
3933
3924
  // WebSocketServerTransport.sessionId so concurrent clients stay
@@ -1,12 +1,12 @@
1
1
  import { Registry, Counter, Histogram, Gauge } from "prom-client";
2
2
  export declare const selfRegistry: Registry<"text/plain; version=0.0.4; charset=utf-8">;
3
- export declare const mcpToolCalls: Counter<"tool" | "outcome">;
3
+ export declare const mcpToolCalls: Counter<"outcome" | "tool">;
4
4
  export declare const mcpToolLatency: Histogram<"tool">;
5
- export declare const connectorCalls: Counter<"type" | "source" | "outcome" | "operation">;
6
- export declare const apiRequests: Counter<"status" | "route" | "method">;
5
+ export declare const connectorCalls: Counter<"operation" | "outcome" | "source" | "type">;
6
+ export declare const apiRequests: Counter<"method" | "route" | "status">;
7
7
  export declare const mcpActiveSessions: Gauge<string>;
8
8
  export declare const auditDlqDepth: Gauge<string>;
9
- export declare const inspectEvents: Counter<"tool" | "outcome" | "decision">;
9
+ export declare const inspectEvents: Counter<"decision" | "outcome" | "tool">;
10
10
  /** Record one inspection observation in the self-metrics registry. Never throws. */
11
11
  export declare function recordInspectEvent(tool: string, outcome: string, decision: string): void;
12
12
  /**
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,124 @@
1
+ // End-to-end check that self-tracing actually exports. initOtel() degrades
2
+ // to "disabled" with a warning when the SDK API doesn't match, so an OTel
3
+ // upgrade can silently switch tracing off while every other test stays
4
+ // green. This boots the real server with tracing on, points it at a local
5
+ // OTLP/HTTP receiver, sends requests and waits for their spans.
6
+ import { test } from "node:test";
7
+ import assert from "node:assert/strict";
8
+ import { spawn } from "node:child_process";
9
+ import { createServer } from "node:http";
10
+ import { mkdtempSync, rmSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join, resolve, dirname } from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
15
+ const SERVICE = "omcp-otel-export-test";
16
+ function readBody(req) {
17
+ return new Promise((ok, fail) => {
18
+ const chunks = [];
19
+ req.on("data", (c) => chunks.push(c));
20
+ req.on("end", () => ok(Buffer.concat(chunks)));
21
+ req.on("error", fail);
22
+ });
23
+ }
24
+ async function freePort() {
25
+ const s = createServer();
26
+ await new Promise((ok) => s.listen(0, "127.0.0.1", ok));
27
+ const { port } = s.address();
28
+ await new Promise((ok) => s.close(() => ok()));
29
+ return port;
30
+ }
31
+ async function waitFor(what, fn, ms) {
32
+ const deadline = Date.now() + ms;
33
+ for (;;) {
34
+ const v = await fn();
35
+ if (v !== undefined)
36
+ return v;
37
+ if (Date.now() > deadline)
38
+ throw new Error(`timed out waiting for ${what}`);
39
+ await new Promise((r) => setTimeout(r, 250));
40
+ }
41
+ }
42
+ test("server exports HTTP spans with its service.name to the OTLP endpoint", { timeout: 150_000 }, async () => {
43
+ const exports = [];
44
+ const receiver = createServer(async (req, res) => {
45
+ if (req.method === "POST" && req.url === "/v1/traces")
46
+ exports.push(await readBody(req));
47
+ res.writeHead(200, { "content-type": "application/json" }).end("{}");
48
+ });
49
+ await new Promise((ok) => receiver.listen(0, "127.0.0.1", ok));
50
+ const otlpPort = receiver.address().port;
51
+ const port = await freePort();
52
+ const work = mkdtempSync(join(tmpdir(), "omcp-otel-"));
53
+ let log = "";
54
+ // Inherited OTEL_* settings (e.g. OTEL_SDK_DISABLED in CI) must not
55
+ // change what the server does here.
56
+ const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith("OTEL_")));
57
+ const server = spawn(process.execPath, [join(ROOT, "node_modules/tsx/dist/cli.mjs"), join(ROOT, "src/index.ts")], {
58
+ cwd: ROOT,
59
+ env: {
60
+ ...env,
61
+ PORT: String(port),
62
+ CONFIG_PATH: join(work, "sources.yaml"),
63
+ OMCP_OTEL_ENABLED: "true",
64
+ OMCP_OTEL_ENDPOINT: `http://127.0.0.1:${otlpPort}/v1/traces`,
65
+ OMCP_OTEL_SERVICE_NAME: SERVICE,
66
+ OTEL_BSP_SCHEDULE_DELAY: "200",
67
+ },
68
+ stdio: ["ignore", "pipe", "pipe"],
69
+ // Own process group: tsx runs the server as a child process.
70
+ detached: true,
71
+ });
72
+ const exited = new Promise((ok) => server.once("exit", ok));
73
+ server.stdout.on("data", (d) => (log += d));
74
+ server.stderr.on("data", (d) => (log += d));
75
+ try {
76
+ await waitFor("server /healthz", async () => {
77
+ const r = await fetch(`http://127.0.0.1:${port}/healthz`).catch(() => undefined);
78
+ return r?.ok ? true : undefined;
79
+ }, 60_000).catch((e) => { throw new Error(`${e.message}\n--- server log ---\n${log}`); });
80
+ assert.match(log, /OTel self-tracing enabled/, `tracing did not start:\n${log}`);
81
+ assert.doesNotMatch(log, /OTel init failed/, log);
82
+ for (let i = 0; i < 3; i++)
83
+ await fetch(`http://127.0.0.1:${port}/api/health`).catch(() => undefined);
84
+ // The HTTP exporter sends OTLP/JSON; match the resource and an HTTP
85
+ // server span rather than raw bytes.
86
+ const found = await waitFor("an exported HTTP server span", () => {
87
+ for (const body of exports) {
88
+ let doc;
89
+ try {
90
+ doc = JSON.parse(body.toString("utf8"));
91
+ }
92
+ catch {
93
+ continue;
94
+ }
95
+ for (const rs of doc.resourceSpans ?? []) {
96
+ const svc = (rs.resource?.attributes ?? []).find((a) => a.key === "service.name")?.value?.stringValue;
97
+ if (svc !== SERVICE)
98
+ continue;
99
+ const spans = (rs.scopeSpans ?? []).flatMap((s) => s.spans ?? []);
100
+ // SpanKind SERVER = 2 in OTLP/JSON.
101
+ const http = spans.find((s) => s.kind === 2 || s.kind === "SPAN_KIND_SERVER");
102
+ if (http)
103
+ return http;
104
+ }
105
+ }
106
+ return undefined;
107
+ }, 30_000).catch((e) => {
108
+ throw new Error(`${e.message}; ${exports.length} export request(s) received\n--- server log ---\n${log}`);
109
+ });
110
+ assert.ok(found.name, "exported span has a name");
111
+ }
112
+ finally {
113
+ server.kill("SIGTERM");
114
+ const stopped = await Promise.race([exited, new Promise((ok) => setTimeout(() => ok("hung"), 20_000).unref())]);
115
+ // Also reaps a server child left behind if only the tsx wrapper exited.
116
+ try {
117
+ process.kill(-server.pid, "SIGKILL");
118
+ }
119
+ catch { /* group already gone */ }
120
+ await new Promise((ok) => receiver.close(() => ok()));
121
+ rmSync(work, { recursive: true, force: true });
122
+ assert.notEqual(stopped, "hung", `server still running 20s after SIGTERM\n${log}`);
123
+ }
124
+ });
@@ -15,6 +15,7 @@
15
15
  // Imports are dynamic so the @opentelemetry/* packages stay outside the
16
16
  // startup hot path when otel is disabled.
17
17
  import { hostname } from "node:os";
18
+ import { onShutdown } from "../util/shutdown.js";
18
19
  let initialized = false;
19
20
  let result = { enabled: false, reason: "init not called" };
20
21
  export function isOtelEnabled(env = process.env) {
@@ -78,13 +79,9 @@ export async function initOtel(opts = {}) {
78
79
  ],
79
80
  });
80
81
  sdk.start();
81
- // Best-effort flush on shutdown so in-flight spans reach the
82
- // collector during a rolling restart.
83
- process.on("SIGTERM", () => {
84
- sdk
85
- .shutdown()
86
- .catch((err) => console.warn("OTel SDK shutdown failed:", err));
87
- });
82
+ // Flush on shutdown so in-flight spans reach the collector during a
83
+ // rolling restart.
84
+ onShutdown("otel sdk", () => sdk.shutdown());
88
85
  result = { enabled: true, endpoint, serviceName };
89
86
  console.log("OTel self-tracing enabled: exporting to %s as service.name=%s", endpoint, serviceName);
90
87
  return result;
@@ -6,10 +6,10 @@ export declare const manifestSchema: z.ZodObject<{
6
6
  version: z.ZodString;
7
7
  description: z.ZodString;
8
8
  signalTypes: z.ZodArray<z.ZodEnum<{
9
- metrics: "metrics";
10
9
  logs: "logs";
11
- traces: "traces";
10
+ metrics: "metrics";
12
11
  topology: "topology";
12
+ traces: "traces";
13
13
  }>>;
14
14
  homepage: z.ZodOptional<z.ZodString>;
15
15
  license: z.ZodOptional<z.ZodString>;
@@ -33,19 +33,19 @@ export declare const manifestSchema: z.ZodObject<{
33
33
  integrity: z.ZodOptional<z.ZodString>;
34
34
  hooks: z.ZodOptional<z.ZodArray<z.ZodObject<{
35
35
  kind: z.ZodEnum<{
36
- tool_pre_invoke: "tool_pre_invoke";
37
- tool_post_invoke: "tool_post_invoke";
38
- resource_pre_fetch: "resource_pre_fetch";
39
- resource_post_fetch: "resource_post_fetch";
40
- prompt_pre_fetch: "prompt_pre_fetch";
41
36
  prompt_post_fetch: "prompt_post_fetch";
37
+ prompt_pre_fetch: "prompt_pre_fetch";
38
+ resource_post_fetch: "resource_post_fetch";
39
+ resource_pre_fetch: "resource_pre_fetch";
40
+ tool_post_invoke: "tool_post_invoke";
41
+ tool_pre_invoke: "tool_pre_invoke";
42
42
  }>;
43
43
  module: z.ZodString;
44
44
  priority: z.ZodOptional<z.ZodNumber>;
45
45
  mode: z.ZodOptional<z.ZodEnum<{
46
+ disabled: "disabled";
46
47
  enforce: "enforce";
47
48
  permissive: "permissive";
48
- disabled: "disabled";
49
49
  }>>;
50
50
  }, z.core.$strip>>>;
51
51
  }, z.core.$strip>;
@@ -55,10 +55,10 @@ export declare function getBlastRadiusHandler(registry: ConnectorRegistry, args:
55
55
  text: string;
56
56
  }[];
57
57
  } | {
58
+ isError?: undefined;
58
59
  content: {
59
60
  type: "text";
60
61
  text: string;
61
62
  }[];
62
- isError?: undefined;
63
63
  }>;
64
64
  export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,104 @@
1
+ // The real server must exit on SIGTERM. It used to register several
2
+ // flush-only SIGTERM listeners and never exit, so Kubernetes and Docker
3
+ // SIGKILLed it after the grace period.
4
+ import { test } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { spawn } from "node:child_process";
7
+ import { createServer } from "node:http";
8
+ import { mkdtempSync, rmSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join, resolve, dirname } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
13
+ async function freePort() {
14
+ const s = createServer();
15
+ await new Promise((ok) => s.listen(0, "127.0.0.1", ok));
16
+ const { port } = s.address();
17
+ await new Promise((ok) => s.close(() => ok()));
18
+ return port;
19
+ }
20
+ test("server drains and exits 0 on SIGTERM", { timeout: 120_000 }, async () => {
21
+ const port = await freePort();
22
+ const work = mkdtempSync(join(tmpdir(), "omcp-shutdown-"));
23
+ let log = "";
24
+ const server = spawn(process.execPath, [join(ROOT, "node_modules/tsx/dist/cli.mjs"), join(ROOT, "src/index.ts")], {
25
+ cwd: ROOT,
26
+ env: { ...process.env, PORT: String(port), CONFIG_PATH: join(work, "sources.yaml") },
27
+ stdio: ["ignore", "pipe", "pipe"],
28
+ // Own process group: tsx runs the server as a child, so a cleanup
29
+ // kill must reach the whole group, not just the tsx wrapper.
30
+ detached: true,
31
+ });
32
+ server.stdout.on("data", (d) => (log += d));
33
+ server.stderr.on("data", (d) => (log += d));
34
+ const exited = new Promise((ok) => server.once("exit", (code) => ok(code)));
35
+ try {
36
+ const deadline = Date.now() + 90_000;
37
+ for (;;) {
38
+ const r = await fetch(`http://127.0.0.1:${port}/readyz`).catch(() => undefined);
39
+ if (r?.ok)
40
+ break;
41
+ if (Date.now() > deadline)
42
+ assert.fail(`server never became ready\n--- log ---\n${log}`);
43
+ await new Promise((r) => setTimeout(r, 250));
44
+ }
45
+ const t0 = Date.now();
46
+ server.kill("SIGTERM");
47
+ const code = await Promise.race([
48
+ exited,
49
+ new Promise((ok) => setTimeout(() => ok("hung"), 20_000).unref()),
50
+ ]);
51
+ assert.notEqual(code, "hung", `still running 20s after SIGTERM\n--- log ---\n${log}`);
52
+ assert.equal(code, 0, log);
53
+ assert.match(log, /SIGTERM received; shutting down/);
54
+ assert.ok(Date.now() - t0 < 15_000);
55
+ }
56
+ finally {
57
+ if (server.exitCode === null && server.signalCode === null) {
58
+ try {
59
+ process.kill(-server.pid, "SIGKILL");
60
+ }
61
+ catch { /* already gone */ }
62
+ }
63
+ rmSync(work, { recursive: true, force: true });
64
+ }
65
+ });
66
+ test("stdio mode flushes and exits 0 on SIGTERM too", { timeout: 120_000 }, async () => {
67
+ const work = mkdtempSync(join(tmpdir(), "omcp-shutdown-stdio-"));
68
+ let log = "";
69
+ const server = spawn(process.execPath, [join(ROOT, "node_modules/tsx/dist/cli.mjs"), join(ROOT, "src/index.ts")], {
70
+ cwd: ROOT,
71
+ env: { ...process.env, MCP_TRANSPORT: "stdio", CONFIG_PATH: join(work, "sources.yaml") },
72
+ // stdin stays open: a closed stdin would end the session on its own.
73
+ stdio: ["pipe", "pipe", "pipe"],
74
+ detached: true,
75
+ });
76
+ server.stdout.on("data", (d) => (log += d));
77
+ server.stderr.on("data", (d) => (log += d));
78
+ const exited = new Promise((ok) => server.once("exit", (code) => ok(code)));
79
+ try {
80
+ const deadline = Date.now() + 90_000;
81
+ while (!/running on stdio transport/.test(log)) {
82
+ if (Date.now() > deadline)
83
+ assert.fail(`stdio server never started\n--- log ---\n${log}`);
84
+ await new Promise((r) => setTimeout(r, 250));
85
+ }
86
+ server.kill("SIGTERM");
87
+ const code = await Promise.race([
88
+ exited,
89
+ new Promise((ok) => setTimeout(() => ok("hung"), 20_000).unref()),
90
+ ]);
91
+ assert.notEqual(code, "hung", `still running 20s after SIGTERM\n--- log ---\n${log}`);
92
+ assert.equal(code, 0, log);
93
+ assert.match(log, /SIGTERM received; shutting down \([1-9]\d* hook/);
94
+ }
95
+ finally {
96
+ if (server.exitCode === null && server.signalCode === null) {
97
+ try {
98
+ process.kill(-server.pid, "SIGKILL");
99
+ }
100
+ catch { /* already gone */ }
101
+ }
102
+ rmSync(work, { recursive: true, force: true });
103
+ }
104
+ });
@@ -0,0 +1,22 @@
1
+ export interface ShutdownDeps {
2
+ exit: (code: number) => void;
3
+ log: (msg: string) => void;
4
+ signals: Pick<NodeJS.Process, "once">;
5
+ }
6
+ /** Register work to run before the process exits (flush buffers, close clients). */
7
+ export declare function onShutdown(name: string, fn: () => unknown): void;
8
+ export declare function isShuttingDown(): boolean;
9
+ /** Runs all hooks concurrently; resolves when they settle or the timeout hits. */
10
+ export declare function runShutdownHooks(timeoutMs: number, log: (msg: string) => void): Promise<void>;
11
+ export declare function installShutdown(opts?: {
12
+ server?: {
13
+ close(cb?: (err?: Error) => void): unknown;
14
+ closeIdleConnections?(): void;
15
+ closeAllConnections?(): void;
16
+ };
17
+ timeoutMs?: number;
18
+ drainMs?: number;
19
+ deps?: Partial<ShutdownDeps>;
20
+ }): void;
21
+ /** Test-only. */
22
+ export declare function _resetShutdownForTests(): void;
@@ -0,0 +1,85 @@
1
+ // Graceful shutdown. Components register a flush hook instead of their own
2
+ // process.on("SIGTERM") — any SIGTERM listener disables Node's default
3
+ // exit, and none of the old per-component handlers ever exited, so the
4
+ // server ignored SIGTERM and was SIGKILLed by Kubernetes/Docker after the
5
+ // grace period, sometimes mid-flush.
6
+ //
7
+ // On the first SIGTERM/SIGINT: flip readiness, stop accepting connections,
8
+ // drain in-flight requests briefly, run every hook in parallel (bounded by
9
+ // a timeout), exit 0. A second signal exits 1 immediately.
10
+ const hooks = [];
11
+ let installed = false;
12
+ let shuttingDown = false;
13
+ /** Register work to run before the process exits (flush buffers, close clients). */
14
+ export function onShutdown(name, fn) {
15
+ hooks.push({ name, fn });
16
+ }
17
+ export function isShuttingDown() {
18
+ return shuttingDown;
19
+ }
20
+ /** Runs all hooks concurrently; resolves when they settle or the timeout hits. */
21
+ export async function runShutdownHooks(timeoutMs, log) {
22
+ const settled = Promise.allSettled(hooks.map(async (h) => {
23
+ try {
24
+ await h.fn();
25
+ }
26
+ catch (err) {
27
+ log(`shutdown hook "${h.name}" failed: ${err instanceof Error ? err.message : String(err)}`);
28
+ }
29
+ }));
30
+ let timer;
31
+ const timedOut = new Promise((ok) => {
32
+ timer = setTimeout(() => ok("timeout"), timeoutMs);
33
+ timer.unref();
34
+ });
35
+ const outcome = await Promise.race([settled, timedOut]);
36
+ clearTimeout(timer);
37
+ if (outcome === "timeout")
38
+ log(`shutdown hooks did not finish within ${timeoutMs}ms; exiting anyway`);
39
+ }
40
+ export function installShutdown(opts = {}) {
41
+ if (installed)
42
+ return;
43
+ installed = true;
44
+ const exit = opts.deps?.exit ?? ((code) => process.exit(code));
45
+ const log = opts.deps?.log ?? ((msg) => console.log(msg));
46
+ const signals = opts.deps?.signals ?? process;
47
+ const timeoutMs = opts.timeoutMs ?? 10_000;
48
+ const drainMs = opts.drainMs ?? 3_000;
49
+ const handle = (sig) => {
50
+ if (shuttingDown) {
51
+ log(`${sig} received again; exiting now`);
52
+ exit(1);
53
+ return;
54
+ }
55
+ shuttingDown = true;
56
+ log(`${sig} received; shutting down (${hooks.length} hook(s), timeout ${timeoutMs}ms)`);
57
+ // A second signal must still be able to force the exit.
58
+ signals.once(sig, () => handle(sig));
59
+ void (async () => {
60
+ // Stop accepting first; the drain below lets in-flight requests finish.
61
+ const server = opts.server;
62
+ const closed = server
63
+ ? new Promise((ok) => {
64
+ server.close(() => ok());
65
+ server.closeIdleConnections?.();
66
+ })
67
+ : Promise.resolve();
68
+ // Let in-flight requests finish (and write their audit entries)
69
+ // before flushing; long-lived streams (SSE, WebSocket) would hold
70
+ // close() open indefinitely, hence the bound.
71
+ await Promise.race([closed, new Promise((ok) => setTimeout(ok, drainMs).unref())]);
72
+ server?.closeAllConnections?.();
73
+ await runShutdownHooks(timeoutMs, log);
74
+ exit(0);
75
+ })();
76
+ };
77
+ for (const sig of ["SIGTERM", "SIGINT"])
78
+ signals.once(sig, () => handle(sig));
79
+ }
80
+ /** Test-only. */
81
+ export function _resetShutdownForTests() {
82
+ hooks.length = 0;
83
+ installed = false;
84
+ shuttingDown = false;
85
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,68 @@
1
+ import { test, beforeEach } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { EventEmitter } from "node:events";
4
+ import { installShutdown, onShutdown, isShuttingDown, _resetShutdownForTests } from "./shutdown.js";
5
+ beforeEach(() => _resetShutdownForTests());
6
+ function harness() {
7
+ const signals = new EventEmitter();
8
+ const events = [];
9
+ let resolveExit;
10
+ const exited = new Promise((ok) => (resolveExit = ok));
11
+ const server = {
12
+ close(cb) { events.push("server.close"); setTimeout(() => cb?.(), 5); },
13
+ closeIdleConnections() { events.push("closeIdle"); },
14
+ closeAllConnections() { events.push("closeAll"); },
15
+ };
16
+ const deps = {
17
+ exit: (code) => { events.push(`exit ${code}`); resolveExit(code); },
18
+ log: (msg) => events.push(`log ${msg}`),
19
+ signals: signals,
20
+ };
21
+ return { signals, events, exited, server, deps };
22
+ }
23
+ test("SIGTERM stops accepting, drains, runs every hook, then exits 0", async () => {
24
+ const h = harness();
25
+ const ran = [];
26
+ onShutdown("a", async () => { await new Promise((r) => setTimeout(r, 10)); ran.push("a"); h.events.push("hook a"); });
27
+ onShutdown("b", () => { ran.push("b"); h.events.push("hook b"); });
28
+ installShutdown({ server: h.server, deps: h.deps, drainMs: 50 });
29
+ assert.equal(isShuttingDown(), false);
30
+ h.signals.emit("SIGTERM");
31
+ assert.equal(isShuttingDown(), true);
32
+ assert.equal(await h.exited, 0);
33
+ assert.deepEqual(ran.sort(), ["a", "b"]);
34
+ const order = h.events.filter((e) => !e.startsWith("log"));
35
+ assert.deepEqual(order, ["server.close", "closeIdle", "closeAll", "hook b", "hook a", "exit 0"]);
36
+ });
37
+ test("a failing hook is logged and does not block the others or the exit", async () => {
38
+ const h = harness();
39
+ let other = false;
40
+ onShutdown("broken", () => { throw new Error("boom"); });
41
+ onShutdown("fine", () => { other = true; });
42
+ installShutdown({ deps: h.deps });
43
+ h.signals.emit("SIGINT");
44
+ assert.equal(await h.exited, 0);
45
+ assert.ok(other);
46
+ assert.ok(h.events.some((e) => e.includes('"broken" failed: boom')));
47
+ });
48
+ test("a hung hook can't keep the process alive past the timeout", async () => {
49
+ const h = harness();
50
+ // A hook stuck on a live handle (socket, timer) — the realistic hang.
51
+ let stuck;
52
+ onShutdown("hangs", () => new Promise((r) => { stuck = setTimeout(r, 60_000); }));
53
+ installShutdown({ deps: h.deps, timeoutMs: 50 });
54
+ h.signals.emit("SIGTERM");
55
+ assert.equal(await h.exited, 0);
56
+ clearTimeout(stuck);
57
+ assert.ok(h.events.some((e) => e.includes("did not finish within 50ms")));
58
+ });
59
+ test("a second signal forces exit 1", async () => {
60
+ const h = harness();
61
+ let slow;
62
+ onShutdown("slow", () => new Promise((r) => { slow = setTimeout(r, 60_000); }));
63
+ installShutdown({ deps: h.deps, timeoutMs: 5000 });
64
+ h.signals.emit("SIGTERM");
65
+ h.signals.emit("SIGTERM");
66
+ assert.equal(await h.exited, 1);
67
+ clearTimeout(slow);
68
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thotischner/observability-mcp",
3
- "version": "3.9.15",
3
+ "version": "3.9.17",
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",
@@ -38,6 +38,9 @@
38
38
  "type": "github",
39
39
  "url": "https://github.com/sponsors/ThoTischner"
40
40
  },
41
+ "engines": {
42
+ "node": ">=22.15.0"
43
+ },
41
44
  "bin": {
42
45
  "observability-mcp": "./dist/index.js",
43
46
  "omcp": "./dist/cli/index.js"
@@ -61,19 +64,19 @@
61
64
  "dependencies": {
62
65
  "@kubernetes/client-node": "^1.4.0",
63
66
  "@modelcontextprotocol/sdk": "^1.32.0",
64
- "@opentelemetry/api": "^1.9.0",
65
- "@opentelemetry/auto-instrumentations-node": "^0.81.0",
66
- "@opentelemetry/exporter-trace-otlp-http": "^0.223.0",
67
- "@opentelemetry/resources": "^2.2.0",
68
- "@opentelemetry/sdk-node": "^0.223.0",
69
- "@opentelemetry/semantic-conventions": "^1.40.0",
67
+ "@opentelemetry/api": "^1.10.0",
68
+ "@opentelemetry/auto-instrumentations-node": "^0.82.0",
69
+ "@opentelemetry/exporter-trace-otlp-http": "^0.300.0",
70
+ "@opentelemetry/resources": "^3.0.0",
71
+ "@opentelemetry/sdk-node": "^0.300.0",
72
+ "@opentelemetry/semantic-conventions": "^1.43.0",
70
73
  "express": "^5.2.1",
71
74
  "express-rate-limit": "^8.5.2",
72
75
  "js-yaml": "^4.3.2",
73
76
  "prom-client": "^15.1.0",
74
77
  "redis": "^4.7.0",
75
78
  "ws": "^8.18.0",
76
- "zod": "^4.4.3"
79
+ "zod": "^4.6.6"
77
80
  },
78
81
  "devDependencies": {
79
82
  "@types/express": "^5.0.0",
@@ -82,7 +85,7 @@
82
85
  "@types/ws": "^8.5.13",
83
86
  "openapi-types": "^12.1.3",
84
87
  "tsx": "^4.22.0",
85
- "typescript": "^6.0.3"
88
+ "typescript": "^7.0.2"
86
89
  },
87
90
  "overrides": {
88
91
  "fast-uri": "^3.1.9",
@@ -98,6 +101,6 @@
98
101
  "form-data": "^4.0.6",
99
102
  "protobufjs": "^7.6.4",
100
103
  "@grpc/grpc-js": "^1.14.5",
101
- "@opentelemetry/core": "^2.8.0"
104
+ "@opentelemetry/core": "^3.0.0"
102
105
  }
103
106
  }