Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(mcp-host): bound idle status heartbeat memory

Alfredo Lopez742735f6db8b
diff --git a/mcp-host/src/__tests__/config.mcpStatusHeartbeat.test.ts b/mcp-host/src/__tests__/config.mcpStatusHeartbeat.test.ts
new file mode 100644
index 000000000..6b897cd8b
--- /dev/null
+++ b/mcp-host/src/__tests__/config.mcpStatusHeartbeat.test.ts
@@ -0,0 +1,29 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { parseMcpStatusHeartbeatDuration } from '../config'
+
+describe('MCP status heartbeat configuration', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs()
+ })
+
+ it('uses documented defaults for unset or blank values', () => {
+ expect(
+ parseMcpStatusHeartbeatDuration('CLERUM_MCP_STATUS_HEARTBEAT_INTERVAL', undefined, 30_000)
+ ).toBe(30_000)
+ expect(
+ parseMcpStatusHeartbeatDuration('CLERUM_MCP_STATUS_HEARTBEAT_TIMEOUT_MS', ' ', 25_000)
+ ).toBe(25_000)
+ })
+
+ it.each(['0', '-1', '1.5', '30ms', '9007199254740992'])('rejects %s', raw => {
+ expect(() =>
+ parseMcpStatusHeartbeatDuration('CLERUM_MCP_STATUS_HEARTBEAT_INTERVAL', raw, 30_000)
+ ).toThrow("CLERUM_MCP_STATUS_HEARTBEAT_INTERVAL='" + raw + "' is not a positive safe integer")
+ })
+
+ it('accepts an explicit positive safe integer', () => {
+ expect(
+ parseMcpStatusHeartbeatDuration('CLERUM_MCP_STATUS_HEARTBEAT_TIMEOUT_MS', '25000', 25_000)
+ ).toBe(25_000)
+ })
+})
diff --git a/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts b/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts
index c474903d1..20d3ab8ef 100644
--- a/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts
+++ b/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts
@@ -9,6 +9,8 @@ const sdkState = vi.hoisted(() => ({
callToolQueue: [] as Array<() => unknown>,
listToolsCalls: [] as unknown[][],
listToolsQueue: [] as Array<() => unknown>,
+ requestCalls: [] as unknown[][],
+ requestQueue: [] as Array<() => unknown>,
}))
vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
@@ -30,6 +32,13 @@ vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
return { tools: [] }
}
+ async request(...args: unknown[]) {
+ sdkState.requestCalls.push(args)
+ const next = sdkState.requestQueue.shift()
+ if (next) return next()
+ return { tools: [] }
+ }
+
async callTool(...args: unknown[]) {
sdkState.callToolCalls.push(args)
const next = sdkState.callToolQueue.shift()
@@ -70,6 +79,8 @@ describe('McpClient SDK request timeouts', () => {
sdkState.callToolQueue.length = 0
sdkState.listToolsCalls.length = 0
sdkState.listToolsQueue.length = 0
+ sdkState.requestCalls.length = 0
+ sdkState.requestQueue.length = 0
})
afterEach(() => {
@@ -157,7 +168,7 @@ describe('McpClient SDK request timeouts', () => {
expect(requestOptions.maxTotalTimeout).toBe(requestOptions.timeout)
})
- it('passes explicit timeout options to SDK listTools calls', async () => {
+ it('uses a raw validated SDK request for status probes without calling listTools', async () => {
const controller = new AbortController()
const c = client()
@@ -172,14 +183,16 @@ describe('McpClient SDK request timeouts', () => {
signal: controller.signal,
}),
])
- expect(sdkState.listToolsCalls[1]).toEqual([
- undefined,
+ expect(sdkState.requestCalls[0]).toEqual([
+ { method: 'tools/list', params: undefined },
+ expect.anything(),
expect.objectContaining({
timeout: 3_000,
maxTotalTimeout: 3_000,
signal: controller.signal,
}),
])
+ expect(sdkState.listToolsCalls).toHaveLength(1)
})
it('fails connect when SDK tool discovery fails', async () => {
diff --git a/mcp-host/src/__tests__/mcp/mcpManager.status.test.ts b/mcp-host/src/__tests__/mcp/mcpManager.status.test.ts
new file mode 100644
index 000000000..4eced747e
--- /dev/null
+++ b/mcp-host/src/__tests__/mcp/mcpManager.status.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it, vi } from 'vitest'
+import { McpManager } from '../../mcp/manager'
+import { ServerStatusTracker, classifyConnectError } from '../../mcp/serverStatus'
+
+type ProbeClient = {
+ probeTools: ReturnType<typeof vi.fn>
+}
+
+function connectedManager(clients: Record<string, ProbeClient>): {
+ manager: McpManager
+ tracker: ServerStatusTracker
+} {
+ const tracker = new ServerStatusTracker(() => new Date('2026-07-23T10:00:00.000Z'))
+ const manager = new McpManager(undefined, tracker)
+ const internalClients = (manager as unknown as { clients: Map<string, ProbeClient> }).clients
+ for (const [name, client] of Object.entries(clients)) {
+ internalClients.set(name, client)
+ tracker.markConnecting(name)
+ tracker.markConnected(name, 1)
+ }
+ return { manager, tracker }
+}
+
+describe('McpManager status refresh', () => {
+ it('aggregates raw-probe metadata and gives every client a distinct derived signal', async () => {
+ const first = {
+ probeTools: vi.fn().mockResolvedValue({ ok: true, toolCount: 2, outputSchemaCount: 1 }),
+ }
+ const second = {
+ probeTools: vi
+ .fn()
+ .mockResolvedValue({ ok: false, error: new Error('upstream unavailable') }),
+ }
+ const { manager, tracker } = connectedManager({ first, second })
+ const controller = new AbortController()
+
+ await expect(
+ manager.refreshAllServerStatus({ timeoutMs: 1234, signal: controller.signal })
+ ).resolves.toEqual({
+ serverCount: 2,
+ succeeded: 1,
+ failed: 1,
+ toolCount: 2,
+ outputSchemaCount: 1,
+ aborted: false,
+ })
+
+ const firstSignal = first.probeTools.mock.calls[0]?.[0].signal as AbortSignal
+ const secondSignal = second.probeTools.mock.calls[0]?.[0].signal as AbortSignal
+ expect(firstSignal).not.toBe(controller.signal)
+ expect(secondSignal).not.toBe(controller.signal)
+ expect(firstSignal).not.toBe(secondSignal)
+ expect(tracker.get('first')?.toolCount).toBe(2)
+ expect(tracker.get('second')?.reason).toBe('unknown')
+ })
+
+ it('does not invoke probes or mutate status for an already aborted round', async () => {
+ const client = { probeTools: vi.fn() }
+ const { manager, tracker } = connectedManager({ one: client })
+ const before = tracker.get('one')
+ const controller = new AbortController()
+ controller.abort('shutdown')
+
+ await expect(
+ manager.refreshAllServerStatus({ signal: controller.signal })
+ ).resolves.toMatchObject({
+ serverCount: 1,
+ aborted: true,
+ })
+ expect(client.probeTools).not.toHaveBeenCalled()
+ expect(tracker.get('one')).toEqual(before)
+ })
+})
+
+describe('MCP status error classification', () => {
+ it('classifies JSON-RPC timeout and Zod response-shape failures deterministically', () => {
+ expect(
+ classifyConnectError({ code: -32001, message: 'request exceeded deadline' })
+ ).toMatchObject({
+ reason: 'timeout',
+ })
+ expect(
+ classifyConnectError({
+ name: '$ZodError',
+ issues: [{ path: ['tools', 0], message: 'invalid' }],
+ message: 'response parse error',
+ })
+ ).toEqual({ reason: 'handshake', message: 'invalid MCP response schema' })
+ })
+})
diff --git a/mcp-host/src/__tests__/mcp/mcpSdkMetadata.contract.test.ts b/mcp-host/src/__tests__/mcp/mcpSdkMetadata.contract.test.ts
new file mode 100644
index 000000000..aa59a9104
--- /dev/null
+++ b/mcp-host/src/__tests__/mcp/mcpSdkMetadata.contract.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from 'vitest'
+import { Client } from '@modelcontextprotocol/sdk/client/index.js'
+import { Server } from '@modelcontextprotocol/sdk/server/index.js'
+import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'
+import { ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'
+import { McpClient } from '../../mcp/client'
+
+class MemoryTransport implements Transport {
+ peer: MemoryTransport | undefined
+ onclose: (() => void) | undefined
+ onerror: ((error: Error) => void) | undefined
+ onmessage: Transport['onmessage'] | undefined
+
+ async start(): Promise<void> {}
+
+ async send(message: Parameters<NonNullable<Transport['onmessage']>>[0]): Promise<void> {
+ queueMicrotask(() => this.peer?.onmessage?.(message))
+ }
+
+ async close(): Promise<void> {
+ this.onclose?.()
+ }
+}
+
+type MetadataClient = {
+ getToolOutputValidator(name: string): unknown
+ isToolTaskRequired(name: string): boolean
+}
+
+type ToolResponse = {
+ name: string
+ description: string
+ inputSchema: { type: 'object'; properties?: Record<string, object> }
+ outputSchema?: { type: 'object'; properties?: Record<string, object> }
+ execution?: { taskSupport: 'required' | 'optional' | 'forbidden' }
+}
+
+function transportPair(): [MemoryTransport, MemoryTransport] {
+ const client = new MemoryTransport()
+ const server = new MemoryTransport()
+ client.peer = server
+ server.peer = client
+ return [client, server]
+}
+
+describe('MCP SDK metadata ownership contract', () => {
+ it('keeps status probes raw while explicit listTools owns metadata validation and cache updates', async () => {
+ let tools: ToolResponse[] = [
+ {
+ name: 'validated-tool',
+ description: 'valid schema',
+ inputSchema: { type: 'object' },
+ outputSchema: { type: 'object', properties: { value: { type: 'string' } } },
+ execution: { taskSupport: 'required' as const },
+ },
+ ]
+ const [clientTransport, serverTransport] = transportPair()
+ const server = new Server(
+ { name: 'metadata-contract-server', version: '1.0.0' },
+ { capabilities: { tools: {} } }
+ )
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }))
+ const sdkClient = new Client(
+ { name: 'metadata-contract-client', version: '1.0.0' },
+ { capabilities: {} }
+ )
+
+ await Promise.all([server.connect(serverTransport), sdkClient.connect(clientTransport)])
+ await sdkClient.listTools()
+ const metadataClient = sdkClient as unknown as MetadataClient
+ const originalValidator = metadataClient.getToolOutputValidator('validated-tool')
+ expect(originalValidator).toBeDefined()
+ expect(metadataClient.isToolTaskRequired('validated-tool')).toBe(true)
+
+ tools = [
+ {
+ name: 'broken-schema-tool',
+ description: 'an unresolved JSON Schema reference for AJV validation',
+ inputSchema: { type: 'object' },
+ outputSchema: {
+ type: 'object',
+ properties: { value: { $ref: 'urn:clerum:missing-schema' } },
+ },
+ },
+ ]
+
+ const wrapper = new McpClient({
+ name: 'metadata-contract',
+ contextRef: 'ctx',
+ transport: { type: 'streamableHttp', url: 'http://metadata-contract/mcp' },
+ enabled: true,
+ status: { deployed: true, ready: true },
+ })
+ ;(wrapper as unknown as { client: Client; connected: boolean }).client = sdkClient
+ ;(wrapper as unknown as { client: Client; connected: boolean }).connected = true
+
+ await expect(wrapper.probeTools()).resolves.toEqual({
+ ok: true,
+ toolCount: 1,
+ outputSchemaCount: 1,
+ })
+ expect(metadataClient.getToolOutputValidator('validated-tool')).toBe(originalValidator)
+ expect(metadataClient.getToolOutputValidator('broken-schema-tool')).toBeUndefined()
+ await expect(sdkClient.listTools()).rejects.toThrow()
+
+ await Promise.all([sdkClient.close(), server.close()])
+ })
+})
diff --git a/mcp-host/src/__tests__/mcp/statusHeartbeat.test.ts b/mcp-host/src/__tests__/mcp/statusHeartbeat.test.ts
new file mode 100644
index 000000000..90eba8774
--- /dev/null
+++ b/mcp-host/src/__tests__/mcp/statusHeartbeat.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { McpStatusRefreshSummary } from '../../mcp/manager'
+import { McpStatusHeartbeat } from '../../mcp/statusHeartbeat'
+
+function metrics() {
+ return {
+ runStarted: vi.fn<() => void>(),
+ runSkipped: vi.fn<() => void>(),
+ runFinished: vi.fn<(summary: McpStatusRefreshSummary) => void>(),
+ }
+}
+
+const summary = {
+ serverCount: 1,
+ succeeded: 1,
+ failed: 0,
+ toolCount: 2,
+ outputSchemaCount: 1,
+ aborted: false,
+}
+
+describe('McpStatusHeartbeat', () => {
+ it('defers its first tick and passes a bounded round signal to the current refresher', async () => {
+ vi.useFakeTimers()
+ const refreshAllServerStatus = vi
+ .fn<(options: { timeoutMs?: number; signal?: AbortSignal }) => Promise<typeof summary>>()
+ .mockResolvedValue(summary)
+ const observedMetrics = metrics()
+ const heartbeat = new McpStatusHeartbeat({
+ intervalMs: 30_000,
+ timeoutMs: 25_000,
+ getRefresher: () => ({ refreshAllServerStatus }),
+ metrics: observedMetrics,
+ })
+
+ heartbeat.start()
+ expect(refreshAllServerStatus).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(refreshAllServerStatus).toHaveBeenCalledWith({
+ timeoutMs: 25_000,
+ signal: expect.any(AbortSignal),
+ })
+ expect(observedMetrics.runStarted).toHaveBeenCalledTimes(1)
+ expect(observedMetrics.runFinished).toHaveBeenCalledWith(summary)
+ heartbeat.stop()
+ vi.useRealTimers()
+ })
+
+ it('never overlaps rounds, aborts the active round on idempotent stop, and leaves transports untouched', async () => {
+ vi.useFakeTimers()
+ let release: (() => void) | undefined
+ const refreshAllServerStatus = vi.fn<
+ (options: { timeoutMs?: number; signal?: AbortSignal }) => Promise<typeof summary>
+ >(() => new Promise<typeof summary>(resolve => (release = () => resolve(summary))))
+ const observedMetrics = metrics()
+ const heartbeat = new McpStatusHeartbeat({
+ intervalMs: 10,
+ timeoutMs: 100,
+ getRefresher: () => ({ refreshAllServerStatus }),
+ metrics: observedMetrics,
+ })
+
+ heartbeat.start()
+ await vi.advanceTimersByTimeAsync(0)
+ const signal = refreshAllServerStatus.mock.calls[0]?.[0].signal as AbortSignal
+ await vi.advanceTimersByTimeAsync(40)
+ expect(refreshAllServerStatus).toHaveBeenCalledTimes(1)
+ expect(observedMetrics.runSkipped).toHaveBeenCalled()
+
+ heartbeat.stop()
+ heartbeat.stop()
+ expect(signal.aborted).toBe(true)
+ release?.()
+ await vi.runAllTimersAsync()
+ expect(refreshAllServerStatus).toHaveBeenCalledTimes(1)
+ vi.useRealTimers()
+ })
+})
diff --git a/mcp-host/src/__tests__/mcp/statusHeartbeatMetrics.test.ts b/mcp-host/src/__tests__/mcp/statusHeartbeatMetrics.test.ts
new file mode 100644
index 000000000..92da3a371
--- /dev/null
+++ b/mcp-host/src/__tests__/mcp/statusHeartbeatMetrics.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+import { Registry } from 'prom-client'
+import { McpStatusHeartbeatMetrics } from '../../mcp/statusHeartbeatMetrics'
+
+describe('MCP status heartbeat metrics', () => {
+ it('registers all heartbeat metrics and records a completed aggregate round', async () => {
+ const registry = new Registry()
+ const metrics = new McpStatusHeartbeatMetrics(registry)
+ metrics.runStarted()
+ metrics.runFinished({
+ serverCount: 2,
+ succeeded: 1,
+ failed: 1,
+ toolCount: 3,
+ outputSchemaCount: 2,
+ aborted: false,
+ })
+
+ const scrape = await registry.metrics()
+ expect(scrape).toContain('clerum_mcp_status_heartbeat_runs_total{outcome="failed"} 1')
+ expect(scrape).toContain('clerum_mcp_status_heartbeat_in_flight 0')
+ expect(scrape).toContain('clerum_mcp_status_heartbeat_probes_total{outcome="succeeded"} 1')
+ expect(scrape).toContain('clerum_mcp_status_heartbeat_servers{outcome="expected"} 2')
+ expect(scrape).toContain('clerum_mcp_status_heartbeat_tools 3')
+ expect(scrape).toContain('clerum_mcp_status_heartbeat_output_schemas 2')
+ })
+})
diff --git a/mcp-host/src/__tests__/processMetrics.test.ts b/mcp-host/src/__tests__/processMetrics.test.ts
new file mode 100644
index 000000000..66c48b5cc
--- /dev/null
+++ b/mcp-host/src/__tests__/processMetrics.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest'
+import { Registry } from 'prom-client'
+import { registerProcessMetrics } from '../observability/processMetrics'
+
+describe('process metrics registration', () => {
+ it('registers the default process metric set once per injected registry', async () => {
+ const registry = new Registry()
+ registerProcessMetrics(registry)
+ registerProcessMetrics(registry)
+
+ expect(registry.getSingleMetric('process_cpu_user_seconds_total')).toBeDefined()
+ const scrape = await registry.metrics()
+ expect(scrape.match(/# HELP process_cpu_user_seconds_total/g)).toHaveLength(1)
+ })
+})
diff --git a/mcp-host/src/__tests__/server.metrics.contract.test.ts b/mcp-host/src/__tests__/server.metrics.contract.test.ts
new file mode 100644
index 000000000..b67bcc05c
--- /dev/null
+++ b/mcp-host/src/__tests__/server.metrics.contract.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest'
+import type { AddressInfo } from 'node:net'
+import { RPCServer } from '../server'
+
+describe('RPCServer metrics contract', () => {
+ it('exposes process and MCP status-heartbeat metrics without runtime auth', async () => {
+ const server = new RPCServer(0)
+ await server.start()
+ const address = (server as unknown as { server: { address(): AddressInfo } }).server.address()
+
+ try {
+ const response = await fetch(`http://127.0.0.1:${address.port}/metrics`)
+ expect(response.status).toBe(200)
+ const body = await response.text()
+ expect(body).toContain('process_cpu_user_seconds_total')
+ expect(body).toContain('clerum_mcp_status_heartbeat_runs_total')
+ expect(body).toContain('clerum_mcp_status_heartbeat_in_flight')
+ } finally {
+ await server.stop()
+ }
+ })
+})
diff --git a/mcp-host/src/config.ts b/mcp-host/src/config.ts
index cb4f825f1..cd8ec4b8d 100644
--- a/mcp-host/src/config.ts
+++ b/mcp-host/src/config.ts
@@ -51,6 +51,10 @@ export interface Config {
// silent failures. Must stay well under the desktop's 120s stale threshold.
mcpStatusHeartbeatInterval: number
+ // Per-heartbeat round budget. A stalled MCP server must not retain the
+ // scheduler in-flight forever or cause overlapping rounds.
+ mcpStatusHeartbeatTimeoutMs: number
+
// Agent configuration
agentTaskDelay: number
agentMaxTaskDuration: number
@@ -277,6 +281,27 @@ export function parseStatelessHeartbeatIntervalMs(raw: string | undefined): numb
return parsed
}
+/**
+ * Parse an MCP status-heartbeat duration. These values participate in the
+ * liveness scheduler, so an explicit typo must fail at boot rather than turn
+ * into an unbounded timer or a silent fallback.
+ */
+export function parseMcpStatusHeartbeatDuration(
+ name: string,
+ raw: string | undefined,
+ defaultValue: number
+): number {
+ if (raw === undefined || raw.trim() === '') return defaultValue
+ if (!/^\d+$/.test(raw)) {
+ throw new Error(`[Config] ${name}='${raw}' is not a positive safe integer`)
+ }
+ const value = Number(raw)
+ if (!Number.isSafeInteger(value) || value <= 0) {
+ throw new Error(`[Config] ${name}='${raw}' is not a positive safe integer`)
+ }
+ return value
+}
+
/**
* Parse CLERUM_HOST_CONFIG JSON for dev mode.
*/
@@ -480,9 +505,15 @@ export const config: Config = {
// MCP status heartbeat. Defaults to 30 seconds so a single missed tick does
// not trip desktop staleness.
- mcpStatusHeartbeatInterval: parseInt(
- getEnv('CLERUM_MCP_STATUS_HEARTBEAT_INTERVAL', '30000')!,
- 10
+ mcpStatusHeartbeatInterval: parseMcpStatusHeartbeatDuration(
+ 'CLERUM_MCP_STATUS_HEARTBEAT_INTERVAL',
+ getEnv('CLERUM_MCP_STATUS_HEARTBEAT_INTERVAL'),
+ 30_000
+ ),
+ mcpStatusHeartbeatTimeoutMs: parseMcpStatusHeartbeatDuration(
+ 'CLERUM_MCP_STATUS_HEARTBEAT_TIMEOUT_MS',
+ getEnv('CLERUM_MCP_STATUS_HEARTBEAT_TIMEOUT_MS'),
+ 25_000
),
// Agent configuration
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index 6556f52fd..fc7b8c0ae 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -65,6 +65,7 @@ import { clerumPromptCacheInvalidationsTotal } from './llm/promptCacheMetrics'
import { ALL_PROVIDERS, type LlmProvider, descriptorFor, isLlmProvider } from './llm/registryCore'
import './logger'
import { McpManager } from './mcp'
+import { McpStatusHeartbeat } from './mcp/statusHeartbeat'
import { startMcpInitializationInBackground } from './mcpBackgroundInit'
import { IncomingMessageHandler, PendingTaskEntry } from './messageHandler'
import { maybeCreatePluginWorkloadSdkServer } from './pluginWorkloadSdk/server'
@@ -154,7 +155,7 @@ let failoverEngine: FailoverEngine | null = null
let bootFallbackEntry: FallbackEntry | null = null
let hostWatcher: HostWatcher | null = null
let contextMapperPollTimer: ReturnType<typeof setInterval> | null = null
-let mcpStatusHeartbeatTimer: ReturnType<typeof setInterval> | null = null
+let mcpStatusHeartbeat: McpStatusHeartbeat | null = null
let lastServerState: Map<string, string> = new Map()
let rpcServer: RPCServer | null = null
let mcpManager: McpManager | null = null
@@ -878,22 +879,28 @@ function stopContextMapperPolling(): void {
* the connection (spec §4.5, §7.1).
*/
function startMcpStatusHeartbeat(): void {
- if (mcpStatusHeartbeatTimer) return
+ if (mcpStatusHeartbeat) return
const interval = config.mcpStatusHeartbeatInterval
- console.log(`[Main] Starting MCP status heartbeat (interval: ${interval}ms)`)
- mcpStatusHeartbeatTimer = setInterval(() => {
- if (!mcpManager) return
- mcpManager.refreshAllServerStatus().catch((err: unknown) => {
+ const timeoutMs = config.mcpStatusHeartbeatTimeoutMs
+ console.log(
+ `[Main] Starting MCP status heartbeat (interval: ${interval}ms, timeout: ${timeoutMs}ms)`
+ )
+ mcpStatusHeartbeat = new McpStatusHeartbeat({
+ intervalMs: interval,
+ timeoutMs,
+ getRefresher: () => mcpManager,
+ onError: (err: unknown) => {
console.error('[Main] MCP status heartbeat failed:', err)
- })
- }, interval)
+ },
+ })
+ mcpStatusHeartbeat.start()
}
function stopMcpStatusHeartbeat(): void {
- if (mcpStatusHeartbeatTimer) {
+ if (mcpStatusHeartbeat) {
console.log('[Main] Stopping MCP status heartbeat')
- clearInterval(mcpStatusHeartbeatTimer)
- mcpStatusHeartbeatTimer = null
+ mcpStatusHeartbeat.stop()
+ mcpStatusHeartbeat = null
}
}
diff --git a/mcp-host/src/mcp/__tests__/managerStatus.test.ts b/mcp-host/src/mcp/__tests__/managerStatus.test.ts
index 6e2178c0f..3c6fa6de9 100644
--- a/mcp-host/src/mcp/__tests__/managerStatus.test.ts
+++ b/mcp-host/src/mcp/__tests__/managerStatus.test.ts
@@ -110,14 +110,21 @@ describe('McpManager.refreshAllServerStatus', () => {
})
const probe = vi
.spyOn(McpClient.prototype, 'probeTools')
- .mockResolvedValue({ ok: true, toolCount: 4 })
+ .mockResolvedValue({ ok: true, toolCount: 4, outputSchemaCount: 0 })
const m = new McpManager()
await m.addServer(serverInfo())
expect(m.status.get('svc')!.toolCount).toBe(1)
- const n = await m.refreshAllServerStatus()
- expect(n).toBe(1)
+ const summary = await m.refreshAllServerStatus()
+ expect(summary).toMatchObject({
+ serverCount: 1,
+ succeeded: 1,
+ failed: 0,
+ toolCount: 4,
+ outputSchemaCount: 0,
+ aborted: false,
+ })
expect(probe).toHaveBeenCalledTimes(1)
expect(m.status.get('svc')!.toolCount).toBe(4)
})
@@ -143,10 +150,16 @@ describe('McpManager.refreshAllServerStatus', () => {
expect(s.reason).toBe('upstream_5xx')
})
- it('returns 0 and is a no-op when no servers are connected', async () => {
+ it('returns an empty summary and is a no-op when no servers are connected', async () => {
const m = new McpManager()
- const n = await m.refreshAllServerStatus()
- expect(n).toBe(0)
+ await expect(m.refreshAllServerStatus()).resolves.toEqual({
+ serverCount: 0,
+ succeeded: 0,
+ failed: 0,
+ toolCount: 0,
+ outputSchemaCount: 0,
+ aborted: false,
+ })
})
})
diff --git a/mcp-host/src/mcp/client.ts b/mcp-host/src/mcp/client.ts
index 278f8a122..b481d2522 100644
--- a/mcp-host/src/mcp/client.ts
+++ b/mcp-host/src/mcp/client.ts
@@ -6,125 +6,18 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'
+import { ListToolsResultSchema } from '@modelcontextprotocol/sdk/types.js'
import { McpServerInfo, McpTool } from '../types'
+import {
+ type McpToolCallOptions,
+ ensureNotAborted,
+ remainingBudgetMs,
+ requestOptions,
+ resolveMcpRequestTimeoutMs,
+ withRequestTimeout,
+} from './requestOptions'
-const DEFAULT_MCP_TOOL_TIMEOUT_MS = 3_600_000
-const DEFAULT_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS = 3_600_000
-const MCP_TOOL_TIMEOUT_ENV = 'CLERUM_MCP_TOOL_TIMEOUT_MS'
-const MCP_TOOL_MAX_TOTAL_TIMEOUT_ENV = 'CLERUM_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS'
-
-export interface McpToolCallOptions {
- timeoutMs?: number
- signal?: AbortSignal
-}
-
-interface McpSdkRequestOptions {
- timeout: number
- maxTotalTimeout: number
- signal?: AbortSignal
-}
-
-function readPositiveSafeIntegerEnv(name: string, defaultValue: number): number {
- const raw = process.env[name]
- if (raw === undefined || raw === '') return defaultValue
- if (!/^\d+$/.test(raw)) throw new Error(`${name} must be a positive safe integer`)
- const value = Number.parseInt(raw, 10)
- if (!Number.isSafeInteger(value) || value < 1) {
- throw new Error(`${name} must be a positive safe integer`)
- }
- return value
-}
-
-function resolveMcpRequestTimeoutMs(callerTimeoutMs?: number): number {
- const configuredTimeoutMs = readPositiveSafeIntegerEnv(
- MCP_TOOL_TIMEOUT_ENV,
- DEFAULT_MCP_TOOL_TIMEOUT_MS
- )
- const configuredMaxTotalTimeoutMs = readPositiveSafeIntegerEnv(
- MCP_TOOL_MAX_TOTAL_TIMEOUT_ENV,
- DEFAULT_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS
- )
- if (
- configuredMaxTotalTimeoutMs < configuredTimeoutMs &&
- (callerTimeoutMs === undefined || callerTimeoutMs > configuredMaxTotalTimeoutMs)
- ) {
- throw new Error(
- `${MCP_TOOL_MAX_TOTAL_TIMEOUT_ENV} must be greater than or equal to ${MCP_TOOL_TIMEOUT_ENV}`
- )
- }
- if (callerTimeoutMs !== undefined) {
- if (!Number.isSafeInteger(callerTimeoutMs) || callerTimeoutMs < 1) {
- throw new Error('caller MCP timeout must be a positive safe integer')
- }
- return Math.min(configuredTimeoutMs, configuredMaxTotalTimeoutMs, callerTimeoutMs)
- }
- return Math.min(configuredTimeoutMs, configuredMaxTotalTimeoutMs)
-}
-
-function ensureNotAborted(signal: AbortSignal | undefined): void {
- if (!signal?.aborted) return
- const reason =
- typeof signal.reason === 'string' && signal.reason.trim() ? signal.reason : 'aborted'
- throw new Error(reason)
-}
-
-function abortError(signal: AbortSignal | undefined, fallback: string): Error {
- const reason =
- typeof signal?.reason === 'string' && signal.reason.trim() ? signal.reason : fallback
- return new Error(reason)
-}
-
-function withRequestTimeout<T>(
- operation: Promise<T>,
- options: McpToolCallOptions,
- timeoutMessage: string
-): Promise<T> {
- ensureNotAborted(options.signal)
- const timeoutMs = resolveMcpRequestTimeoutMs(options.timeoutMs)
- return new Promise((resolve, reject) => {
- let settled = false
- const cleanup = () => {
- clearTimeout(timer)
- options.signal?.removeEventListener('abort', onAbort)
- }
- const resolveOnce = (value: T) => {
- if (settled) return
- settled = true
- cleanup()
- resolve(value)
- }
- const rejectOnce = (error: unknown) => {
- if (settled) return
- settled = true
- cleanup()
- reject(error)
- }
- const onAbort = () => rejectOnce(abortError(options.signal, 'aborted'))
- const timer = setTimeout(
- () =>
- rejectOnce(new Error(options.timeoutMs !== undefined ? 'step-timeout' : timeoutMessage)),
- timeoutMs
- )
- options.signal?.addEventListener('abort', onAbort, { once: true })
- operation.then(resolveOnce, rejectOnce)
- })
-}
-
-function remainingBudgetMs(deadlineMs: number | undefined): number | undefined {
- if (deadlineMs === undefined) return undefined
- const remainingMs = deadlineMs - Date.now()
- if (remainingMs <= 0) throw new Error('step-timeout')
- return remainingMs
-}
-
-function requestOptions(
- timeoutMs: number | undefined,
- signal: AbortSignal | undefined
-): McpSdkRequestOptions {
- ensureNotAborted(signal)
- const timeout = resolveMcpRequestTimeoutMs(timeoutMs)
- return { timeout, maxTotalTimeout: timeout, ...(signal ? { signal } : {}) }
-}
+export type { McpToolCallOptions } from './requestOptions'
export class McpClient {
private client: Client | null = null
@@ -317,17 +210,26 @@ export class McpClient {
*/
async probeTools(
options: McpToolCallOptions = {}
- ): Promise<{ ok: true; toolCount: number } | { ok: false; error: unknown }> {
+ ): Promise<
+ { ok: true; toolCount: number; outputSchemaCount: number } | { ok: false; error: unknown }
+ > {
if (!this.client || !this.connected) {
return { ok: false, error: new Error(`${this.name} is not connected`) }
}
try {
- const response = await this.client.listTools(
- undefined,
+ // Deliberately use the validated raw request instead of Client.listTools().
+ // The SDK convenience method compiles output schemas and mutates task/output
+ // metadata caches, which must remain owned by connection and explicit refresh.
+ const response = await this.client.request(
+ { method: 'tools/list', params: undefined },
+ ListToolsResultSchema,
requestOptions(options.timeoutMs, options.signal)
)
- const toolCount = (response.tools || []).length
- return { ok: true, toolCount }
+ return {
+ ok: true,
+ toolCount: response.tools.length,
+ outputSchemaCount: response.tools.filter(tool => tool.outputSchema !== undefined).length,
+ }
} catch (error) {
return { ok: false, error }
}
diff --git a/mcp-host/src/mcp/manager.ts b/mcp-host/src/mcp/manager.ts
index b498bdf1e..d50d89596 100644
--- a/mcp-host/src/mcp/manager.ts
+++ b/mcp-host/src/mcp/manager.ts
@@ -5,6 +5,22 @@ import { McpServerInfo, McpTool, ToolCallResult } from '../types'
import { McpClient, type McpToolCallOptions } from './client'
import { ServerStatusTracker } from './serverStatus'
+export interface McpStatusRefreshSummary {
+ serverCount: number
+ succeeded: number
+ failed: number
+ toolCount: number
+ outputSchemaCount: number
+ aborted: boolean
+}
+
+function deriveProbeSignal(roundSignal: AbortSignal | undefined): AbortSignal {
+ const probeController = new AbortController()
+ return roundSignal
+ ? AbortSignal.any([roundSignal, probeController.signal])
+ : probeController.signal
+}
+
export class McpManager {
private clients: Map<string, McpClient> = new Map()
private serverInfos: Map<string, McpServerInfo> = new Map()
@@ -219,21 +235,62 @@ export class McpManager {
* Called by the background heartbeat to keep `observedAt` fresh and to
* classify refresh failures (spec §4.5 — stay connected, attach reason).
*
- * Returns the number of servers probed.
+ * Probes a stable client snapshot. State is written only after every probe
+ * settles; an aborted round never mutates the last known server status.
*/
- async refreshAllServerStatus(): Promise<number> {
+ async refreshAllServerStatus(options: McpToolCallOptions = {}): Promise<McpStatusRefreshSummary> {
const entries = [...this.clients.entries()]
- await Promise.all(
+ if (options.signal?.aborted) {
+ return {
+ serverCount: entries.length,
+ succeeded: 0,
+ failed: 0,
+ toolCount: 0,
+ outputSchemaCount: 0,
+ aborted: true,
+ }
+ }
+
+ const results = await Promise.all(
entries.map(async ([name, client]) => {
- const result = await client.probeTools()
- if (result.ok) {
- this.statusTracker.updateToolCount(name, result.toolCount)
- } else {
- this.statusTracker.updateToolCount(name, 0, { refreshError: result.error })
+ try {
+ return {
+ name,
+ result: await client.probeTools({
+ timeoutMs: options.timeoutMs,
+ signal: deriveProbeSignal(options.signal),
+ }),
+ }
+ } catch (error) {
+ return { name, result: { ok: false as const, error } }
}
})
)
- return entries.length
+ const succeeded = results.filter(({ result }) => result.ok).length
+ const summary: McpStatusRefreshSummary = {
+ serverCount: entries.length,
+ succeeded,
+ failed: entries.length - succeeded,
+ toolCount: results.reduce(
+ (total, { result }) => total + (result.ok ? result.toolCount : 0),
+ 0
+ ),
+ outputSchemaCount: results.reduce(
+ (total, { result }) => total + (result.ok ? result.outputSchemaCount : 0),
+ 0
+ ),
+ aborted: options.signal?.aborted === true,
+ }
+ if (summary.aborted) return summary
+
+ for (const { name, result } of results) {
+ if (result.ok) {
+ this.statusTracker.updateToolCount(name, result.toolCount)
+ } else {
+ this.statusTracker.updateToolCount(name, 0, { refreshError: result.error })
+ }
+ }
+ return summary
}
/**
diff --git a/mcp-host/src/mcp/requestOptions.ts b/mcp-host/src/mcp/requestOptions.ts
new file mode 100644
index 000000000..7790cd295
--- /dev/null
+++ b/mcp-host/src/mcp/requestOptions.ts
@@ -0,0 +1,117 @@
+const DEFAULT_MCP_TOOL_TIMEOUT_MS = 3_600_000
+const DEFAULT_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS = 3_600_000
+const MCP_TOOL_TIMEOUT_ENV = 'CLERUM_MCP_TOOL_TIMEOUT_MS'
+const MCP_TOOL_MAX_TOTAL_TIMEOUT_ENV = 'CLERUM_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS'
+
+export interface McpToolCallOptions {
+ timeoutMs?: number
+ signal?: AbortSignal
+}
+
+export interface McpSdkRequestOptions {
+ timeout: number
+ maxTotalTimeout: number
+ signal?: AbortSignal
+}
+
+function readPositiveSafeIntegerEnv(name: string, defaultValue: number): number {
+ const raw = process.env[name]
+ if (raw === undefined || raw === '') return defaultValue
+ if (!/^\d+$/.test(raw)) throw new Error(`${name} must be a positive safe integer`)
+ const value = Number.parseInt(raw, 10)
+ if (!Number.isSafeInteger(value) || value < 1) {
+ throw new Error(`${name} must be a positive safe integer`)
+ }
+ return value
+}
+
+export function resolveMcpRequestTimeoutMs(callerTimeoutMs?: number): number {
+ const configuredTimeoutMs = readPositiveSafeIntegerEnv(
+ MCP_TOOL_TIMEOUT_ENV,
+ DEFAULT_MCP_TOOL_TIMEOUT_MS
+ )
+ const configuredMaxTotalTimeoutMs = readPositiveSafeIntegerEnv(
+ MCP_TOOL_MAX_TOTAL_TIMEOUT_ENV,
+ DEFAULT_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS
+ )
+ if (
+ configuredMaxTotalTimeoutMs < configuredTimeoutMs &&
+ (callerTimeoutMs === undefined || callerTimeoutMs > configuredMaxTotalTimeoutMs)
+ ) {
+ throw new Error(
+ `${MCP_TOOL_MAX_TOTAL_TIMEOUT_ENV} must be greater than or equal to ${MCP_TOOL_TIMEOUT_ENV}`
+ )
+ }
+ if (callerTimeoutMs !== undefined) {
+ if (!Number.isSafeInteger(callerTimeoutMs) || callerTimeoutMs < 1) {
+ throw new Error('caller MCP timeout must be a positive safe integer')
+ }
+ return Math.min(configuredTimeoutMs, configuredMaxTotalTimeoutMs, callerTimeoutMs)
+ }
+ return Math.min(configuredTimeoutMs, configuredMaxTotalTimeoutMs)
+}
+
+export function ensureNotAborted(signal: AbortSignal | undefined): void {
+ if (!signal?.aborted) return
+ const reason =
+ typeof signal.reason === 'string' && signal.reason.trim() ? signal.reason : 'aborted'
+ throw new Error(reason)
+}
+
+function abortError(signal: AbortSignal | undefined, fallback: string): Error {
+ const reason =
+ typeof signal?.reason === 'string' && signal.reason.trim() ? signal.reason : fallback
+ return new Error(reason)
+}
+
+export function withRequestTimeout<T>(
+ operation: Promise<T>,
+ options: McpToolCallOptions,
+ timeoutMessage: string
+): Promise<T> {
+ ensureNotAborted(options.signal)
+ const timeoutMs = resolveMcpRequestTimeoutMs(options.timeoutMs)
+ return new Promise((resolve, reject) => {
+ let settled = false
+ const cleanup = () => {
+ clearTimeout(timer)
+ options.signal?.removeEventListener('abort', onAbort)
+ }
+ const resolveOnce = (value: T) => {
+ if (settled) return
+ settled = true
+ cleanup()
+ resolve(value)
+ }
+ const rejectOnce = (error: unknown) => {
+ if (settled) return
+ settled = true
+ cleanup()
+ reject(error)
+ }
+ const onAbort = () => rejectOnce(abortError(options.signal, 'aborted'))
+ const timer = setTimeout(
+ () =>
+ rejectOnce(new Error(options.timeoutMs !== undefined ? 'step-timeout' : timeoutMessage)),
+ timeoutMs
+ )
+ options.signal?.addEventListener('abort', onAbort, { once: true })
+ operation.then(resolveOnce, rejectOnce)
+ })
+}
+
+export function remainingBudgetMs(deadlineMs: number | undefined): number | undefined {
+ if (deadlineMs === undefined) return undefined
+ const remainingMs = deadlineMs - Date.now()
+ if (remainingMs <= 0) throw new Error('step-timeout')
+ return remainingMs
+}
+
+export function requestOptions(
+ timeoutMs: number | undefined,
+ signal: AbortSignal | undefined
+): McpSdkRequestOptions {
+ ensureNotAborted(signal)
+ const timeout = resolveMcpRequestTimeoutMs(timeoutMs)
+ return { timeout, maxTotalTimeout: timeout, ...(signal ? { signal } : {}) }
+}
diff --git a/mcp-host/src/mcp/serverStatus.ts b/mcp-host/src/mcp/serverStatus.ts
index dd6d72785..a5f15ed99 100644
--- a/mcp-host/src/mcp/serverStatus.ts
+++ b/mcp-host/src/mcp/serverStatus.ts
@@ -64,7 +64,7 @@ export function classifyConnectError(error: unknown): {
}
const code = extractErrorCode(error)
- if (code === 'ETIMEDOUT' || /timed? ?out/i.test(msg)) {
+ if (code === 'ETIMEDOUT' || code === -32001 || /timed? ?out/i.test(msg)) {
return { reason: 'timeout', message: truncate(msg || 'request timed out') }
}
if (
@@ -77,8 +77,11 @@ export function classifyConnectError(error: unknown): {
}
// MCP SDK surfaces protocol errors with numeric JSON-RPC codes in msg.
- if (/jsonrpc|protocol|invalid params|invalid request/i.test(msg)) {
- return { reason: 'handshake', message: truncate(msg) }
+ if (/jsonrpc|protocol|invalid params|invalid request/i.test(msg) || isZodValidationError(error)) {
+ return {
+ reason: 'handshake',
+ message: isZodValidationError(error) ? 'invalid MCP response schema' : truncate(msg),
+ }
}
return { reason: 'unknown', message: truncate(msg || 'unknown error') }
@@ -118,14 +121,22 @@ function extractHttpStatus(error: unknown, msg: string): number | null {
return null
}
-function extractErrorCode(error: unknown): string | null {
+function extractErrorCode(error: unknown): string | number | null {
if (error && typeof error === 'object') {
const code = (error as Record<string, unknown>).code
if (typeof code === 'string') return code
+ if (typeof code === 'number') return code
}
return null
}
+function isZodValidationError(error: unknown): boolean {
+ if (!error || typeof error !== 'object') return false
+ const candidate = error as Record<string, unknown>
+ const hasIssues = Array.isArray(candidate.issues)
+ return hasIssues && (candidate.name === 'ZodError' || candidate.name === '$ZodError')
+}
+
function truncate(s: string, max = 240): string {
return s.length > max ? `${s.slice(0, max - 1)}…` : s
}
diff --git a/mcp-host/src/mcp/statusHeartbeat.ts b/mcp-host/src/mcp/statusHeartbeat.ts
new file mode 100644
index 000000000..accea88eb
--- /dev/null
+++ b/mcp-host/src/mcp/statusHeartbeat.ts
@@ -0,0 +1,94 @@
+import type { McpToolCallOptions } from './client'
+import type { McpManager, McpStatusRefreshSummary } from './manager'
+import {
+ type McpStatusHeartbeatMetricsPort,
+ mcpStatusHeartbeatMetrics,
+} from './statusHeartbeatMetrics'
+
+export interface McpStatusHeartbeatOptions {
+ intervalMs: number
+ timeoutMs: number
+ getRefresher: () => Pick<McpManager, 'refreshAllServerStatus'> | null
+ metrics?: McpStatusHeartbeatMetricsPort
+ onError?: (error: unknown) => void
+}
+
+/**
+ * Owns one bounded background status round at a time. It deliberately does
+ * not own transports: stopping cancels only its current probe round.
+ */
+export class McpStatusHeartbeat {
+ private readonly metrics: McpStatusHeartbeatMetricsPort
+ private interval: ReturnType<typeof setInterval> | null = null
+ private initialTick: ReturnType<typeof setTimeout> | null = null
+ private activeRound: AbortController | null = null
+ private stopped = false
+
+ constructor(private readonly options: McpStatusHeartbeatOptions) {
+ this.metrics = options.metrics ?? mcpStatusHeartbeatMetrics
+ }
+
+ start(): void {
+ if (this.interval || this.initialTick) return
+ this.stopped = false
+ this.initialTick = setTimeout(() => {
+ this.initialTick = null
+ void this.tick()
+ }, 0)
+ this.interval = setInterval(() => void this.tick(), this.options.intervalMs)
+ }
+
+ stop(): void {
+ if (this.stopped) return
+ this.stopped = true
+ if (this.initialTick) clearTimeout(this.initialTick)
+ if (this.interval) clearInterval(this.interval)
+ this.initialTick = null
+ this.interval = null
+ this.activeRound?.abort('MCP status heartbeat stopped')
+ }
+
+ private async tick(): Promise<void> {
+ if (this.stopped || this.activeRound) {
+ this.metrics.runSkipped()
+ return
+ }
+ const refresher = this.options.getRefresher()
+ if (!refresher) {
+ this.metrics.runSkipped()
+ return
+ }
+
+ const controller = new AbortController()
+ this.activeRound = controller
+ this.metrics.runStarted()
+ const timeout = setTimeout(
+ () => controller.abort('MCP status heartbeat timeout'),
+ this.options.timeoutMs
+ )
+ try {
+ const summary = await refresher.refreshAllServerStatus({
+ timeoutMs: this.options.timeoutMs,
+ signal: controller.signal,
+ } satisfies McpToolCallOptions)
+ this.metrics.runFinished(summary)
+ } catch (error) {
+ this.metrics.runFinished(failedSummary(controller.signal.aborted))
+ this.options.onError?.(error)
+ } finally {
+ clearTimeout(timeout)
+ if (this.activeRound === controller) this.activeRound = null
+ }
+ }
+}
+
+function failedSummary(aborted: boolean): McpStatusRefreshSummary {
+ return {
+ serverCount: 0,
+ succeeded: 0,
+ failed: 0,
+ toolCount: 0,
+ outputSchemaCount: 0,
+ aborted,
+ }
+}
diff --git a/mcp-host/src/mcp/statusHeartbeatMetrics.ts b/mcp-host/src/mcp/statusHeartbeatMetrics.ts
new file mode 100644
index 000000000..293e6cf23
--- /dev/null
+++ b/mcp-host/src/mcp/statusHeartbeatMetrics.ts
@@ -0,0 +1,96 @@
+import { Counter, Gauge, type Registry, register } from 'prom-client'
+import type { McpStatusRefreshSummary } from './manager'
+
+type Outcome = 'completed' | 'failed' | 'skipped' | 'aborted'
+type ProbeOutcome = 'succeeded' | 'failed'
+type ServerOutcome = 'expected' | 'succeeded' | 'failed'
+
+export interface McpStatusHeartbeatMetricsPort {
+ runStarted(): void
+ runSkipped(): void
+ runFinished(summary: McpStatusRefreshSummary): void
+}
+
+function counter<Label extends string>(
+ registry: Registry,
+ options: { name: string; help: string; labelNames?: Label[] }
+): Counter<Label> {
+ const existing = registry.getSingleMetric(options.name)
+ if (existing) return existing as Counter<Label>
+ return new Counter<Label>({ ...options, registers: [registry] })
+}
+
+function gauge<Label extends string>(
+ registry: Registry,
+ options: { name: string; help: string; labelNames?: Label[] }
+): Gauge<Label> {
+ const existing = registry.getSingleMetric(options.name)
+ if (existing) return existing as Gauge<Label>
+ return new Gauge<Label>({ ...options, registers: [registry] })
+}
+
+export class McpStatusHeartbeatMetrics implements McpStatusHeartbeatMetricsPort {
+ private readonly runs: Counter<'outcome'>
+ private readonly inFlight: Gauge
+ private readonly probes: Counter<'outcome'>
+ private readonly servers: Gauge<'outcome'>
+ private readonly tools: Gauge
+ private readonly outputSchemas: Gauge
+
+ constructor(registry: Registry = register) {
+ this.runs = counter(registry, {
+ name: 'clerum_mcp_status_heartbeat_runs_total',
+ help: 'Completed MCP status-heartbeat rounds by outcome.',
+ labelNames: ['outcome'],
+ })
+ this.inFlight = gauge(registry, {
+ name: 'clerum_mcp_status_heartbeat_in_flight',
+ help: 'Whether an MCP status-heartbeat round is currently in flight.',
+ })
+ this.probes = counter(registry, {
+ name: 'clerum_mcp_status_heartbeat_probes_total',
+ help: 'Individual MCP status probes by outcome.',
+ labelNames: ['outcome'],
+ })
+ this.servers = gauge(registry, {
+ name: 'clerum_mcp_status_heartbeat_servers',
+ help: 'MCP status-heartbeat server counts by outcome.',
+ labelNames: ['outcome'],
+ })
+ this.tools = gauge(registry, {
+ name: 'clerum_mcp_status_heartbeat_tools',
+ help: 'Tools observed during the most recent MCP status-heartbeat round.',
+ })
+ this.outputSchemas = gauge(registry, {
+ name: 'clerum_mcp_status_heartbeat_output_schemas',
+ help: 'Tool output schemas observed during the most recent MCP status-heartbeat round.',
+ })
+ }
+
+ runStarted(): void {
+ this.inFlight.inc()
+ }
+
+ runSkipped(): void {
+ this.runs.inc({ outcome: 'skipped' satisfies Outcome })
+ }
+
+ runFinished(summary: McpStatusRefreshSummary): void {
+ this.inFlight.dec()
+ const outcome: Outcome = summary.aborted
+ ? 'aborted'
+ : summary.failed > 0
+ ? 'failed'
+ : 'completed'
+ this.runs.inc({ outcome })
+ this.probes.inc({ outcome: 'succeeded' satisfies ProbeOutcome }, summary.succeeded)
+ this.probes.inc({ outcome: 'failed' satisfies ProbeOutcome }, summary.failed)
+ this.servers.set({ outcome: 'expected' satisfies ServerOutcome }, summary.serverCount)
+ this.servers.set({ outcome: 'succeeded' satisfies ServerOutcome }, summary.succeeded)
+ this.servers.set({ outcome: 'failed' satisfies ServerOutcome }, summary.failed)
+ this.tools.set(summary.toolCount)
+ this.outputSchemas.set(summary.outputSchemaCount)
+ }
+}
+
+export const mcpStatusHeartbeatMetrics = new McpStatusHeartbeatMetrics()
diff --git a/mcp-host/src/observability/processMetrics.ts b/mcp-host/src/observability/processMetrics.ts
new file mode 100644
index 000000000..27c4c3b28
--- /dev/null
+++ b/mcp-host/src/observability/processMetrics.ts
@@ -0,0 +1,31 @@
+import { type Registry, collectDefaultMetrics, register } from 'prom-client'
+
+type RegistrationState = 'idle' | 'registering' | 'complete'
+
+const registrationStates = new WeakMap<Registry, RegistrationState>()
+const PROCESS_CPU_METRIC = 'process_cpu_user_seconds_total'
+
+/**
+ * Register prom-client's process metrics once for each registry. The state
+ * machine makes repeated server imports safe while preserving a retry path if
+ * registration throws before the metric set is complete.
+ */
+export function registerProcessMetrics(registry: Registry = register): void {
+ const state = registrationStates.get(registry) ?? 'idle'
+ if (state === 'complete' || state === 'registering') return
+ if (registry.getSingleMetric(PROCESS_CPU_METRIC)) {
+ registrationStates.set(registry, 'complete')
+ return
+ }
+
+ registrationStates.set(registry, 'registering')
+ try {
+ collectDefaultMetrics({ register: registry })
+ registrationStates.set(registry, 'complete')
+ } catch (error) {
+ registrationStates.set(registry, 'idle')
+ throw error
+ }
+}
+
+registerProcessMetrics()
diff --git a/mcp-host/src/server.ts b/mcp-host/src/server.ts
index ca4024d8c..7d094f1a5 100644
--- a/mcp-host/src/server.ts
+++ b/mcp-host/src/server.ts
@@ -11,6 +11,8 @@ import { register } from 'prom-client'
import { readOpenedArtifactBuffer, redactArtifactForDelivery } from './artifacts/artifactBytes'
import type { ArtifactSecretEntry } from './artifacts/artifactRedaction'
import type { RuntimeLifecycleGate } from './lifecycle/statelessHeartbeat'
+import './mcp/statusHeartbeatMetrics'
+import './observability/processMetrics'
import { requireScope } from './server/authMiddleware'
import { getRuntimeCallerContext, runtimeEdgeGuard } from './server/edgeRuntimeAuth'
import { getAllowedOrigins, json } from './server/httpUtils'