Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): isolate concurrent call recovery
Alfredo Lopez2ecd7fbfce38
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 611f4a185..a66c660a1 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.213",+ "version": "0.1.214","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.213",+ "version": "0.1.214","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex b28758c4c..dfb6f2a56 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.213",+ "version": "0.1.214","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts b/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.tsindex bb3d7dc54..b96dfcdda 100644--- a/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts+++ b/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts@@ -125,7 +125,7 @@ describe('McpClient SDK request timeouts', () => {])})- it('preserves timeout options across reconnect retry', async () => {+ it('preserves the caller budget for retry while shared recovery uses its lifecycle budget', async () => {vi.useFakeTimers()sdkState.callToolQueue.push(() => {@@ -144,7 +144,202 @@ describe('McpClient SDK request timeouts', () => {expect(sdkState.callToolCalls).toHaveLength(2)expect(sdkState.callToolCalls[0][2]).toEqual(expect.objectContaining({ timeout: 30_000 }))expect(sdkState.callToolCalls[1][2]).toEqual(expect.objectContaining({ timeout: 29_000 }))- expect(sdkState.listToolsCalls[1][1]).toEqual(expect.objectContaining({ timeout: 29_000 }))+ expect(sdkState.listToolsCalls[1][1]).toEqual(expect.objectContaining({ timeout: 3_600_000 }))+ })++ it('lets a slower peer adopt the completed recovery of their shared session', async () => {+ vi.useFakeTimers()+ sdkState.callToolQueue.push(+ () => {+ throw Object.assign(new Error('session not found'), { code: -32003 })+ },+ () => {+ throw Object.assign(new Error('session not found'), { code: -32003 })+ },+ () => ({ content: [{ type: 'text', text: 'first-after-reconnect' }] }),+ () => ({ content: [{ type: 'text', text: 'second-after-reconnect' }] })+ )+ const c = client()+ await c.connect()++ const first = c.callTool('read', { id: 1 }, { timeoutMs: 30_000 })+ await vi.advanceTimersByTimeAsync(500)+ const second = c.callTool('read', { id: 2 }, { timeoutMs: 30_000 })+ const settled = Promise.allSettled([first, second])+ await vi.advanceTimersByTimeAsync(500)++ // The first call has already completed the one shared reconnect while the+ // slower peer is still inside its independently budgeted retry delay.+ expect(sdkState.connectCalls).toHaveLength(2)+ expect(sdkState.callToolCalls).toHaveLength(3)+ await vi.advanceTimersByTimeAsync(500)++ await expect(settled).resolves.toEqual([+ {+ status: 'fulfilled',+ value: { content: [{ type: 'text', text: 'first-after-reconnect' }] },+ },+ {+ status: 'fulfilled',+ value: { content: [{ type: 'text', text: 'second-after-reconnect' }] },+ },+ ])+ expect(sdkState.connectCalls).toHaveLength(2)+ expect(sdkState.callToolCalls).toHaveLength(4)+ })++ it('retries a session error that arrives after a peer has recovered their source', async () => {+ vi.useFakeTimers()+ const lateSessionError = deferred<unknown>()+ sdkState.callToolQueue.push(+ () => {+ throw Object.assign(new Error('session not found'), { code: -32003 })+ },+ () => lateSessionError.promise,+ () => ({ content: [{ type: 'text', text: 'first-after-reconnect' }] }),+ () => ({ content: [{ type: 'text', text: 'late-after-reconnect' }] })+ )+ const c = client()+ await c.connect()++ const settled = Promise.allSettled([+ c.callTool('read', { id: 1 }, { timeoutMs: 30_000 }),+ c.callTool('read', { id: 2 }, { timeoutMs: 30_000 }),+ ])+ await vi.advanceTimersByTimeAsync(1000)+ expect(sdkState.connectCalls).toHaveLength(2)+ expect(sdkState.callToolCalls).toHaveLength(3)++ lateSessionError.reject(Object.assign(new Error('session not found'), { code: -32003 }))+ await vi.advanceTimersByTimeAsync(1000)++ await expect(settled).resolves.toEqual([+ {+ status: 'fulfilled',+ value: { content: [{ type: 'text', text: 'first-after-reconnect' }] },+ },+ {+ status: 'fulfilled',+ value: { content: [{ type: 'text', text: 'late-after-reconnect' }] },+ },+ ])+ expect(sdkState.connectCalls).toHaveLength(2)+ expect(sdkState.callToolCalls).toHaveLength(4)+ })++ it('fails all shared recovery waiters closed when the client is retired', async () => {+ vi.useFakeTimers()+ const reconnectHandshake = deferred()+ sdkState.callToolQueue.push(+ () => {+ throw Object.assign(new Error('session not found'), { code: -32003 })+ },+ () => {+ throw Object.assign(new Error('session not found'), { code: -32003 })+ },+ () => ({ content: [{ type: 'text', text: 'must-not-run' }] }),+ () => ({ content: [{ type: 'text', text: 'must-not-run' }] })+ )+ const c = client()+ await c.connect()+ sdkState.connectQueue.push(() => reconnectHandshake.promise)++ const settled = Promise.allSettled([+ c.callTool('write', { id: 1 }, { timeoutMs: 30_000 }),+ c.callTool('write', { id: 2 }, { timeoutMs: 30_000 }),+ ])+ await vi.advanceTimersByTimeAsync(1000)+ expect(sdkState.connectCalls).toHaveLength(2)++ const closing = retirePermanently(c)+ reconnectHandshake.resolve()+ await closing+ await vi.advanceTimersByTimeAsync(0)++ await expect(settled).resolves.toEqual([+ {+ status: 'rejected',+ reason: expect.objectContaining({ message: expect.stringMatching(/closed|superseded/) }),+ },+ {+ status: 'rejected',+ reason: expect.objectContaining({ message: expect.stringMatching(/closed|superseded/) }),+ },+ ])+ expect(sdkState.callToolCalls).toHaveLength(2)+ expect(c.isConnected).toBe(false)+ })++ it('keeps shared recovery alive when its first caller exhausts a shorter budget', async () => {+ vi.useFakeTimers()+ const reconnectHandshake = deferred()+ sdkState.callToolQueue.push(+ () => {+ throw Object.assign(new Error('session not found'), { code: -32003 })+ },+ () => {+ throw Object.assign(new Error('session not found'), { code: -32003 })+ },+ () => ({ content: [{ type: 'text', text: 'long-budget-peer-recovered' }] })+ )+ const c = client()+ await c.connect()+ sdkState.connectQueue.push(() => reconnectHandshake.promise)++ const shortBudget = c.callTool('read', { id: 1 }, { timeoutMs: 1_500 })+ const shortAssertion = expect(shortBudget).rejects.toThrow('step-timeout')+ const longBudget = c.callTool('read', { id: 2 }, { timeoutMs: 30_000 })+ await vi.advanceTimersByTimeAsync(1000)+ expect(sdkState.connectCalls).toHaveLength(2)++ await vi.advanceTimersByTimeAsync(500)+ await shortAssertion+ expect(sdkState.callToolCalls).toHaveLength(2)++ reconnectHandshake.resolve()+ await vi.advanceTimersByTimeAsync(0)+ await expect(longBudget).resolves.toEqual({+ content: [{ type: 'text', text: 'long-budget-peer-recovered' }],+ })+ expect(sdkState.connectCalls).toHaveLength(2)+ expect(sdkState.callToolCalls).toHaveLength(3)+ })++ it('lets an aborted peer leave shared recovery without cancelling it for another caller', async () => {+ vi.useFakeTimers()+ const reconnectHandshake = deferred()+ const peerController = new AbortController()+ sdkState.callToolQueue.push(+ () => {+ throw Object.assign(new Error('session not found'), { code: -32003 })+ },+ () => {+ throw Object.assign(new Error('session not found'), { code: -32003 })+ },+ () => ({ content: [{ type: 'text', text: 'leader-recovered' }] })+ )+ const c = client()+ await c.connect()+ sdkState.connectQueue.push(() => reconnectHandshake.promise)++ const leader = c.callTool('read', { id: 1 }, { timeoutMs: 30_000 })+ const peer = c.callTool('read', { id: 2 }, { timeoutMs: 30_000, signal: peerController.signal })+ const peerAssertion = expect(peer).rejects.toThrow('peer-aborted')+ await vi.advanceTimersByTimeAsync(1000)+ expect(sdkState.connectCalls).toHaveLength(2)++ peerController.abort('peer-aborted')+ await peerAssertion+ expect(sdkState.connectCalls).toHaveLength(2)+ expect(sdkState.callToolCalls).toHaveLength(2)++ reconnectHandshake.resolve()+ await vi.advanceTimersByTimeAsync(0)+ await expect(leader).resolves.toEqual({+ content: [{ type: 'text', text: 'leader-recovered' }],+ })+ expect(sdkState.connectCalls).toHaveLength(2)+ expect(sdkState.callToolCalls).toHaveLength(3)})it('does not start reconnect retry after the caller budget is exhausted', async () => {@@ -164,6 +359,32 @@ describe('McpClient SDK request timeouts', () => {expect(sdkState.listToolsCalls).toHaveLength(1)})+ it('does not start reconnect after the caller aborts during the retry delay', async () => {+ vi.useFakeTimers()+ sdkState.callToolQueue.push(() => {+ throw Object.assign(new Error('session not found'), { code: -32003 })+ })+ const controller = new AbortController()+ const c = client()+ await c.connect()++ const pending = c.callTool(+ 'write',+ { value: 'side-effect' },+ { timeoutMs: 30_000, signal: controller.signal }+ )+ const assertion = expect(pending).rejects.toThrow('caller-aborted')+ await vi.advanceTimersByTimeAsync(500)+ controller.abort('caller-aborted')+ await vi.advanceTimersByTimeAsync(500)++ await assertion+ expect(sdkState.connectCalls).toHaveLength(1)+ expect(sdkState.transportCloseCalls).toHaveLength(0)+ expect(sdkState.callToolCalls).toHaveLength(1)+ expect(c.isConnected).toBe(true)+ })+it('fails closed for invalid timeout env before SDK tool discovery', async () => {vi.stubEnv('CLERUM_MCP_TOOL_TIMEOUT_MS', '0')const c = client()@@ -392,6 +613,45 @@ describe('McpClient SDK request timeouts', () => {expect(new Set(sdkState.transportCloseCalls.map(([transport]) => transport)).size).toBe(2)})+ it('rejects all recovery waiters promptly when retired while reconnect never settles', async () => {+ vi.useFakeTimers()+ const reconnectHandshake = deferred()+ sdkState.callToolQueue.push(+ () => {+ throw Object.assign(new Error('session not found'), { code: -32003 })+ },+ () => {+ throw Object.assign(new Error('session not found'), { code: -32003 })+ }+ )+ const c = client()+ await c.connect()+ sdkState.connectQueue.push(() => reconnectHandshake.promise)++ const settled = Promise.allSettled([+ c.callTool('write', { id: 1 }, { timeoutMs: 30_000 }),+ c.callTool('write', { id: 2 }, { timeoutMs: 30_000 }),+ ])+ await vi.advanceTimersByTimeAsync(1000)+ expect(sdkState.connectCalls).toHaveLength(2)++ await retirePermanently(c)+ await vi.advanceTimersByTimeAsync(0)++ await expect(settled).resolves.toEqual([+ {+ status: 'rejected',+ reason: expect.objectContaining({ message: expect.stringMatching(/closed/) }),+ },+ {+ status: 'rejected',+ reason: expect.objectContaining({ message: expect.stringMatching(/closed/) }),+ },+ ])+ expect(sdkState.callToolCalls).toHaveLength(2)+ expect(c.isConnected).toBe(false)+ })+it('does not publish tools discovered after permanent close', async () => {const discovery = deferred<{tools: Array<{ name: string; description: string; inputSchema: Record<string, unknown> }>diff --git a/mcp-host/src/mcp/client.ts b/mcp-host/src/mcp/client.tsindex f0d9a7161..febe8b8e4 100644--- a/mcp-host/src/mcp/client.ts+++ b/mcp-host/src/mcp/client.ts@@ -25,6 +25,14 @@ interface McpSdkRequestOptions {signal?: AbortSignal}+interface McpCallRecovery {+ sourceEpoch: number+ sourceClient: Client+ targetEpoch?: number+ targetClient?: Client+ promise: Promise<void>+}+type McpProbeResult =| { ok: true; toolCount: number }| { ok: false; error: unknown; stale: boolean }@@ -68,12 +76,11 @@ function resolveMcpRequestTimeoutMs(callerTimeoutMs?: number): number {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)+ throw abortError(signal, 'aborted')}function abortError(signal: AbortSignal | undefined, fallback: string): Error {+ if (signal?.reason instanceof Error) return signal.reasonconst reason =typeof signal?.reason === 'string' && signal.reason.trim() ? signal.reason : fallbackreturn new Error(reason)@@ -140,8 +147,10 @@ export class McpClient {private tools: McpTool[] = []private connected: boolean = falseprivate reconnectPromise: Promise<void> | null = null+ private reconnectCallRecovery: McpCallRecovery | null = nullprivate connectionEpoch = 0private retired = false+ private readonly retirementController = new AbortController()private readonly transportCleanups = new WeakMap<SupportedMcpTransport, Promise<void>>()constructor(serverConfig: McpServerInfo, authToken?: string, proxyUrl?: string) {@@ -352,6 +361,7 @@ export class McpClient {*/retire(): () => Promise<void> {this.retired = true+ this.retirementController.abort(this.lifecycleError('closed'))return this.detachConnection()}@@ -469,6 +479,13 @@ export class McpClient {if (this.reconnectPromise) {return this.reconnectPromise}+ // A caller-independent reconnect supersedes any completed session+ // recovery. Calls from that older source must not adopt this connection.+ this.reconnectCallRecovery = null+ await this.startReconnect(options)+ }++ private async startReconnect(options: McpToolCallOptions): Promise<void> {this.reconnectPromise = (async () => {console.log(`[MCP:${this.name}] Reconnecting...`)await this.disconnect()@@ -482,6 +499,92 @@ export class McpClient {}}+ /**+ * Join a session recovery only when it was started by another call from the+ * exact same connection. An unrelated reconnect or replacement must keep+ * stale calls fenced off. The completed source-to-target marker also lets a+ * slower peer adopt a recovery that finished before its retry delay elapsed.+ * Each joining caller retains its own budget and abort signal.+ */+ private async reconnectForCall(+ callEpoch: number,+ callClient: Client,+ options: McpToolCallOptions+ ): Promise<void> {+ this.ensureNotRetired()+ const existingRecovery = this.reconnectCallRecovery+ if (+ existingRecovery?.sourceEpoch === callEpoch &&+ existingRecovery.sourceClient === callClient+ ) {+ await this.waitForCallRecovery(existingRecovery, options)+ return+ }++ if (this.reconnectPromise) {+ throw this.lifecycleError('superseded')+ }++ this.ensureCallCurrent(callEpoch, callClient)+ const recovery: McpCallRecovery = {+ sourceEpoch: callEpoch,+ sourceClient: callClient,+ promise: Promise.resolve(),+ }+ recovery.promise = (async () => {+ try {+ // Recovery belongs to the connection lifecycle, not to whichever+ // affected call happens to win the race. Callers independently bound+ // their wait below without cancelling recovery for healthier peers.+ await this.startReconnect({})+ const targetClient = this.client+ const targetEpoch = this.connectionEpoch+ if (!targetClient) throw this.lifecycleError('superseded')+ this.ensureCallCurrent(targetEpoch, targetClient)+ if (this.reconnectCallRecovery !== recovery) {+ throw this.lifecycleError(this.retired ? 'closed' : 'superseded')+ }+ recovery.targetEpoch = targetEpoch+ recovery.targetClient = targetClient+ } catch (error) {+ if (this.reconnectCallRecovery === recovery) {+ this.reconnectCallRecovery = null+ }+ throw error+ }+ })()+ this.reconnectCallRecovery = recovery+ await this.waitForCallRecovery(recovery, options)+ }++ private async waitForCallRecovery(+ recovery: McpCallRecovery,+ options: McpToolCallOptions+ ): Promise<void> {+ const signal = options.signal+ ? AbortSignal.any([options.signal, this.retirementController.signal])+ : this.retirementController.signal+ await withRequestTimeout(recovery.promise, { ...options, signal }, 'MCP reconnect timeout')+ const { targetEpoch, targetClient } = recovery+ if (+ targetEpoch === undefined ||+ !targetClient ||+ !this.isCallCurrent(targetEpoch, targetClient)+ ) {+ throw this.lifecycleError(this.retired ? 'closed' : 'superseded')+ }+ }++ private canAdoptCallRecovery(callEpoch: number, callClient: Client): boolean {+ const recovery = this.reconnectCallRecovery+ if (recovery?.sourceEpoch !== callEpoch || recovery.sourceClient !== callClient) {+ return false+ }+ if (recovery.targetEpoch === undefined && !recovery.targetClient) return true+ if (recovery.targetEpoch === undefined || !recovery.targetClient) return false+ return this.isCallCurrent(recovery.targetEpoch, recovery.targetClient)+ }+/*** Call a tool on the MCP server.* On session errors (e.g. server pod restarted), reconnects and retries once.@@ -522,22 +625,22 @@ export class McpClient {console.log(`[MCP:${this.name}] Tool result:`, JSON.stringify(result).substring(0, 200))return result} catch (error) {- if (- this.retired ||- this.connectionEpoch !== callEpoch ||- this.client !== callClient ||- !this.connected- ) {- throw this.lifecycleError(this.retired ? 'closed' : 'superseded')+ const sessionError = this.isSessionError(error)+ if (this.retired) {+ throw this.lifecycleError('closed')+ }+ const callCurrent = this.isCallCurrent(callEpoch, callClient)+ if (!callCurrent && (!sessionError || !this.canAdoptCallRecovery(callEpoch, callClient))) {+ throw this.lifecycleError('superseded')}- if (this.isSessionError(error)) {+ if (sessionError) {console.warn(`[MCP:${this.name}] Session lost, reconnecting and retrying after delay...`)try {// Brief delay before reconnect to avoid hammering the serverconst retryDelayMs = Math.min(1000, remainingBudgetMs(deadlineMs) ?? 1000)await new Promise(resolve => setTimeout(resolve, retryDelayMs))- this.ensureCallCurrent(callEpoch, callClient)- await this.reconnect({+ ensureNotAborted(options.signal)+ await this.reconnectForCall(callEpoch, callClient, {timeoutMs: remainingBudgetMs(deadlineMs),signal: options.signal,})