Skip to content

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

TypeScript

fix(mcp-host): probe only the SHARED representative in the status heartbeat (R4-M2)

Diego Zacarias18cb32800345
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 8f09f8437..e73fa5691 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.300",
+ "version": "0.1.301",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.300",
+ "version": "0.1.301",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 06b11e05a..d994b340c 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.300",
+ "version": "0.1.301",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/mcp/__tests__/managerProbeRepresentative.test.ts b/mcp-host/src/mcp/__tests__/managerProbeRepresentative.test.ts
new file mode 100644
index 000000000..078275219
--- /dev/null
+++ b/mcp-host/src/mcp/__tests__/managerProbeRepresentative.test.ts
@@ -0,0 +1,187 @@
+/**
+ * R4-M2 — platform heartbeat probes must never spend a user's OAuth token.
+ *
+ * `refreshAllServerStatus()` is the background platform heartbeat: it calls
+ * `client.probeTools()`, a REAL network round-trip (tools/list). It must probe
+ * ONLY the SHARED partition (`probeRepresentativeClient`), never fall back to a
+ * per-user partition — otherwise a platform probe rides a user's OAuth
+ * connection and spends that user's identity/quota.
+ *
+ * The pathological state pinned here: an oauth-user server whose SHARED
+ * representative is gone but a per-user partition is still alive. Under the old
+ * `representativeClient` fallback the heartbeat would probe the per-user
+ * connection. This test asserts the OBSERVABLE (T4): the probe carrying the
+ * user's Bearer is never issued, and the server does not count as `succeeded`.
+ *
+ * Fixtures are derived from the real producers (McpManager + the real McpClient
+ * over a mocked SDK, the same wiring managerPartition.test.ts uses) — the
+ * pathological state is reached with real manager APIs (callTool to admit the
+ * per-user partition, evictRevokedPartitions to drop the SHARED key), never a
+ * hand-built internal-map fixture.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { McpServerInfo } from '../../types'
+import type { McpTokenProvider } from '../client'
+import {
+ McpManager,
+ type McpPrincipal,
+ type McpTokenProviderFactory,
+ SHARED_PRINCIPAL,
+ serializeClientKey,
+} from '../manager'
+
+// ─── SDK mocks (constructable; capture per-transport headers) ────────────────
+//
+// probeTools() issues `client.request({ method: 'tools/list' }, …)` — NOT
+// Client.listTools(). So the observable of "which connection was probed" is the
+// Authorization header on the transport of each `request` call. Connect-time
+// tool discovery uses Client.listTools(), kept separate so setup probes don't
+// pollute `probeAuth`.
+
+interface MockTransport {
+ requestHeaders: Record<string, string>
+ close: ReturnType<typeof vi.fn>
+}
+
+const sdk: {
+ transports: MockTransport[]
+ /** Authorization header of every probe (`request` tools/list) call, in order. */
+ probeAuth: Array<string | undefined>
+} = { transports: [], probeAuth: [] }
+
+const TOOLS_RESULT = {
+ tools: [{ name: 'do', description: 'demo tool', inputSchema: { type: 'object' } }],
+}
+
+vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
+ Client: class MockClient {
+ private transport: MockTransport | null = null
+ connect = vi.fn(async (t: MockTransport) => {
+ this.transport = t
+ })
+ close = vi.fn().mockResolvedValue(undefined)
+ // Connect-time discovery (refreshTools → Client.listTools()).
+ listTools = vi.fn(async () => TOOLS_RESULT)
+ // Platform probe (probeTools → client.request tools/list). Records the auth
+ // header so the test can see WHICH connection the heartbeat probed.
+ request = vi.fn(async () => {
+ const headers = this.transport?.requestHeaders ?? {}
+ sdk.probeAuth.push(headers['Authorization'])
+ return TOOLS_RESULT
+ })
+ callTool = vi.fn(async () => {
+ const headers = this.transport?.requestHeaders ?? {}
+ return { content: [{ type: 'text', text: 'ok' }], authorization: headers['Authorization'] }
+ })
+ },
+}))
+
+vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({
+ StreamableHTTPClientTransport: class MockStreamable {
+ requestHeaders: Record<string, string>
+ close = vi.fn().mockResolvedValue(undefined)
+ constructor(_url: URL, opts?: { requestInit?: { headers?: Record<string, string> } }) {
+ this.requestHeaders = opts?.requestInit?.headers ?? {}
+ sdk.transports.push(this as unknown as MockTransport)
+ }
+ },
+}))
+
+vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({
+ SSEClientTransport: class MockSSE {
+ close = vi.fn().mockResolvedValue(undefined)
+ },
+}))
+
+// ─── Helpers ─────────────────────────────────────────────────────────────────
+
+function oauthUserServer(name = 'gh'): McpServerInfo {
+ return {
+ name,
+ contextRef: 'ctx-1',
+ transport: { type: 'streamableHttp', url: `http://${name}/mcp` },
+ authKind: 'oauth-user',
+ enabled: true,
+ status: { deployed: true, ready: true },
+ }
+}
+
+function oauthContextServer(name = 'ctx-gh'): McpServerInfo {
+ return {
+ name,
+ contextRef: 'ctx-1',
+ transport: { type: 'streamableHttp', url: `http://${name}/mcp` },
+ authKind: 'oauth-context',
+ enabled: true,
+ status: { deployed: true, ready: true },
+ }
+}
+
+/** oauth-user factory: per-user principals get a per-user Bearer; the SHARED
+ * representative is token-less (catalog population, no grant). Mirrors main.ts
+ * createMcpTokenProviderFactory grantScope='user'. */
+function userFactory(): McpTokenProviderFactory {
+ return (server: McpServerInfo, principal: McpPrincipal): McpTokenProvider => {
+ if (principal.kind === 'shared') {
+ return { resolve: async () => undefined, refresh: async () => undefined }
+ }
+ const token = `token-for-${principal.userId}`
+ return { resolve: async () => token, refresh: async () => token }
+ }
+}
+
+/** oauth-context factory: even the SHARED representative carries the context
+ * Bearer (grantScope='context'). */
+function contextFactory(): McpTokenProviderFactory {
+ return () => ({ resolve: async () => 'context-bearer', refresh: async () => 'context-bearer' })
+}
+
+beforeEach(() => {
+ sdk.transports = []
+ sdk.probeAuth = []
+})
+
+// ─── R4-M2 · pathological: SHARED down + per-user alive → NOT probed ──────────
+
+describe('refreshAllServerStatus never probes a per-user partition (R4-M2)', () => {
+ it('an oauth-user server with only a per-user partition alive is not probed and not counted', async () => {
+ const manager = new McpManager(undefined, undefined, userFactory())
+ await manager.addServer(oauthUserServer()) // SHARED representative (token-less)
+ await manager.callTool('gh__do', {}, { userId: 'alice' }) // per-user partition (alice)
+
+ // Reach the pathological state via a real manager API: drop ONLY the SHARED
+ // partition, leaving alice's per-user partition live. representativeClient
+ // would now fall back to alice's client; probeRepresentativeClient must not.
+ const evicted = manager.evictRevokedPartitions([serializeClientKey('gh', SHARED_PRINCIPAL)])
+ expect(evicted).toBe(1)
+ // The server is still known (alice's partition keeps 'gh' in the index).
+ expect(manager.getConnectedServers()).toEqual(['gh'])
+
+ sdk.probeAuth = [] // only observe probes issued by the heartbeat below.
+ const summary = await manager.refreshAllServerStatus()
+
+ // Observable (T4): the heartbeat issued NO probe on alice's connection —
+ // her OAuth Bearer never left the host for a platform probe.
+ expect(sdk.probeAuth).not.toContain('Bearer token-for-alice')
+ // And this server, having no SHARED representative, is not probed at all,
+ // so it contributes nothing to the round's tally.
+ expect(sdk.probeAuth).toEqual([])
+ expect(summary.serverCount).toBe(0)
+ expect(summary.succeeded).toBe(0)
+ })
+
+ // ─── control: SHARED alive IS still probed (normal path unbroken) ──────────
+
+ it('an oauth-context server with a live SHARED partition is still probed', async () => {
+ const manager = new McpManager(undefined, undefined, contextFactory())
+ await manager.addServer(oauthContextServer()) // SHARED partition (context Bearer)
+
+ sdk.probeAuth = []
+ const summary = await manager.refreshAllServerStatus()
+
+ // The SHARED connection was probed on the context Bearer, and counts.
+ expect(sdk.probeAuth).toContain('Bearer context-bearer')
+ expect(summary.serverCount).toBe(1)
+ expect(summary.succeeded).toBe(1)
+ })
+})
diff --git a/mcp-host/src/mcp/manager.ts b/mcp-host/src/mcp/manager.ts
index 70211a8b1..aeed7f2d2 100644
--- a/mcp-host/src/mcp/manager.ts
+++ b/mcp-host/src/mcp/manager.ts
@@ -183,6 +183,29 @@ export class McpManager {
return undefined
}
+ /**
+ * The representative to probe on behalf of the PLATFORM (background
+ * heartbeat) — the SHARED partition ONLY, with NO per-user fallback.
+ *
+ * A platform probe (`probeTools`) makes a REAL network call. It must never be
+ * charged to a user's OAuth token/quota, so it may only ride the SHARED
+ * connection:
+ * - static / oauth-context / the token-less oauth-user SHARED representative
+ * all live under the SHARED key, so they are still probed here.
+ * - the sole case skipped is the pathological "SHARED down + a per-user
+ * partition alive" — there `representativeClient` would fall back to a
+ * per-user client and spend that user's identity on a platform probe.
+ * Such a server simply goes un-refreshed this round (status left stale)
+ * rather than being probed with a user's token.
+ *
+ * Catalog reads (`getAllTools` / `describeCapabilities`) intentionally KEEP
+ * the per-user fallback: they read `client.availableTools` from cache — no
+ * network, no token spent — so falling back keeps the catalog populated.
+ */
+ private probeRepresentativeClient(serverName: string): McpClient | undefined {
+ return this.clients.get(this.sharedKey(serverName))
+ }
+
private buildTokenProvider(
serverConfig: McpServerInfo,
principal: McpPrincipal,
@@ -1016,7 +1039,9 @@ export class McpManager {
* Probe every connected server's tool list and update the status tracker.
* Called by the background heartbeat to keep `observedAt` fresh and to
* classify refresh failures (spec §4.5 — stay connected, attach reason).
- * Probes the representative connection per serverName.
+ * Probes the SHARED representative per serverName (probeRepresentativeClient):
+ * a platform probe is a real network call and must never spend a user's OAuth
+ * token, so a server whose only live client is per-user is skipped this round.
*
* Probes a stable client snapshot. State is written only after every probe
* settles; an aborted round never mutates the last known server status.
@@ -1027,7 +1052,7 @@ export class McpManager {
// probes each server once via its representative; iterating raw clients would
// double-count those partitions in the summary tally.
const entries = [...this.byServer.keys()]
- .map(name => [name, this.representativeClient(name)] as const)
+ .map(name => [name, this.probeRepresentativeClient(name)] as const)
.filter((entry): entry is readonly [string, McpClient] => entry[1] !== undefined)
if (options.signal?.aborted) {
return {
@@ -1067,7 +1092,7 @@ export class McpManager {
// inflate `failed` and flip the run's outcome on the series #148 watches.
const committed = results.filter(
({ name, client, result }) =>
- this.representativeClient(name) === client && !(!result.ok && result.stale)
+ this.probeRepresentativeClient(name) === client && !(!result.ok && result.stale)
)
const succeeded = committed.filter(({ result }) => result.ok).length
const summary: McpStatusRefreshSummary = {