Skip to content

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

TypeScript

fix(mcp-host): fence authoritative fleet lifecycles

Alfredo Lopez67dddf2572c4
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 744d328c2..611f4a185 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.212",
+ "version": "0.1.213",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.212",
+ "version": "0.1.213",
"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 4662ad56b..b28758c4c 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.212",
+ "version": "0.1.213",
"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__/main.mcpInitialization.test.ts b/mcp-host/src/__tests__/main.mcpInitialization.test.ts
index 94b3b88f3..b6f711fa2 100644
--- a/mcp-host/src/__tests__/main.mcpInitialization.test.ts
+++ b/mcp-host/src/__tests__/main.mcpInitialization.test.ts
@@ -2,12 +2,16 @@ import { describe, expect, it, vi } from 'vitest'
import {
admitDevelopmentMcpServers,
createCoalescedPollRunner,
- reconcileAuthoritativeMcpSnapshot,
- replaceAuthoritativeMcpFleet,
- runAuthoritativeMcpInitialization,
startContextMapperPolling,
stopContextMapperPolling,
} from '../main'
+import {
+ AuthoritativeMcpFleetCoordinator,
+ pollAuthoritativeMcpSnapshotIfCurrent,
+ reconcileAuthoritativeMcpSnapshot,
+ replaceAuthoritativeMcpFleet,
+ runAuthoritativeMcpInitialization,
+} from '../mcp/authoritativeFleet'
import { McpManager } from '../mcp/manager'
import type { McpServerInfo } from '../types'
@@ -23,16 +27,47 @@ function readyServer(overrides: Partial<McpServerInfo> = {}): McpServerInfo {
}
}
+function deferred<T = void>(): {
+ promise: Promise<T>
+ resolve: (value: T) => void
+ reject: (reason?: unknown) => void
+} {
+ let resolve!: (value: T) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
+}
+
+function appliedAdmission(
+ effect?: (server: McpServerInfo, authToken?: string) => void | Promise<void>
+) {
+ return vi.fn(
+ async (
+ server: McpServerInfo,
+ authToken?: string,
+ control?: Parameters<McpManager['addServer']>[2]
+ ) => {
+ await effect?.(server, authToken)
+ if (control?.isCurrent?.() === false) return 'stale' as const
+ control?.onCommit?.()
+ return 'applied' as const
+ }
+ )
+}
+
describe('admitDevelopmentMcpServers', () => {
it('continues admitting peers when one development server is unavailable', async () => {
const firstServer = readyServer({ name: 'first-server', auth: { type: 'none' } })
const failedServer = readyServer({ name: 'failed-server', auth: { type: 'none' } })
const thirdServer = readyServer({ name: 'third-server', auth: { type: 'none' } })
- const addServer = vi
- .fn()
- .mockResolvedValueOnce(undefined)
- .mockRejectedValueOnce(new Error('MCP connect failed'))
- .mockResolvedValueOnce(undefined)
+ const addServer = appliedAdmission(async server => {
+ if (server.name === failedServer.name) {
+ throw new Error('MCP connect failed')
+ }
+ })
await expect(
admitDevelopmentMcpServers([firstServer, failedServer, thirdServer], { addServer })
@@ -102,6 +137,68 @@ describe('runAuthoritativeMcpInitialization', () => {
expect(currentState).toBe(priorState)
})
+ it.each(['shutdown', 'a newer initialization'] as const)(
+ 'drops delayed initial discovery after %s while the manager is still null',
+ async invalidation => {
+ const discoveryStarted = deferred()
+ const delayedDiscovery = deferred<McpServerInfo[]>()
+ const candidateManager = {
+ addServer: appliedAdmission(),
+ disconnectAll: vi.fn().mockResolvedValue(undefined),
+ recordAdmissionFailure: vi.fn(),
+ }
+ let shuttingDown = false
+ let currentGeneration = 1
+ const initializationGeneration = currentGeneration
+ let currentManager: typeof candidateManager | null = null
+ const installFleet = vi.fn((manager: typeof candidateManager) => {
+ currentManager = manager
+ })
+ const startPolling = vi.fn()
+ const createManager = vi.fn(() => candidateManager)
+ const replaceFleet = vi.fn((servers: McpServerInfo[]) =>
+ replaceAuthoritativeMcpFleet({
+ servers,
+ previousManager: currentManager,
+ createManager,
+ getAuthToken: vi.fn(),
+ installFleet,
+ onColdStartPublished: startPolling,
+ isFleetLifecycleCurrent: () =>
+ !shuttingDown && currentGeneration === initializationGeneration,
+ })
+ )
+
+ const initialization = runAuthoritativeMcpInitialization({
+ contextRef: 'production',
+ client: {
+ healthCheck: vi.fn().mockResolvedValue(true),
+ listServersByContext: vi.fn(async () => {
+ discoveryStarted.resolve()
+ return delayedDiscovery.promise
+ }),
+ },
+ replaceFleet,
+ isCurrent: () => !shuttingDown && currentGeneration === initializationGeneration,
+ })
+
+ await discoveryStarted.promise
+ expect(currentManager).toBeNull()
+ if (invalidation === 'shutdown') {
+ shuttingDown = true
+ }
+ currentGeneration += 1
+ delayedDiscovery.resolve([readyServer({ auth: { type: 'none' } })])
+ await initialization
+
+ expect(replaceFleet).not.toHaveBeenCalled()
+ expect(createManager).not.toHaveBeenCalled()
+ expect(installFleet).not.toHaveBeenCalled()
+ expect(startPolling).not.toHaveBeenCalled()
+ expect(currentManager).toBeNull()
+ }
+ )
+
it('fails explicitly after readiness retry exhaustion without replacing the prior fleet', async () => {
const replaceFleet = vi.fn()
const sleep = vi.fn().mockResolvedValue(undefined)
@@ -168,6 +265,262 @@ describe('createCoalescedPollRunner', () => {
})
})
+describe('AuthoritativeMcpFleetCoordinator scheduling', () => {
+ it('prunes obsolete unique-name admissions while the global permit is saturated', async () => {
+ const coordinator = new AuthoritativeMcpFleetCoordinator(1, 1, true)
+ const manager = {}
+ const blocker = readyServer({ name: 'blocker', auth: { type: 'none' } })
+ const blockerLease = coordinator.publishSnapshot(manager, [blocker])
+ const blockerStarted = deferred()
+ const releaseBlocker = deferred()
+ const blockerRun = coordinator.runAdmission(manager, blocker.name, blockerLease, async () => {
+ blockerStarted.resolve()
+ await releaseBlocker.promise
+ })
+ await blockerStarted.promise
+
+ const executed: string[] = []
+ const scheduled: Array<Promise<void>> = []
+ for (let revision = 0; revision < 50; revision += 1) {
+ const server = readyServer({
+ name: `churn-${revision}`,
+ auth: { type: 'none' },
+ })
+ const lease = coordinator.publishSnapshot(manager, [blocker, server])
+ scheduled.push(
+ coordinator.runAdmission(manager, server.name, lease, async isCurrent => {
+ expect(isCurrent()).toBe(true)
+ executed.push(server.name)
+ })
+ )
+ }
+
+ const scheduler = coordinator as unknown as {
+ admissionWaiters: unknown[]
+ admissions: WeakMap<object, Map<string, unknown>>
+ admissionTasks: Set<Promise<void>>
+ }
+ const queuedBeforeRelease = scheduler.admissionWaiters.length
+ const slotsBeforeRelease = scheduler.admissions.get(manager)?.size ?? 0
+ const tasksBeforeRelease = scheduler.admissionTasks.size
+
+ await Promise.all(scheduled.slice(0, -1))
+ expect(executed).toEqual([])
+ releaseBlocker.resolve()
+ await Promise.all([blockerRun, ...scheduled])
+
+ expect({
+ queuedBeforeRelease,
+ slotsBeforeRelease,
+ tasksBeforeRelease,
+ }).toEqual({
+ queuedBeforeRelease: 1,
+ slotsBeforeRelease: 2,
+ tasksBeforeRelease: 2,
+ })
+ expect(executed).toEqual(['churn-49'])
+ })
+
+ it('replaces stale queued epochs with only the latest admission per server', async () => {
+ const coordinator = new AuthoritativeMcpFleetCoordinator(1, 1, true)
+ const manager = {}
+ const blocker = readyServer({ name: 'blocker', auth: { type: 'none' } })
+ const blockerLease = coordinator.publishSnapshot(manager, [blocker])
+ const blockerStarted = deferred()
+ const releaseBlocker = deferred()
+ const blockerRun = coordinator.runAdmission(manager, blocker.name, blockerLease, async () => {
+ blockerStarted.resolve()
+ await releaseBlocker.promise
+ })
+ await blockerStarted.promise
+
+ const executedRevisions: number[] = []
+ const scheduled: Array<Promise<void>> = []
+ for (let revision = 0; revision < 25; revision += 1) {
+ const target = readyServer({
+ name: 'target',
+ auth: { type: 'none' },
+ transport: {
+ type: 'streamableHttp',
+ url: `http://target.test/revision-${revision}`,
+ },
+ })
+ const lease = coordinator.publishSnapshot(manager, [blocker, target])
+ scheduled.push(
+ coordinator.runAdmission(manager, target.name, lease, async isCurrent => {
+ expect(isCurrent()).toBe(true)
+ executedRevisions.push(revision)
+ })
+ )
+ }
+
+ expect(executedRevisions).toEqual([])
+ releaseBlocker.resolve()
+ await Promise.all([blockerRun, ...scheduled])
+
+ expect(executedRevisions).toEqual([24])
+ })
+
+ it('does not let a delayed poll publish authority after manager shutdown', async () => {
+ const coordinator = new AuthoritativeMcpFleetCoordinator(1, 1, true)
+ const manager = {}
+ const server = readyServer({ name: 'closed-server', auth: { type: 'none' } })
+ coordinator.publishSnapshot(manager, [server])
+ const delayedSnapshot = deferred<McpServerInfo[]>()
+ const admission = vi.fn()
+ const delayedPoll = delayedSnapshot.promise.then(async servers => {
+ const delayedLease = coordinator.publishSnapshot(manager, servers)
+ await coordinator.runAdmission(manager, server.name, delayedLease, admission)
+ })
+
+ coordinator.closeManager(manager)
+ delayedSnapshot.resolve([server])
+ await delayedPoll
+
+ expect(admission).not.toHaveBeenCalled()
+ })
+
+ it('abandons a hung cleanup permit so later cleanup can progress', async () => {
+ vi.useFakeTimers()
+ try {
+ const coordinator = new AuthoritativeMcpFleetCoordinator(1, 1, true)
+ const neverSettles = new Promise<void>(() => {})
+ const laterCleanup = vi.fn().mockResolvedValue(undefined)
+
+ coordinator.scheduleCleanup(() => neverSettles)
+ coordinator.scheduleCleanup(laterCleanup)
+ await Promise.resolve()
+ expect(laterCleanup).not.toHaveBeenCalled()
+
+ await vi.advanceTimersByTimeAsync(30_000)
+ await vi.waitFor(() => expect(laterCleanup).toHaveBeenCalledTimes(1))
+ await coordinator.drainCleanups()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('observes manager-scheduled cleanup rejection and drains the tracked task', async () => {
+ const { McpClient } = await import('../mcp/client')
+ const error = new Error('cleanup rejected')
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const connect = vi.spyOn(McpClient.prototype, 'connect').mockResolvedValue(undefined)
+ const retire = vi.spyOn(McpClient.prototype, 'retire').mockReturnValue(async () => {
+ throw error
+ })
+ const coordinator = new AuthoritativeMcpFleetCoordinator(1, 1, true)
+ const manager = new McpManager()
+ const server = readyServer({ name: 'cleanup-error-server', auth: { type: 'none' } })
+
+ await manager.addServer(server)
+ await manager.close(cleanup => coordinator.scheduleCleanup(cleanup))
+ await coordinator.drainCleanups()
+
+ expect(errorSpy).toHaveBeenCalledWith('[Main] MCP detached client cleanup failed:', error)
+ expect(retire).toHaveBeenCalledTimes(1)
+ connect.mockRestore()
+ retire.mockRestore()
+ errorSpy.mockRestore()
+ })
+
+ it('waits for a closing admission to schedule its late cleanup before shutdown drain returns', async () => {
+ const { McpClient } = await import('../mcp/client')
+ const connectStarted = deferred()
+ const releaseConnect = deferred()
+ const connect = vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async function (
+ this: any
+ ) {
+ connectStarted.resolve()
+ await releaseConnect.promise
+ this.connected = true
+ this.tools = [{ name: 'late-tool', inputSchema: {}, serverName: 'late-server' }]
+ })
+ const retire = vi.spyOn(McpClient.prototype, 'retire').mockReturnValue(async () => undefined)
+ const coordinator = new AuthoritativeMcpFleetCoordinator(1, 1, true)
+ const manager = new McpManager()
+ const server = readyServer({ name: 'late-server', auth: { type: 'none' } })
+ const lease = coordinator.publishSnapshot(manager, [server])
+ const admission = coordinator.runAdmission(manager, server.name, lease, async isCurrent => {
+ await manager.addServer(server, undefined, {
+ isCurrent,
+ onCommit: vi.fn(),
+ scheduleCleanup: cleanup => coordinator.scheduleCleanup(cleanup),
+ })
+ })
+
+ await connectStarted.promise
+ coordinator.closeManager(manager)
+ await manager.close(cleanup => coordinator.scheduleCleanup(cleanup))
+ let drainReturned = false
+ const drain = coordinator.drainForShutdown().then(() => {
+ drainReturned = true
+ })
+ await Promise.resolve()
+ expect(drainReturned).toBe(false)
+
+ releaseConnect.resolve()
+ await Promise.all([admission, drain])
+
+ expect(connect).toHaveBeenCalledTimes(1)
+ expect(retire).toHaveBeenCalledTimes(1)
+ expect(manager.getConnectedServers()).toEqual([])
+ expect(manager.getKnownServers()).toEqual([])
+ connect.mockRestore()
+ retire.mockRestore()
+ })
+
+ it('bounds shutdown admission drain when transport connect never settles', async () => {
+ vi.useFakeTimers()
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const coordinator = new AuthoritativeMcpFleetCoordinator(1, 1, true, 30_000, 25)
+ const manager = {}
+ const server = readyServer({ name: 'never-settles', auth: { type: 'none' } })
+ const lease = coordinator.publishSnapshot(manager, [server])
+ void coordinator.runAdmission(manager, server.name, lease, () => new Promise<void>(() => {}))
+ await Promise.resolve()
+ coordinator.closeManager(manager)
+
+ const drain = coordinator.drainForShutdown()
+ await vi.advanceTimersByTimeAsync(25)
+ await drain
+
+ expect(warnSpy).toHaveBeenCalledWith(
+ '[Main] MCP admission drain exceeded 25ms; abandoning transport wait'
+ )
+ } finally {
+ warnSpy.mockRestore()
+ vi.useRealTimers()
+ }
+ })
+})
+
+describe('authoritative poll publication fence', () => {
+ it('drops a delayed snapshot when shutdown or a manager swap makes the poll stale', async () => {
+ const pollStarted = deferred()
+ const delayedSnapshot = deferred<{ servers: McpServerInfo[] }>()
+ let current = true
+ const reconcile = vi.fn().mockResolvedValue(undefined)
+ const poll = pollAuthoritativeMcpSnapshotIfCurrent({
+ poll: async () => {
+ pollStarted.resolve()
+ return delayedSnapshot.promise
+ },
+ isCurrent: () => current,
+ reconcile,
+ })
+
+ await pollStarted.promise
+ current = false
+ delayedSnapshot.resolve({
+ servers: [readyServer({ name: 'stale-post-fetch-server' })],
+ })
+ await poll
+
+ expect(reconcile).not.toHaveBeenCalled()
+ })
+})
+
describe('context-mapper polling lifecycle', () => {
it('keeps exactly one interval producer when polling is started again', () => {
vi.useFakeTimers()
@@ -185,17 +538,390 @@ describe('context-mapper polling lifecycle', () => {
})
describe('replaceAuthoritativeMcpFleet', () => {
+ it('publishes a cold manager and healthy peer before a slow peer finishes admission', async () => {
+ const slowServer = readyServer({ name: 'slow-server', auth: { type: 'none' } })
+ const healthyServer = readyServer({ name: 'healthy-server', auth: { type: 'none' } })
+ const slowStarted = deferred()
+ const releaseSlow = deferred()
+ const connected = new Set<string>()
+ const initializationGeneration = 1
+ const currentGeneration = initializationGeneration
+ const candidateManager = {
+ addServer: appliedAdmission(async (server: McpServerInfo) => {
+ if (server.name === slowServer.name) {
+ slowStarted.resolve()
+ await releaseSlow.promise
+ }
+ connected.add(server.name)
+ }),
+ disconnectAll: vi.fn().mockResolvedValue(undefined),
+ recordAdmissionFailure: vi.fn(),
+ }
+ let installedManager: typeof candidateManager | undefined
+ let installedState: Map<string, string> | undefined
+ const initialization = replaceAuthoritativeMcpFleet({
+ servers: [slowServer, healthyServer],
+ previousManager: null,
+ createManager: () => candidateManager,
+ getAuthToken: vi.fn(),
+ maxConcurrency: 2,
+ installFleet: (manager, serverState) => {
+ installedManager = manager
+ installedState = serverState
+ },
+ isFleetLifecycleCurrent: () => currentGeneration === initializationGeneration,
+ })
+
+ try {
+ await slowStarted.promise
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(installedManager).toBe(candidateManager)
+ expect(candidateManager.addServer).toHaveBeenCalledTimes(2)
+ expect(connected).toContain(healthyServer.name)
+ expect(installedState?.get(healthyServer.name)).toBe(JSON.stringify(healthyServer))
+ expect(connected).not.toContain(slowServer.name)
+ expect(installedState?.has(slowServer.name)).toBe(false)
+ } finally {
+ releaseSlow.resolve()
+ await initialization
+ }
+
+ expect(connected).toEqual(new Set([healthyServer.name, slowServer.name]))
+ expect(installedState?.get(slowServer.name)).toBe(JSON.stringify(slowServer))
+ })
+
+ it('bounds concurrent cold-start admission without serializing the fleet', async () => {
+ const servers = Array.from({ length: 5 }, (_, index) =>
+ readyServer({ name: `server-${index}`, auth: { type: 'none' } })
+ )
+ const firstAdmissionStarted = deferred()
+ const releaseAdmissions = deferred()
+ let active = 0
+ let maxActive = 0
+ const candidateManager = {
+ addServer: appliedAdmission(async () => {
+ active += 1
+ maxActive = Math.max(maxActive, active)
+ firstAdmissionStarted.resolve()
+ await releaseAdmissions.promise
+ active -= 1
+ }),
+ disconnectAll: vi.fn().mockResolvedValue(undefined),
+ recordAdmissionFailure: vi.fn(),
+ }
+ const initialization = replaceAuthoritativeMcpFleet({
+ servers,
+ previousManager: null,
+ createManager: () => candidateManager,
+ getAuthToken: vi.fn(),
+ maxConcurrency: 2,
+ installFleet: vi.fn(),
+ })
+
+ try {
+ await firstAdmissionStarted.promise
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(candidateManager.addServer).toHaveBeenCalledTimes(2)
+ expect(maxActive).toBe(2)
+ } finally {
+ releaseAdmissions.resolve()
+ await initialization
+ }
+
+ expect(candidateManager.addServer).toHaveBeenCalledTimes(servers.length)
+ expect(maxActive).toBe(2)
+ })
+
+ it('rejects invalid cold-start concurrency before publishing a candidate', async () => {
+ const candidateManager = {
+ addServer: appliedAdmission(),
+ disconnectAll: vi.fn().mockResolvedValue(undefined),
+ recordAdmissionFailure: vi.fn(),
+ }
+ const createManager = vi.fn(() => candidateManager)
+ const installFleet = vi.fn()
+
+ await expect(
+ replaceAuthoritativeMcpFleet({
+ servers: [readyServer({ auth: { type: 'none' } })],
+ previousManager: null,
+ createManager,
+ getAuthToken: vi.fn(),
+ installFleet,
+ maxConcurrency: 0,
+ })
+ ).rejects.toThrow('MCP fleet reconciliation concurrency must be a positive integer')
+
+ expect(createManager).not.toHaveBeenCalled()
+ expect(installFleet).not.toHaveBeenCalled()
+ expect(candidateManager.addServer).not.toHaveBeenCalled()
+ expect(candidateManager.disconnectAll).not.toHaveBeenCalled()
+ })
+
+ it('keeps polling live after cold publish and prevents revoked in-flight peers from resurfacing', async () => {
+ const slowServer = readyServer({ name: 'slow-server', auth: { type: 'none' } })
+ const healthyServer = readyServer({ name: 'healthy-server', auth: { type: 'none' } })
+ const slowStarted = deferred()
+ const releaseSlow = deferred()
+ const connected = new Set<string>()
+ const known = new Set<string>()
+ const coordinator = new AuthoritativeMcpFleetCoordinator(2, 2, true)
+ const candidateManager = {
+ addServer: vi.fn(
+ async (
+ server: McpServerInfo,
+ _authToken?: string,
+ control?: { isCurrent(): boolean; onCommit(): void }
+ ) => {
+ if (server.name === slowServer.name) {
+ slowStarted.resolve()
+ await releaseSlow.promise
+ }
+ if (control && !control.isCurrent()) return 'stale'
+ connected.add(server.name)
+ known.add(server.name)
+ control?.onCommit()
+ return 'applied'
+ }
+ ),
+ replaceServer: appliedAdmission(),
+ removeServer: vi.fn(async (name: string) => {
+ connected.delete(name)
+ known.delete(name)
+ }),
+ detachServer: vi.fn((name: string) => {
+ connected.delete(name)
+ known.delete(name)
+ return vi.fn().mockResolvedValue(undefined)
+ }),
+ disconnectAll: vi.fn().mockResolvedValue(undefined),
+ getConnectedServers: vi.fn(() => [...connected]),
+ getKnownServers: vi.fn(() => [...known]),
+ recordAdmissionFailure: vi.fn(),
+ }
+ let installedState: Map<string, string> | undefined
+ const pollingStarted = vi.fn()
+ const initialization = replaceAuthoritativeMcpFleet({
+ servers: [slowServer, healthyServer],
+ previousManager: null,
+ createManager: () => candidateManager,
+ getAuthToken: vi.fn(),
+ installFleet: (_manager, serverState) => {
+ installedState = serverState
+ },
+ coordinator,
+ onColdStartPublished: pollingStarted,
+ maxConcurrency: 2,
+ })
+
+ await slowStarted.promise
+ await vi.waitFor(() => expect(connected).toContain(healthyServer.name))
+ expect(pollingStarted).toHaveBeenCalledTimes(1)
+
+ await reconcileAuthoritativeMcpSnapshot({
+ servers: [slowServer, healthyServer],
+ manager: candidateManager,
+ serverState: installedState!,
+ getAuthToken: vi.fn(),
+ coordinator,
+ maxConcurrency: 2,
+ })
+ await reconcileAuthoritativeMcpSnapshot({
+ servers: [slowServer],
+ manager: candidateManager,
+ serverState: installedState!,
+ getAuthToken: vi.fn(),
+ coordinator,
+ maxConcurrency: 2,
+ })
+
+ expect(connected).toEqual(new Set())
+ expect(installedState).toEqual(new Map())
+
+ releaseSlow.resolve()
+ await initialization
+
+ expect(connected).toEqual(new Set([slowServer.name]))
+ expect(known).toEqual(new Set([slowServer.name]))
+ expect(installedState).toEqual(new Map([[slowServer.name, JSON.stringify(slowServer)]]))
+ })
+
+ it('coalesces an identical poll onto a cold admission and retries after its failure', async () => {
+ const server = readyServer({ name: 'retry-server', auth: { type: 'none' } })
+ const firstStarted = deferred()
+ const releaseFirst = deferred()
+ const coordinator = new AuthoritativeMcpFleetCoordinator(2, 2, true)
+ let attempt = 0
+ const known = new Set<string>()
+ const manager = {
+ addServer: vi.fn(
+ async (
+ desired: McpServerInfo,
+ _authToken?: string,
+ control?: { isCurrent(): boolean; onCommit(): void }
+ ) => {
+ attempt += 1
+ if (attempt === 1) {
+ firstStarted.resolve()
+ await releaseFirst.promise
+ throw new Error('first connect failed')
+ }
+ if (control && !control.isCurrent()) return 'stale'
+ known.add(desired.name)
+ control?.onCommit()
+ return 'applied'
+ }
+ ),
+ replaceServer: appliedAdmission(),
+ removeServer: vi.fn(),
+ disconnectAll: vi.fn().mockResolvedValue(undefined),
+ getConnectedServers: vi.fn(() => []),
+ getKnownServers: vi.fn(() => [...known]),
+ recordAdmissionFailure: vi.fn((desired: McpServerInfo) => known.add(desired.name)),
+ }
+ let state: Map<string, string> | undefined
+ const initialization = replaceAuthoritativeMcpFleet({
+ servers: [server],
+ previousManager: null,
+ createManager: () => manager,
+ getAuthToken: vi.fn(),
+ installFleet: (_manager, serverState) => {
+ state = serverState
+ },
+ coordinator,
+ })
+
+ await firstStarted.promise
+ for (let poll = 0; poll < 25; poll += 1) {
+ await reconcileAuthoritativeMcpSnapshot({
+ servers: [server],
+ manager,
+ serverState: state!,
+ getAuthToken: vi.fn(),
+ coordinator,
+ })
+ }
+ expect(manager.addServer).toHaveBeenCalledTimes(1)
+
+ releaseFirst.resolve()
+ await initialization
+ expect(state).toEqual(new Map())
+
+ await reconcileAuthoritativeMcpSnapshot({
+ servers: [server],
+ manager,
+ serverState: state!,
+ getAuthToken: vi.fn(),
+ coordinator,
+ })
+ await vi.waitFor(() => expect(manager.addServer).toHaveBeenCalledTimes(2))
+ expect(state?.get(server.name)).toBe(JSON.stringify(server))
+ })
+
+ it('does not publish an auth failure after a newer snapshot deletes the server', async () => {
+ const server = readyServer({ name: 'stale-auth-server' })
+ const authStarted = deferred()
+ const rejectAuth = deferred<string | undefined>()
+ const coordinator = new AuthoritativeMcpFleetCoordinator(2, 2, true)
+ const manager = {
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(),
+ removeServer: vi.fn(),
+ disconnectAll: vi.fn().mockResolvedValue(undefined),
+ getConnectedServers: vi.fn(() => []),
+ getKnownServers: vi.fn(() => []),
+ recordAdmissionFailure: vi.fn(),
+ }
+ let state: Map<string, string> | undefined
+ const initialization = replaceAuthoritativeMcpFleet({
+ servers: [server],
+ previousManager: null,
+ createManager: () => manager,
+ getAuthToken: vi.fn(async () => {
+ authStarted.resolve()
+ return rejectAuth.promise
+ }),
+ installFleet: (_manager, serverState) => {
+ state = serverState
+ },
+ coordinator,
+ })
+
+ await authStarted.promise
+ await reconcileAuthoritativeMcpSnapshot({
+ servers: [],
+ manager,
+ serverState: state!,
+ getAuthToken: vi.fn(),
+ coordinator,
+ })
+ rejectAuth.reject(new Error('stale auth failure'))
+ await initialization
+
+ expect(manager.recordAdmissionFailure).not.toHaveBeenCalled()
+ expect(manager.addServer).not.toHaveBeenCalled()
+ expect(state).toEqual(new Map())
+ })
+
+ it('removes a failed-only server when the next authoritative snapshot deletes it', async () => {
+ const failedServer = readyServer({ name: 'failed-only-server', auth: { type: 'none' } })
+ const connectError = new Error('MCP connect failed')
+ const knownServers = new Set<string>()
+ const candidateManager = {
+ addServer: vi.fn(async (server: McpServerInfo) => {
+ knownServers.add(server.name)
+ throw connectError
+ }),
+ replaceServer: appliedAdmission(),
+ removeServer: vi.fn(async (serverName: string) => {
+ knownServers.delete(serverName)
+ }),
+ disconnectAll: vi.fn().mockResolvedValue(undefined),
+ getConnectedServers: vi.fn(() => []),
+ getKnownServers: vi.fn(() => [...knownServers]),
+ recordAdmissionFailure: vi.fn((server: McpServerInfo) => {
+ knownServers.add(server.name)
+ }),
+ }
+ let installedState: Map<string, string> | undefined
+
+ await replaceAuthoritativeMcpFleet({
+ servers: [failedServer],
+ previousManager: null,
+ createManager: () => candidateManager,
+ getAuthToken: vi.fn(),
+ installFleet: (_manager, serverState) => {
+ installedState = serverState
+ },
+ })
+
+ expect(installedState).toEqual(new Map())
+ expect(candidateManager.getKnownServers()).toEqual([failedServer.name])
+
+ await reconcileAuthoritativeMcpSnapshot({
+ servers: [],
+ manager: candidateManager,
+ serverState: installedState!,
+ getAuthToken: vi.fn(),
+ })
+
+ expect(candidateManager.removeServer).toHaveBeenCalledWith(failedServer.name)
+ expect(candidateManager.getKnownServers()).toEqual([])
+ })
+
it('publishes healthy servers, retains the failed admission status, and leaves its revision retryable', async () => {
const firstServer = readyServer({ name: 'first-server', auth: { type: 'none' } })
const failedServer = readyServer({ name: 'failed-server', auth: { type: 'none' } })
const thirdServer = readyServer({ name: 'third-server', auth: { type: 'none' } })
const connectError = new Error('MCP connect failed')
const candidateManager = {
- addServer: vi
- .fn()
- .mockResolvedValueOnce(undefined)
- .mockRejectedValueOnce(connectError)
- .mockResolvedValueOnce(undefined),
+ addServer: appliedAdmission(async server => {
+ if (server.name === failedServer.name) throw connectError
+ }),
disconnectAll: vi.fn(),
recordAdmissionFailure: vi.fn(),
}
@@ -226,7 +952,7 @@ describe('replaceAuthoritativeMcpFleet', () => {
it('publishes a failed auth status without recording its revision', async () => {
const authError = new Error('HTTP 503: Service Unavailable')
const candidateManager = {
- addServer: vi.fn(),
+ addServer: appliedAdmission(),
disconnectAll: vi.fn().mockResolvedValue(undefined),
recordAdmissionFailure: vi.fn(),
}
@@ -252,11 +978,13 @@ describe('replaceAuthoritativeMcpFleet', () => {
const firstServer = readyServer({ name: 'first-server', auth: { type: 'none' } })
const failingServer = readyServer({ name: 'failing-server', auth: { type: 'none' } })
const previousManager = {
- addServer: vi.fn(),
+ addServer: appliedAdmission(),
disconnectAll: vi.fn().mockResolvedValue(undefined),
}
const candidateManager = {
- addServer: vi.fn().mockResolvedValueOnce(undefined).mockRejectedValueOnce(connectError),
+ addServer: appliedAdmission(async server => {
+ if (server.name === failingServer.name) throw connectError
+ }),
disconnectAll: vi.fn().mockResolvedValue(undefined),
recordAdmissionFailure: vi.fn(),
}
@@ -272,24 +1000,112 @@ describe('replaceAuthoritativeMcpFleet', () => {
})
).rejects.toBe(connectError)
- expect(candidateManager.addServer).toHaveBeenNthCalledWith(1, firstServer, undefined)
- expect(candidateManager.addServer).toHaveBeenNthCalledWith(2, failingServer, undefined)
+ expect(candidateManager.addServer).toHaveBeenNthCalledWith(
+ 1,
+ firstServer,
+ undefined,
+ expect.any(Object)
+ )
+ expect(candidateManager.addServer).toHaveBeenNthCalledWith(
+ 2,
+ failingServer,
+ undefined,
+ expect.any(Object)
+ )
expect(candidateManager.recordAdmissionFailure).not.toHaveBeenCalled()
expect(installFleet).not.toHaveBeenCalled()
expect(candidateManager.disconnectAll).toHaveBeenCalledTimes(1)
expect(previousManager.disconnectAll).not.toHaveBeenCalled()
})
+ it('rejects a replacement candidate superseded by a newer live snapshot', async () => {
+ const previousServer = readyServer({ name: 'previous-server', auth: { type: 'none' } })
+ const candidateServer = readyServer({ name: 'candidate-server', auth: { type: 'none' } })
+ const newerServer = readyServer({ name: 'newer-server', auth: { type: 'none' } })
+ const previousManager = { disconnectAll: vi.fn().mockResolvedValue(undefined) }
+ const coordinator = new AuthoritativeMcpFleetCoordinator(2, 2, true)
+ coordinator.publishSnapshot(previousManager, [previousServer])
+ const candidateStarted = deferred()
+ const releaseCandidate = deferred()
+ const candidateManager = {
+ addServer: appliedAdmission(async () => {
+ candidateStarted.resolve()
+ await releaseCandidate.promise
+ }),
+ disconnectAll: vi.fn().mockResolvedValue(undefined),
+ recordAdmissionFailure: vi.fn(),
+ }
+ const installFleet = vi.fn()
+ const replacement = replaceAuthoritativeMcpFleet({
+ servers: [candidateServer],
+ previousManager,
+ createManager: () => candidateManager,
+ getAuthToken: vi.fn(),
+ installFleet,
+ coordinator,
+ })
+
+ await candidateStarted.promise
+ coordinator.publishSnapshot(previousManager, [newerServer])
+ releaseCandidate.resolve()
+
+ await expect(replacement).rejects.toThrow(
+ 'MCP fleet replacement candidate was superseded before commit'
+ )
+ expect(installFleet).not.toHaveBeenCalled()
+ expect(candidateManager.disconnectAll).toHaveBeenCalledTimes(1)
+ expect(previousManager.disconnectAll).not.toHaveBeenCalled()
+ })
+
+ it('commits a replacement candidate across an identical live poll', async () => {
+ const previousServer = readyServer({ name: 'previous-server', auth: { type: 'none' } })
+ const candidateServer = readyServer({ name: 'candidate-server', auth: { type: 'none' } })
+ const previousManager = { disconnectAll: vi.fn().mockResolvedValue(undefined) }
+ const coordinator = new AuthoritativeMcpFleetCoordinator(2, 2, true)
+ coordinator.publishSnapshot(previousManager, [previousServer])
+ const candidateStarted = deferred()
+ const releaseCandidate = deferred()
+ const candidateManager = {
+ addServer: appliedAdmission(async () => {
+ candidateStarted.resolve()
+ await releaseCandidate.promise
+ }),
+ disconnectAll: vi.fn().mockResolvedValue(undefined),
+ recordAdmissionFailure: vi.fn(),
+ }
+ const installFleet = vi.fn()
+ const replacement = replaceAuthoritativeMcpFleet({
+ servers: [candidateServer],
+ previousManager,
+ createManager: () => candidateManager,
+ getAuthToken: vi.fn(),
+ installFleet,
+ coordinator,
+ })
+
+ await candidateStarted.promise
+ coordinator.publishSnapshot(previousManager, [previousServer])
+ releaseCandidate.resolve()
+ await replacement
+
+ expect(installFleet).toHaveBeenCalledWith(
+ candidateManager,
+ new Map([[candidateServer.name, JSON.stringify(candidateServer)]])
+ )
+ expect(candidateManager.disconnectAll).not.toHaveBeenCalled()
+ expect(previousManager.disconnectAll).toHaveBeenCalledTimes(1)
+ })
+
it('installs an HTTP 200 empty fleet before retiring the prior fleet', async () => {
const effects: string[] = []
const previousManager = {
- addServer: vi.fn(),
+ addServer: appliedAdmission(),
disconnectAll: vi.fn(async () => {
effects.push('retire-prior')
}),
}
const candidateManager = {
- addServer: vi.fn(),
+ addServer: appliedAdmission(),
disconnectAll: vi.fn(),
recordAdmissionFailure: vi.fn(),
}
@@ -314,11 +1130,11 @@ describe('replaceAuthoritativeMcpFleet', () => {
status: { deployed: true, ready: false, message: 'Deployment is progressing' },
})
const previousManager = {
- addServer: vi.fn(),
+ addServer: appliedAdmission(),
disconnectAll: vi.fn().mockResolvedValue(undefined),
}
const candidateManager = {
- addServer: vi.fn().mockResolvedValue(undefined),
+ addServer: appliedAdmission(),
disconnectAll: vi.fn(),
recordAdmissionFailure: vi.fn(),
}
@@ -334,7 +1150,7 @@ describe('replaceAuthoritativeMcpFleet', () => {
installFleet,
})
- expect(candidateManager.addServer).toHaveBeenCalledWith(notReady, undefined)
+ expect(candidateManager.addServer).toHaveBeenCalledWith(notReady, undefined, expect.any(Object))
expect(installFleet).toHaveBeenCalledWith(
candidateManager,
new Map([[notReady.name, JSON.stringify(notReady)]])
@@ -352,11 +1168,11 @@ describe('replaceAuthoritativeMcpFleet', () => {
},
})
const previousManager = {
- addServer: vi.fn(),
+ addServer: appliedAdmission(),
disconnectAll: vi.fn().mockResolvedValue(undefined),
}
const candidateManager = {
- addServer: vi.fn(),
+ addServer: appliedAdmission(),
disconnectAll: vi.fn(),
recordAdmissionFailure: vi.fn(),
}
@@ -372,7 +1188,11 @@ describe('replaceAuthoritativeMcpFleet', () => {
})
expect(getAuthToken).not.toHaveBeenCalled()
- expect(candidateManager.addServer).toHaveBeenCalledWith(nonAuthoritative, undefined)
+ expect(candidateManager.addServer).toHaveBeenCalledWith(
+ nonAuthoritative,
+ undefined,
+ expect.any(Object)
+ )
expect(installFleet).toHaveBeenCalledWith(
candidateManager,
new Map([[nonAuthoritative.name, JSON.stringify(nonAuthoritative)]])
@@ -415,11 +1235,11 @@ describe('replaceAuthoritativeMcpFleet', () => {
it('keeps the committed fleet when retiring the prior manager fails', async () => {
const cleanupError = new Error('disconnect failed')
const previousManager = {
- addServer: vi.fn(),
+ addServer: appliedAdmission(),
disconnectAll: vi.fn().mockRejectedValue(cleanupError),
}
const candidateManager = {
- addServer: vi.fn(),
+ addServer: appliedAdmission(),
disconnectAll: vi.fn(),
recordAdmissionFailure: vi.fn(),
}
@@ -442,6 +1262,222 @@ describe('replaceAuthoritativeMcpFleet', () => {
})
describe('reconcileAuthoritativeMcpSnapshot', () => {
+ it('detaches every deletion synchronously while bounding deferred cleanup', async () => {
+ const deletedServers = Array.from({ length: 3 }, (_, index) =>
+ readyServer({ name: `deleted-${index}`, auth: { type: 'none' } })
+ )
+ const connected = new Set(deletedServers.map(server => server.name))
+ const known = new Set(connected)
+ const serverState = new Map(deletedServers.map(server => [server.name, JSON.stringify(server)]))
+ const releaseCleanup = deferred()
+ let activeCleanup = 0
+ let maxActiveCleanup = 0
+ const cleanupStarted = vi.fn()
+ const manager = {
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(),
+ removeServer: vi.fn(),
+ detachServer: vi.fn((name: string) => {
+ connected.delete(name)
+ known.delete(name)
+ return async () => {
+ activeCleanup += 1
+ maxActiveCleanup = Math.max(maxActiveCleanup, activeCleanup)
+ cleanupStarted()
+ await releaseCleanup.promise
+ activeCleanup -= 1
+ }
+ }),
+ getConnectedServers: vi.fn(() => [...connected]),
+ getKnownServers: vi.fn(() => [...known]),
+ recordAdmissionFailure: vi.fn(),
+ }
+
+ await reconcileAuthoritativeMcpSnapshot({
+ servers: [],
+ manager,
+ serverState,
+ getAuthToken: vi.fn(),
+ coordinator: new AuthoritativeMcpFleetCoordinator(2, 2, true),
+ })
+
+ expect(manager.detachServer).toHaveBeenCalledTimes(deletedServers.length)
+ expect(connected).toEqual(new Set())
+ expect(known).toEqual(new Set())
+ expect(serverState).toEqual(new Map())
+ expect(cleanupStarted).toHaveBeenCalledTimes(2)
+ expect(maxActiveCleanup).toBe(2)
+
+ releaseCleanup.resolve()
+ await vi.waitFor(() => expect(cleanupStarted).toHaveBeenCalledTimes(deletedServers.length))
+ expect(maxActiveCleanup).toBe(2)
+ })
+
+ it('prioritizes authoritative deletions when every admission worker is slow', async () => {
+ const slowServers = [
+ readyServer({ name: 'slow-server-1', auth: { type: 'none' } }),
+ readyServer({ name: 'slow-server-2', auth: { type: 'none' } }),
+ ]
+ const deletedServer = readyServer({ name: 'deleted-server', auth: { type: 'none' } })
+ const serverState = new Map([[deletedServer.name, JSON.stringify(deletedServer)]])
+ const allAdmissionsStarted = deferred()
+ const releaseAdmissions = deferred()
+ let startedAdmissions = 0
+ const manager = {
+ addServer: appliedAdmission(async () => {
+ startedAdmissions += 1
+ if (startedAdmissions === slowServers.length) {
+ allAdmissionsStarted.resolve()
+ }
+ await releaseAdmissions.promise
+ }),
+ replaceServer: appliedAdmission(),
+ removeServer: vi.fn().mockResolvedValue(undefined),
+ getConnectedServers: vi.fn(() => []),
+ getKnownServers: vi.fn(() => [deletedServer.name]),
+ recordAdmissionFailure: vi.fn(),
+ }
+ const reconciliation = reconcileAuthoritativeMcpSnapshot({
+ servers: slowServers,
+ manager,
+ serverState,
+ getAuthToken: vi.fn(),
+ maxConcurrency: slowServers.length,
+ })
+
+ try {
+ await allAdmissionsStarted.promise
+
+ expect(manager.removeServer).toHaveBeenCalledWith(deletedServer.name)
+ expect(serverState.has(deletedServer.name)).toBe(false)
+ } finally {
+ releaseAdmissions.resolve()
+ await reconciliation
+ }
+ })
+
+ it('reconciles healthy peers and authoritative deletions while another peer is slow', async () => {
+ const slowServer = readyServer({ name: 'slow-server', auth: { type: 'none' } })
+ const healthyServer = readyServer({ name: 'healthy-server', auth: { type: 'none' } })
+ const deletedServer = readyServer({ name: 'deleted-server', auth: { type: 'none' } })
+ const serverState = new Map([[deletedServer.name, JSON.stringify(deletedServer)]])
+ const slowStarted = deferred()
+ const releaseSlow = deferred()
+ const knownServers = new Set([deletedServer.name])
+ const manager = {
+ addServer: appliedAdmission(async (server: McpServerInfo) => {
+ if (server.name === slowServer.name) {
+ slowStarted.resolve()
+ await releaseSlow.promise
+ }
+ knownServers.add(server.name)
+ }),
+ replaceServer: appliedAdmission(),
+ removeServer: vi.fn(async (serverName: string) => {
+ knownServers.delete(serverName)
+ }),
+ getConnectedServers: vi.fn(() => []),
+ getKnownServers: vi.fn(() => [...knownServers]),
+ recordAdmissionFailure: vi.fn(),
+ }
+ const reconciliation = reconcileAuthoritativeMcpSnapshot({
+ servers: [slowServer, healthyServer],
+ manager,
+ serverState,
+ getAuthToken: vi.fn(),
+ maxConcurrency: 2,
+ })
+
+ try {
+ await slowStarted.promise
+ await vi.waitFor(() => {
+ expect(manager.addServer).toHaveBeenCalledWith(healthyServer, undefined, expect.any(Object))
+ expect(manager.removeServer).toHaveBeenCalledWith(deletedServer.name)
+ })
+ expect(serverState.get(healthyServer.name)).toBe(JSON.stringify(healthyServer))
+ expect(serverState.has(deletedServer.name)).toBe(false)
+ expect(knownServers).not.toContain(deletedServer.name)
+ } finally {
+ releaseSlow.resolve()
+ await reconciliation
+ }
+
+ expect(serverState.get(slowServer.name)).toBe(JSON.stringify(slowServer))
+ })
+
+ it('bounds concurrent authoritative snapshot effects without serializing distinct servers', async () => {
+ const servers = Array.from({ length: 5 }, (_, index) =>
+ readyServer({ name: `snapshot-server-${index}`, auth: { type: 'none' } })
+ )
+ const firstEffectStarted = deferred()
+ const releaseEffects = deferred()
+ let active = 0
+ let maxActive = 0
+ const manager = {
+ addServer: appliedAdmission(async () => {
+ active += 1
+ maxActive = Math.max(maxActive, active)
+ firstEffectStarted.resolve()
+ await releaseEffects.promise
+ active -= 1
+ }),
+ replaceServer: appliedAdmission(),
+ removeServer: vi.fn(),
+ getConnectedServers: vi.fn(() => []),
+ getKnownServers: vi.fn(() => []),
+ recordAdmissionFailure: vi.fn(),
+ }
+ const reconciliation = reconcileAuthoritativeMcpSnapshot({
+ servers,
+ manager,
+ serverState: new Map(),
+ getAuthToken: vi.fn(),
+ maxConcurrency: 2,
+ })
+
+ try {
+ await firstEffectStarted.promise
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(manager.addServer).toHaveBeenCalledTimes(2)
+ expect(maxActive).toBe(2)
+ } finally {
+ releaseEffects.resolve()
+ await reconciliation
+ }
+
+ expect(manager.addServer).toHaveBeenCalledTimes(servers.length)
+ expect(maxActive).toBe(2)
+ })
+
+ it('rejects invalid snapshot concurrency before reading or mutating manager state', async () => {
+ const manager = {
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(),
+ removeServer: vi.fn(),
+ getConnectedServers: vi.fn(() => []),
+ getKnownServers: vi.fn(() => []),
+ recordAdmissionFailure: vi.fn(),
+ }
+
+ await expect(
+ reconcileAuthoritativeMcpSnapshot({
+ servers: [readyServer({ auth: { type: 'none' } })],
+ manager,
+ serverState: new Map(),
+ getAuthToken: vi.fn(),
+ maxConcurrency: 0,
+ })
+ ).rejects.toThrow('MCP fleet reconciliation concurrency must be a positive integer')
+
+ expect(manager.getConnectedServers).not.toHaveBeenCalled()
+ expect(manager.getKnownServers).not.toHaveBeenCalled()
+ expect(manager.addServer).not.toHaveBeenCalled()
+ expect(manager.replaceServer).not.toHaveBeenCalled()
+ expect(manager.removeServer).not.toHaveBeenCalled()
+ })
+
it('connects a ready desired candidate before retiring the previous connection', async () => {
const previous = readyServer({ auth: { type: 'none' } })
const modified = readyServer({
@@ -452,10 +1488,13 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
const connectError = new Error('replacement connect failed')
const serverState = new Map([[previous.name, JSON.stringify(previous)]])
const manager = {
- addServer: vi.fn(),
- replaceServer: vi.fn().mockRejectedValueOnce(connectError).mockResolvedValueOnce(undefined),
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(
+ vi.fn().mockRejectedValueOnce(connectError).mockResolvedValue(undefined)
+ ),
removeServer: vi.fn(),
getConnectedServers: vi.fn(() => [previous.name]),
+ getKnownServers: vi.fn(() => [previous.name]),
recordAdmissionFailure: vi.fn(),
}
const options = {
@@ -467,7 +1506,7 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
await expect(reconcileAuthoritativeMcpSnapshot(options)).resolves.toBeUndefined()
- expect(manager.replaceServer).toHaveBeenCalledWith(modified, undefined)
+ expect(manager.replaceServer).toHaveBeenCalledWith(modified, undefined, expect.any(Object))
expect(manager.removeServer).not.toHaveBeenCalled()
expect(manager.addServer).not.toHaveBeenCalled()
expect(manager.recordAdmissionFailure).not.toHaveBeenCalled()
@@ -490,10 +1529,11 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
})
const serverState = new Map([[previous.name, JSON.stringify(previous)]])
const manager = {
- addServer: vi.fn(),
- replaceServer: vi.fn(),
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(),
removeServer: vi.fn(),
getConnectedServers: vi.fn(() => [previous.name]),
+ getKnownServers: vi.fn(() => [previous.name]),
recordAdmissionFailure: vi.fn(),
}
@@ -522,14 +1562,15 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
})
const serverState = new Map([[previous.name, JSON.stringify(previous)]])
const manager = {
- addServer: vi.fn(async () => {
+ addServer: appliedAdmission(async () => {
effects.push('mark-not-ready')
}),
- replaceServer: vi.fn(),
+ replaceServer: appliedAdmission(),
removeServer: vi.fn(async () => {
effects.push('remove')
}),
getConnectedServers: vi.fn(() => [previous.name]),
+ getKnownServers: vi.fn(() => [previous.name]),
recordAdmissionFailure: vi.fn(),
}
@@ -541,7 +1582,7 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
})
expect(effects).toEqual(['remove', 'mark-not-ready'])
- expect(manager.addServer).toHaveBeenCalledWith(notReady, undefined)
+ expect(manager.addServer).toHaveBeenCalledWith(notReady, undefined, expect.any(Object))
expect(serverState.get(previous.name)).toBe(JSON.stringify(notReady))
})
@@ -552,10 +1593,11 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
})
const serverState = new Map([[previous.name, JSON.stringify(previous)]])
const manager = {
- addServer: vi.fn().mockResolvedValue(undefined),
- replaceServer: vi.fn(),
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(),
removeServer: vi.fn().mockResolvedValue(undefined),
getConnectedServers: vi.fn(() => [previous.name]),
+ getKnownServers: vi.fn(() => [previous.name]),
recordAdmissionFailure: vi.fn(),
}
@@ -567,7 +1609,7 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
})
expect(manager.removeServer).toHaveBeenCalledWith(previous.name)
- expect(manager.addServer).toHaveBeenCalledWith(legacyNotReady, undefined)
+ expect(manager.addServer).toHaveBeenCalledWith(legacyNotReady, undefined, expect.any(Object))
})
it('admits an unconnected server when its observed readiness becomes true', async () => {
@@ -581,10 +1623,11 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
})
const serverState = new Map([[notReady.name, JSON.stringify(notReady)]])
const manager = {
- addServer: vi.fn().mockResolvedValue(undefined),
- replaceServer: vi.fn(),
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(),
removeServer: vi.fn(),
getConnectedServers: vi.fn(() => []),
+ getKnownServers: vi.fn(() => [notReady.name]),
recordAdmissionFailure: vi.fn(),
}
@@ -596,7 +1639,7 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
})
expect(manager.removeServer).not.toHaveBeenCalled()
- expect(manager.addServer).toHaveBeenCalledWith(ready, undefined)
+ expect(manager.addServer).toHaveBeenCalledWith(ready, undefined, expect.any(Object))
expect(serverState.get(ready.name)).toBe(JSON.stringify(ready))
})
@@ -611,10 +1654,11 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
})
const serverState = new Map<string, string>()
const manager = {
- addServer: vi.fn(),
- replaceServer: vi.fn(),
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(),
removeServer: vi.fn(),
getConnectedServers: vi.fn(() => []),
+ getKnownServers: vi.fn(() => []),
recordAdmissionFailure: vi.fn(),
}
const getAuthToken = vi.fn()
@@ -627,7 +1671,7 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
})
expect(getAuthToken).not.toHaveBeenCalled()
- expect(manager.addServer).toHaveBeenCalledWith(nonAuthoritative, undefined)
+ expect(manager.addServer).toHaveBeenCalledWith(nonAuthoritative, undefined, expect.any(Object))
expect(manager.removeServer).not.toHaveBeenCalled()
expect(serverState.get(nonAuthoritative.name)).toBe(JSON.stringify(nonAuthoritative))
})
@@ -645,10 +1689,11 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
})
const serverState = new Map([[previous.name, JSON.stringify(previous)]])
const manager = {
- addServer: vi.fn(),
- replaceServer: vi.fn(),
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(),
removeServer: vi.fn().mockResolvedValue(undefined),
getConnectedServers: vi.fn(() => [previous.name]),
+ getKnownServers: vi.fn(() => [previous.name]),
recordAdmissionFailure: vi.fn(),
}
const getAuthToken = vi.fn()
@@ -662,7 +1707,7 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
expect(manager.removeServer).toHaveBeenCalledWith(previous.name)
expect(getAuthToken).not.toHaveBeenCalled()
- expect(manager.addServer).toHaveBeenCalledWith(modified, undefined)
+ expect(manager.addServer).toHaveBeenCalledWith(modified, undefined, expect.any(Object))
expect(serverState.get(modified.name)).toBe(JSON.stringify(modified))
})
@@ -683,10 +1728,11 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
} as McpServerInfo
const serverState = new Map([[current.name, JSON.stringify(previousWithDifferentKeyOrder)]])
const manager = {
- addServer: vi.fn(),
- replaceServer: vi.fn(),
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(),
removeServer: vi.fn(),
getConnectedServers: vi.fn(() => [current.name]),
+ getKnownServers: vi.fn(() => [current.name]),
recordAdmissionFailure: vi.fn(),
}
@@ -718,14 +1764,15 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
})
const serverState = new Map([[previous.name, JSON.stringify(previous)]])
const manager = {
- addServer: vi.fn(async () => {
+ addServer: appliedAdmission(async () => {
effects.push('add')
}),
- replaceServer: vi.fn(),
+ replaceServer: appliedAdmission(),
removeServer: vi.fn(async () => {
effects.push('remove')
}),
getConnectedServers: vi.fn(() => [previous.name]),
+ getKnownServers: vi.fn(() => [previous.name]),
recordAdmissionFailure: vi.fn(),
}
@@ -744,10 +1791,11 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
const previous = readyServer({ auth: { type: 'none' } })
const serverState = new Map([[previous.name, JSON.stringify(previous)]])
const manager = {
- addServer: vi.fn(),
- replaceServer: vi.fn(),
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(),
removeServer: vi.fn().mockResolvedValue(undefined),
getConnectedServers: vi.fn(() => [previous.name]),
+ getKnownServers: vi.fn(() => [previous.name]),
recordAdmissionFailure: vi.fn(),
}
@@ -767,10 +1815,11 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
const serverState = new Map<string, string>()
const connectError = new Error('MCP connect failed')
const manager = {
- addServer: vi.fn().mockRejectedValueOnce(connectError).mockResolvedValueOnce(undefined),
- replaceServer: vi.fn(),
+ addServer: appliedAdmission(vi.fn().mockRejectedValueOnce(connectError)),
+ replaceServer: appliedAdmission(),
removeServer: vi.fn(),
getConnectedServers: vi.fn(() => []),
+ getKnownServers: vi.fn(() => []),
recordAdmissionFailure: vi.fn(),
}
const options = {
@@ -794,10 +1843,11 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
const serverState = new Map<string, string>()
const authError = new Error('auth discovery failed')
const manager = {
- addServer: vi.fn(),
- replaceServer: vi.fn(),
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(),
removeServer: vi.fn(),
getConnectedServers: vi.fn(() => []),
+ getKnownServers: vi.fn(() => []),
recordAdmissionFailure: vi.fn(),
}
diff --git a/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts b/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts
index c474903d1..bb3d7dc54 100644
--- a/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts
+++ b/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts
@@ -3,12 +3,15 @@ import { McpClient } from '../../mcp/client'
const sdkState = vi.hoisted(() => ({
closeCalls: [] as unknown[][],
+ closeQueue: [] as Array<() => unknown>,
connectCalls: [] as unknown[][],
connectQueue: [] as Array<() => unknown>,
callToolCalls: [] as unknown[][],
callToolQueue: [] as Array<() => unknown>,
listToolsCalls: [] as unknown[][],
listToolsQueue: [] as Array<() => unknown>,
+ transportCloseCalls: [] as unknown[][],
+ transportCloseQueue: [] as Array<() => unknown>,
}))
vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
@@ -21,6 +24,8 @@ vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
async close(...args: unknown[]) {
sdkState.closeCalls.push(args)
+ const next = sdkState.closeQueue.shift()
+ if (next) return next()
}
async listTools(...args: unknown[]) {
@@ -41,13 +46,21 @@ vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({
StreamableHTTPClientTransport: class MockStreamableHTTP {
- close = vi.fn().mockResolvedValue(undefined)
+ async close(...args: unknown[]) {
+ sdkState.transportCloseCalls.push([this, ...args])
+ const next = sdkState.transportCloseQueue.shift()
+ if (next) return next()
+ }
},
}))
vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({
SSEClientTransport: class MockSSE {
- close = vi.fn().mockResolvedValue(undefined)
+ async close(...args: unknown[]) {
+ sdkState.transportCloseCalls.push([this, ...args])
+ const next = sdkState.transportCloseQueue.shift()
+ if (next) return next()
+ }
},
}))
@@ -61,15 +74,37 @@ function client(): McpClient {
})
}
+function deferred<T = void>(): {
+ promise: Promise<T>
+ resolve: (value: T) => void
+ reject: (error: unknown) => void
+} {
+ let resolve!: (value: T) => void
+ let reject!: (error: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
+}
+
+function retirePermanently(client: McpClient): Promise<void> {
+ const cleanup = client.retire()
+ return cleanup()
+}
+
describe('McpClient SDK request timeouts', () => {
beforeEach(() => {
sdkState.closeCalls.length = 0
+ sdkState.closeQueue.length = 0
sdkState.connectCalls.length = 0
sdkState.connectQueue.length = 0
sdkState.callToolCalls.length = 0
sdkState.callToolQueue.length = 0
sdkState.listToolsCalls.length = 0
sdkState.listToolsQueue.length = 0
+ sdkState.transportCloseCalls.length = 0
+ sdkState.transportCloseQueue.length = 0
})
afterEach(() => {
@@ -194,7 +229,7 @@ describe('McpClient SDK request timeouts', () => {
expect(sdkState.listToolsCalls[0][1]).toEqual(
expect.objectContaining({ timeout: 5_000, maxTotalTimeout: 5_000 })
)
- expect(sdkState.closeCalls).toHaveLength(1)
+ expect(sdkState.transportCloseCalls).toHaveLength(1)
})
it('abandons SDK connect when the caller budget expires during handshake', async () => {
@@ -210,7 +245,7 @@ describe('McpClient SDK request timeouts', () => {
expect(c.isConnected).toBe(false)
expect(sdkState.connectCalls).toHaveLength(1)
expect(sdkState.listToolsCalls).toHaveLength(0)
- expect(sdkState.closeCalls).toHaveLength(1)
+ expect(sdkState.transportCloseCalls).toHaveLength(1)
})
it('abandons SDK connect when the caller signal aborts during handshake', async () => {
@@ -225,6 +260,204 @@ describe('McpClient SDK request timeouts', () => {
expect(c.isConnected).toBe(false)
expect(sdkState.connectCalls).toHaveLength(1)
expect(sdkState.listToolsCalls).toHaveLength(0)
- expect(sdkState.closeCalls).toHaveLength(1)
+ expect(sdkState.transportCloseCalls).toHaveLength(1)
+ })
+
+ it('detaches immediately and closes the owned transport when SDK protocol close hangs', async () => {
+ const releaseClose = deferred()
+ sdkState.transportCloseQueue.push(() => releaseClose.promise)
+ const c = client()
+ await c.connect()
+
+ const disconnecting = c.disconnect()
+ await Promise.resolve()
+
+ expect(c.isConnected).toBe(false)
+ expect(c.availableTools).toEqual([])
+ expect(sdkState.closeCalls).toHaveLength(0)
+ expect(sdkState.transportCloseCalls).toHaveLength(1)
+
+ releaseClose.resolve()
+ await expect(disconnecting).resolves.toBeUndefined()
+ })
+
+ it('does not reconnect or replay a tool after permanent close during the retry delay', async () => {
+ vi.useFakeTimers()
+ sdkState.callToolQueue.push(
+ () => {
+ throw Object.assign(new Error('session not found'), { code: -32003 })
+ },
+ () => ({ content: [{ type: 'text', text: 'must-not-run' }] })
+ )
+ const c = client()
+ await c.connect()
+
+ const pending = c.callTool('write', { value: 'side-effect' }, { timeoutMs: 30_000 })
+ const assertion = expect(pending).rejects.toThrow(/closed/)
+ await vi.advanceTimersByTimeAsync(0)
+ await retirePermanently(c)
+ await vi.advanceTimersByTimeAsync(1000)
+
+ await assertion
+ expect(sdkState.connectCalls).toHaveLength(1)
+ expect(sdkState.callToolCalls).toHaveLength(1)
+ expect(c.isConnected).toBe(false)
+ })
+
+ it('discards a successful tool result that arrives after permanent close', async () => {
+ let resolveCall!: (value: unknown) => void
+ const callResult = new Promise<unknown>(resolve => {
+ resolveCall = resolve
+ })
+ sdkState.callToolQueue.push(() => callResult)
+ const c = client()
+ await c.connect()
+
+ const pending = c.callTool('write', { value: 'side-effect' })
+ const assertion = expect(pending).rejects.toThrow(/closed/)
+ await vi.waitFor(() => expect(sdkState.callToolCalls).toHaveLength(1))
+ await retirePermanently(c)
+ resolveCall({ content: [{ type: 'text', text: 'late-success' }] })
+
+ await assertion
+ expect(sdkState.connectCalls).toHaveLength(1)
+ expect(sdkState.callToolCalls).toHaveLength(1)
+ expect(c.isConnected).toBe(false)
+ })
+
+ it('starts transport close synchronously when permanently retired', async () => {
+ const c = client()
+ await c.connect()
+
+ const cleanup = c.retire()
+
+ expect(c.isConnected).toBe(false)
+ expect(sdkState.transportCloseCalls).toHaveLength(1)
+ await cleanup()
+ expect(sdkState.transportCloseCalls).toHaveLength(1)
+ })
+
+ it('discards a retry result that arrives after permanent close', async () => {
+ vi.useFakeTimers()
+ const retryResult = deferred<unknown>()
+ sdkState.callToolQueue.push(
+ () => {
+ throw Object.assign(new Error('session not found'), { code: -32003 })
+ },
+ () => retryResult.promise
+ )
+ const c = client()
+ await c.connect()
+
+ const pending = c.callTool('write', { value: 'side-effect' }, { timeoutMs: 30_000 })
+ const assertion = expect(pending).rejects.toThrow(/closed/)
+ await vi.advanceTimersByTimeAsync(1000)
+ await vi.waitFor(() => expect(sdkState.callToolCalls).toHaveLength(2))
+
+ await retirePermanently(c)
+ retryResult.resolve({ content: [{ type: 'text', text: 'late-retry-success' }] })
+
+ await assertion
+ expect(sdkState.callToolCalls).toHaveLength(2)
+ expect(c.isConnected).toBe(false)
+ })
+
+ it('invalidates a reconnect handshake when permanent close arrives in flight', async () => {
+ vi.useFakeTimers()
+ const reconnectHandshake = deferred()
+ sdkState.callToolQueue.push(
+ () => {
+ throw Object.assign(new Error('session not found'), { code: -32003 })
+ },
+ () => ({ content: [{ type: 'text', text: 'must-not-run' }] })
+ )
+ const c = client()
+ await c.connect()
+ sdkState.connectQueue.push(() => reconnectHandshake.promise)
+
+ const pending = c.callTool('write', { value: 'side-effect' }, { timeoutMs: 30_000 })
+ const assertion = expect(pending).rejects.toThrow(/closed|superseded/)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(sdkState.connectCalls).toHaveLength(2)
+
+ const closing = retirePermanently(c)
+ reconnectHandshake.resolve()
+ await closing
+ await vi.advanceTimersByTimeAsync(0)
+
+ await assertion
+ expect(sdkState.callToolCalls).toHaveLength(1)
+ expect(c.isConnected).toBe(false)
+ expect(sdkState.transportCloseCalls).toHaveLength(2)
+ expect(new Set(sdkState.transportCloseCalls.map(([transport]) => transport)).size).toBe(2)
+ })
+
+ it('does not publish tools discovered after permanent close', async () => {
+ const discovery = deferred<{
+ tools: Array<{ name: string; description: string; inputSchema: Record<string, unknown> }>
+ }>()
+ sdkState.listToolsQueue.push(() => discovery.promise)
+ const c = client()
+
+ const pending = c.connect()
+ await vi.waitFor(() => expect(sdkState.listToolsCalls).toHaveLength(1))
+ const closing = retirePermanently(c)
+ discovery.resolve({
+ tools: [{ name: 'stale-tool', description: 'stale', inputSchema: {} }],
+ })
+
+ await closing
+ await expect(pending).rejects.toThrow(/closed/)
+ expect(c.availableTools).toEqual([])
+ expect(c.isConnected).toBe(false)
+ expect(sdkState.transportCloseCalls).toHaveLength(1)
+ })
+
+ it('does not let an old tools/list failure erase a reconnected tool cache', async () => {
+ const c = client()
+ await c.connect()
+
+ const staleDiscovery = deferred<{
+ tools: Array<{ name: string; description: string; inputSchema: Record<string, unknown> }>
+ }>()
+ sdkState.listToolsQueue.push(
+ () => staleDiscovery.promise,
+ () => ({
+ tools: [{ name: 'fresh-tool', description: 'fresh', inputSchema: {} }],
+ })
+ )
+ const staleRefresh = c.listTools()
+ await vi.waitFor(() => expect(sdkState.listToolsCalls).toHaveLength(2))
+
+ await c.reconnect()
+ expect(c.availableTools.map(tool => tool.name)).toEqual(['fresh-tool'])
+
+ staleDiscovery.reject(new Error('old tools/list failed'))
+ await expect(staleRefresh).rejects.toThrow(/superseded/)
+ expect(c.availableTools.map(tool => tool.name)).toEqual(['fresh-tool'])
+ expect(c.isConnected).toBe(true)
+ })
+
+ it('does not report a successful probe from a permanently closed connection', async () => {
+ const c = client()
+ await c.connect()
+ const staleProbe = deferred<{
+ tools: Array<{ name: string; description: string; inputSchema: Record<string, unknown> }>
+ }>()
+ sdkState.listToolsQueue.push(() => staleProbe.promise)
+
+ const probing = c.probeTools()
+ await vi.waitFor(() => expect(sdkState.listToolsCalls).toHaveLength(2))
+ const closing = retirePermanently(c)
+ staleProbe.resolve({
+ tools: [{ name: 'stale-tool', description: 'stale', inputSchema: {} }],
+ })
+
+ await closing
+ await expect(probing).resolves.toEqual({
+ ok: false,
+ error: expect.objectContaining({ message: expect.stringMatching(/closed/) }),
+ stale: true,
+ })
})
})
diff --git a/mcp-host/src/__tests__/mcp/mcpTransportClose.contract.test.ts b/mcp-host/src/__tests__/mcp/mcpTransportClose.contract.test.ts
new file mode 100644
index 000000000..928e4d169
--- /dev/null
+++ b/mcp-host/src/__tests__/mcp/mcpTransportClose.contract.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it, vi } from 'vitest'
+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 { EventSource } from 'eventsource'
+
+function deferred<T>(): {
+ promise: Promise<T>
+ resolve: (value: T) => void
+} {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>(resolvePromise => {
+ resolve = resolvePromise
+ })
+ return { promise, resolve }
+}
+
+describe('installed MCP transport close contract', () => {
+ it('aborts Streamable HTTP I/O and notifies close before its promise settles', async () => {
+ const transport = new StreamableHTTPClientTransport(new URL('http://mcp.test/mcp'))
+ const onclose = vi.fn()
+ transport.onclose = onclose
+ await transport.start()
+ const controller = (
+ transport as unknown as {
+ _abortController?: AbortController
+ }
+ )._abortController
+
+ const closing = transport.close()
+
+ expect(controller?.signal.aborted).toBe(true)
+ expect(onclose).toHaveBeenCalledOnce()
+ await expect(closing).resolves.toBeUndefined()
+ })
+
+ it('synchronously detaches the real SDK Client through the transport onclose hook', async () => {
+ const client = new Client(
+ { name: 'transport-close-contract', version: '1.0.0' },
+ { capabilities: {} }
+ )
+ const transport = new StreamableHTTPClientTransport(new URL('http://mcp.test/mcp'), {
+ sessionId: 'existing-session',
+ })
+ await client.connect(transport)
+ expect(client.transport).toBe(transport)
+
+ const closing = transport.close()
+
+ expect(client.transport).toBeUndefined()
+ await expect(closing).resolves.toBeUndefined()
+ })
+
+ it('aborts SSE POST and EventSource receive I/O before its promise settles', async () => {
+ const receiveStarted = deferred<AbortSignal>()
+ const pendingFetch = vi.fn(
+ (_input: string | URL | Request, init?: RequestInit): Promise<Response> =>
+ new Promise((_resolve, reject) => {
+ const signal = init?.signal
+ if (!signal) {
+ reject(new Error('EventSource fetch did not receive an AbortSignal'))
+ return
+ }
+ receiveStarted.resolve(signal)
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true })
+ })
+ )
+ const transport = new SSEClientTransport(new URL('http://mcp.test/sse'), {
+ eventSourceInit: {
+ fetch: pendingFetch as typeof fetch,
+ },
+ })
+ const onclose = vi.fn()
+ transport.onclose = onclose
+ const starting = transport.start()
+ void starting.catch(() => undefined)
+ const receiveSignal = await receiveStarted.promise
+ const transportController = (
+ transport as unknown as {
+ _abortController?: AbortController
+ }
+ )._abortController
+ const eventSource = (
+ transport as unknown as {
+ _eventSource?: EventSource
+ }
+ )._eventSource
+
+ const closing = transport.close()
+
+ expect(transportController?.signal.aborted).toBe(true)
+ expect(receiveSignal.aborted).toBe(true)
+ expect(eventSource?.readyState).toBe(EventSource.CLOSED)
+ expect(onclose).toHaveBeenCalledOnce()
+ await expect(closing).resolves.toBeUndefined()
+ })
+})
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index 94193f251..cad8c1607 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -65,6 +65,14 @@ import { clerumPromptCacheInvalidationsTotal } from './llm/promptCacheMetrics'
import { ALL_PROVIDERS, type LlmProvider, descriptorFor, isLlmProvider } from './llm/registryCore'
import './logger'
import { McpManager } from './mcp'
+import {
+ AuthoritativeMcpFleetCoordinator,
+ DEFAULT_MCP_FLEET_RECONCILE_MAX_CONCURRENCY,
+ pollAuthoritativeMcpSnapshotIfCurrent,
+ reconcileAuthoritativeMcpSnapshot,
+ replaceAuthoritativeMcpFleet,
+ runAuthoritativeMcpInitialization,
+} from './mcp/authoritativeFleet'
import { startMcpInitializationInBackground } from './mcpBackgroundInit'
import { IncomingMessageHandler, PendingTaskEntry } from './messageHandler'
import { maybeCreatePluginWorkloadSdkServer } from './pluginWorkloadSdk/server'
@@ -174,6 +182,7 @@ let agent: AgentStateMachine | null = null
let cronScheduler: CronScheduler | null = null
let sessionProcessor: SessionProcessor | null = null
let isShuttingDown = false
+let mcpInitializationGeneration = 0
// Stage 3 (stateless-agents) — heartbeat emitter + DRAINING fence holder.
let statelessHeartbeat: StatelessHeartbeat | null = null
@@ -740,137 +749,11 @@ async function initializeProvider(
}
}
-/**
- * Initialize MCP servers for the host's context using skill-mapper.
- */
-export async function runAuthoritativeMcpInitialization(options: {
- contextRef: string
- client: Pick<ContextMapperClient, 'healthCheck' | 'listServersByContext'>
- replaceFleet: (servers: McpServerInfo[]) => Promise<void>
- sleep?: (milliseconds: number) => Promise<void>
- maxRetries?: number
-}): Promise<void> {
- const maxRetries = options.maxRetries ?? 5
- const sleep =
- options.sleep ??
- ((milliseconds: number) => new Promise(resolve => setTimeout(resolve, milliseconds)))
-
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
- const ready = await options.client.healthCheck()
- if (ready) {
- const servers = await options.client.listServersByContext(options.contextRef)
- await options.replaceFleet(servers)
- return
- }
-
- console.log(`[Main] Waiting for Context Mapper... (${attempt}/${maxRetries})`)
- if (attempt < maxRetries) {
- await sleep(2000)
- }
- }
-
- throw new Error(`Context Mapper was not ready after ${maxRetries} attempts`)
-}
-
-interface AuthoritativeMcpFleetManager {
- addServer(server: McpServerInfo, authToken?: string): Promise<void>
- disconnectAll(): Promise<void>
- recordAdmissionFailure(server: McpServerInfo, error: unknown): void
-}
-
-async function resolveRequiredMcpAuthToken(
- server: McpServerInfo,
- getAuthToken: (serverName: string) => Promise<string | undefined>
-): Promise<string | undefined> {
- if (
- !server.enabled ||
- !server.status?.ready ||
- server.status.authoritative === false ||
- !server.auth?.secretRef
- ) {
- return undefined
- }
-
- const authToken = await getAuthToken(server.name)
- if (!authToken) {
- throw new Error(`Required auth token is unavailable for MCP server ${server.name}`)
- }
- return authToken
-}
-
-/**
- * Apply an authoritative MCP fleet snapshot with per-server admission.
- *
- * On cold start, healthy and intentionally skipped servers are published
- * immediately while failed revisions remain retryable. When a prior manager
- * exists, replacement remains atomic: any admission failure rejects and
- * cleans up the candidate without retiring the live fleet.
- */
-export async function replaceAuthoritativeMcpFleet<
- TManager extends AuthoritativeMcpFleetManager,
->(options: {
- servers: McpServerInfo[]
- previousManager: { disconnectAll(): Promise<void> } | null
- createManager: () => TManager
- getAuthToken: (serverName: string) => Promise<string | undefined>
- installFleet: (manager: TManager, serverState: Map<string, string>) => void
-}): Promise<void> {
- const nextManager = options.createManager()
- const nextServerState = new Map<string, string>()
- const admissionFailures: unknown[] = []
-
- try {
- for (const server of options.servers) {
- let authToken: string | undefined
- try {
- authToken = await resolveRequiredMcpAuthToken(server, options.getAuthToken)
- } catch (error) {
- // Auth discovery fails before addServer can own the status transition.
- nextManager.recordAdmissionFailure(server, error)
- admissionFailures.push(error)
- console.error(`[Main] MCP server admission failed; will retry: ${server.name}`, error)
- continue
- }
-
- try {
- await nextManager.addServer(server, authToken)
- nextServerState.set(server.name, JSON.stringify(server))
- } catch (error) {
- // addServer owns connection-failure status. Avoid recording the same
- // transition twice while keeping the desired revision retryable.
- admissionFailures.push(error)
- console.error(`[Main] MCP server admission failed; will retry: ${server.name}`, error)
- }
- }
-
- // Cold start may publish healthy peers so HCC readiness is independent of
- // full-fleet convergence. A live prior fleet is safer to preserve
- // atomically until its complete replacement candidate is admitted.
- if (options.previousManager && admissionFailures.length > 0) {
- throw admissionFailures[0]
- }
-
- options.installFleet(nextManager, nextServerState)
- } catch (error) {
- try {
- await nextManager.disconnectAll()
- } catch (cleanupError) {
- console.error('[Main] Failed to clean up rejected MCP fleet candidate:', cleanupError)
- }
- throw error
- }
-
- // installFleet is the commit point. Once the accepted candidate is visible,
- // failure to retire stale connections must not invalidate or retry the
- // already-committed authoritative fleet.
- if (options.previousManager && options.previousManager !== nextManager) {
- try {
- await options.previousManager.disconnectAll()
- } catch (cleanupError) {
- console.error('[Main] Failed to retire previous MCP fleet after replacement:', cleanupError)
- }
- }
-}
+const mcpFleetCoordinator = new AuthoritativeMcpFleetCoordinator(
+ DEFAULT_MCP_FLEET_RECONCILE_MAX_CONCURRENCY,
+ DEFAULT_MCP_FLEET_RECONCILE_MAX_CONCURRENCY,
+ true
+)
/**
* Admit development MCP servers independently.
@@ -893,163 +776,17 @@ export async function admitDevelopmentMcpServers(
}
}
-interface AuthoritativeMcpSnapshotManager {
- addServer(server: McpServerInfo, authToken?: string): Promise<void>
- replaceServer(server: McpServerInfo, authToken?: string): Promise<void>
- removeServer(serverName: string): Promise<void>
- getConnectedServers(): string[]
- recordAdmissionFailure(server: McpServerInfo, error: unknown): void
-}
-
-function canonicalJson(value: unknown): string {
- if (Array.isArray(value)) {
- return `[${value.map(canonicalJson).join(',')}]`
- }
- if (value !== null && typeof value === 'object') {
- const entries = Object.entries(value as Record<string, unknown>)
- .filter(([, entryValue]) => entryValue !== undefined)
- .sort(([left], [right]) => left.localeCompare(right))
- return `{${entries
- .map(([key, entryValue]) => `${JSON.stringify(key)}:${canonicalJson(entryValue)}`)
- .join(',')}}`
- }
- return JSON.stringify(value) ?? 'null'
-}
-
-function mcpServerDesiredRevision(server: McpServerInfo): string {
- const { status: _observedStatus, ...desired } = server
- return canonicalJson(desired)
-}
-
-/**
- * Apply one authoritative inventory snapshot without confusing transient
- * observed readiness with a desired server revision.
- */
-export async function reconcileAuthoritativeMcpSnapshot(options: {
- servers: McpServerInfo[]
- manager: AuthoritativeMcpSnapshotManager
- serverState: Map<string, string>
- getAuthToken: (serverName: string) => Promise<string | undefined>
-}): Promise<void> {
- const currentNames = new Set(options.servers.map(server => server.name))
- const previousNames = new Set(options.serverState.keys())
- const connectedNames = new Set(options.manager.getConnectedServers())
-
- const resolveAuthToken = async (server: McpServerInfo): Promise<string | undefined> => {
- try {
- return await resolveRequiredMcpAuthToken(server, options.getAuthToken)
- } catch (error) {
- // Auth discovery fails before manager admission. Preserve a live
- // connection's status during replacement; otherwise publish the
- // admission failure exactly once.
- if (!connectedNames.has(server.name)) {
- options.manager.recordAdmissionFailure(server, error)
- }
- throw error
- }
- }
-
- const reconcileServer = async (server: McpServerInfo): Promise<void> => {
- const previousState = options.serverState.get(server.name)
- const currentState = JSON.stringify(server)
-
- if (!previousState) {
- const authToken = await resolveAuthToken(server)
- await options.manager.addServer(server, authToken)
- options.serverState.set(server.name, currentState)
- return
- }
-
- const previousServer = JSON.parse(previousState) as McpServerInfo
- const desiredChanged =
- mcpServerDesiredRevision(previousServer) !== mcpServerDesiredRevision(server)
-
- if (desiredChanged) {
- if (server.status?.authoritative === false) {
- await options.manager.removeServer(server.name)
- // Reuse the manager's fail-closed admission path to keep the expected
- // server visible as not_ready without opening a connection.
- await options.manager.addServer(server, undefined)
- options.serverState.set(server.name, currentState)
- return
- }
-
- if (!server.enabled || !server.status?.ready) {
- await options.manager.removeServer(server.name)
- await options.manager.addServer(server, undefined)
- options.serverState.set(server.name, currentState)
- return
- }
-
- // A ready authoritative desired revision is connected before commit.
- // Failure leaves the previous connection and recorded revision intact,
- // so an identical later snapshot retries it.
- const authToken = await resolveAuthToken(server)
- await options.manager.replaceServer(server, authToken)
- options.serverState.set(server.name, currentState)
- return
- }
-
- if (server.status?.authoritative === false) {
- // The producer explicitly could not establish status authority. Record
- // the snapshot, but never use it to open a connection. An existing live
- // connection remains valid until authoritative status or desired/delete
- // state says otherwise.
- options.serverState.set(server.name, currentState)
- return
- }
-
- if (!server.status?.ready) {
- // An authoritative ready=false, and a legacy ready=false with no
- // authority marker, retain the existing fail-closed behavior. Re-adding
- // a not-ready server does not connect; it updates observed status.
- if (connectedNames.has(server.name)) {
- await options.manager.removeServer(server.name)
- }
- await options.manager.addServer(server, undefined)
- options.serverState.set(server.name, currentState)
- return
- }
-
- // A previously not-ready server was intentionally recorded without a
- // connection. Admit it once the authoritative snapshot reports it ready.
- if (!connectedNames.has(server.name) && server.enabled) {
- const authToken = await resolveAuthToken(server)
- await options.manager.addServer(server, authToken)
- }
-
- // Status-only degradation is still an authoritative observation, but it
- // must not tear down a live connection that may remain healthy.
- options.serverState.set(server.name, currentState)
- }
-
- for (const server of options.servers) {
- try {
- await reconcileServer(server)
- } catch (error) {
- console.error(`[Main] MCP server reconciliation failed; will retry: ${server.name}`, error)
- }
- }
-
- for (const name of previousNames) {
- if (!currentNames.has(name)) {
- try {
- await options.manager.removeServer(name)
- options.serverState.delete(name)
- } catch (error) {
- console.error(`[Main] MCP server deletion failed; will retry: ${name}`, error)
- }
- }
- }
-}
-
async function initializeMcpServers(contextRef: string): Promise<void> {
console.log(`[Main] Initializing MCP servers for context: ${contextRef}`)
+ const initializationGeneration = ++mcpInitializationGeneration
+ const isInitializationCurrent = (): boolean =>
+ !isShuttingDown && mcpInitializationGeneration === initializationGeneration
const replaceFleet = async (servers: McpServerInfo[]): Promise<void> => {
+ const previousManager = mcpManager
await replaceAuthoritativeMcpFleet({
servers,
- previousManager: mcpManager,
+ previousManager,
createManager: () => new McpManager(config.mcpProxyEnabled ? config.mcpProxyUrl : undefined),
getAuthToken: async serverName => {
if (!contextMapperClient) {
@@ -1062,6 +799,10 @@ async function initializeMcpServers(contextRef: string): Promise<void> {
lastServerState = nextServerState
agent?.setMcpManager(nextManager)
},
+ coordinator: mcpFleetCoordinator,
+ onColdStartPublished: () => ensureContextMapperPolling(contextRef),
+ isPreviousManagerCurrent: () => mcpManager === previousManager,
+ isFleetLifecycleCurrent: isInitializationCurrent,
})
}
@@ -1076,6 +817,7 @@ async function initializeMcpServers(contextRef: string): Promise<void> {
contextRef,
client: contextMapperClient,
replaceFleet,
+ isCurrent: isInitializationCurrent,
})
} else {
await replaceFleet([])
@@ -1115,12 +857,20 @@ async function pollContextMapper(contextRef: string): Promise<void> {
return
}
- const { servers } = await contextMapperClient.pollServers(contextRef)
- await reconcileAuthoritativeMcpSnapshot({
- servers,
- manager: mcpManager,
- serverState: lastServerState,
- getAuthToken: serverName => contextMapperClient!.getAuthToken(serverName),
+ const manager = mcpManager
+ await pollAuthoritativeMcpSnapshotIfCurrent({
+ poll: () => contextMapperClient!.pollServers(contextRef),
+ // A delayed fetch may resolve after shutdown or after a manager swap.
+ // Never publish that stale snapshot into a closed/retired manager.
+ isCurrent: () => !isShuttingDown && mcpManager === manager,
+ reconcile: servers =>
+ reconcileAuthoritativeMcpSnapshot({
+ servers,
+ manager,
+ serverState: lastServerState,
+ getAuthToken: serverName => contextMapperClient!.getAuthToken(serverName),
+ coordinator: mcpFleetCoordinator,
+ }),
})
} catch (error) {
console.error('[Main] Error polling skill-mapper:', error)
@@ -1174,6 +924,7 @@ export function createCoalescedPollRunner(poll: () => Promise<void>): {
* Start polling context-mapper for McpServer changes.
*/
export function startContextMapperPolling(contextRef: string): void {
+ if (isShuttingDown) return
// Re-entry replaces the complete producer/runner pair. Stopping only the
// runner would leave the previous interval dispatching into the new runner.
stopContextMapperPolling()
@@ -1188,6 +939,11 @@ export function startContextMapperPolling(contextRef: string): void {
}, config.contextMapperPollInterval)
}
+export function ensureContextMapperPolling(contextRef: string): void {
+ if (isShuttingDown || (contextMapperPollTimer && contextMapperPollRunner)) return
+ startContextMapperPolling(contextRef)
+}
+
/**
* Stop polling context-mapper.
*/
@@ -2749,9 +2505,20 @@ async function shutdown(signal: string): Promise<void> {
return
}
isShuttingDown = true
+ mcpInitializationGeneration += 1
console.log(`[Main] Received ${signal}, shutting down`)
+ // Fence MCP authority and detach live tools before any awaited shutdown
+ // phase. Delayed polls and in-flight connects cannot reopen a closed manager.
+ const closingMcpManager = mcpManager
+ if (closingMcpManager) {
+ mcpFleetCoordinator.closeManager(closingMcpManager)
+ }
+ const mcpClosePromise = closingMcpManager?.close(cleanup =>
+ mcpFleetCoordinator.scheduleCleanup(cleanup)
+ )
+
// Stop components in order
stopRuntimeAuthProactiveRefresh()
hostWatcher?.stop()
@@ -2792,7 +2559,8 @@ async function shutdown(signal: string): Promise<void> {
cronScheduler?.stop()
spilloverStorage?.stopGc()
- await mcpManager?.disconnectAll()
+ await mcpClosePromise
+ await mcpFleetCoordinator.drainForShutdown()
await pluginWorkloadSdkServer?.stop()
await rpcServer?.stop()
@@ -2950,7 +2718,7 @@ async function startProductionMode(): Promise<void> {
// reconciles the catalog (the platform tolerates the 'connecting' sweep).
startMcpInitializationInBackground({
initialize: () => initializeMcpServers(host.spec.contextRef),
- afterInitialAttempt: () => startContextMapperPolling(host.spec.contextRef),
+ afterInitialAttempt: () => ensureContextMapperPolling(host.spec.contextRef),
})
console.log(`[Main] Approval system: ${config.enableApproval ? 'ENABLED' : 'DISABLED'}`)
diff --git a/mcp-host/src/mcp/__tests__/managerStatus.test.ts b/mcp-host/src/mcp/__tests__/managerStatus.test.ts
index 3ce51b61b..b4e2a4386 100644
--- a/mcp-host/src/mcp/__tests__/managerStatus.test.ts
+++ b/mcp-host/src/mcp/__tests__/managerStatus.test.ts
@@ -20,6 +20,20 @@ function serverInfo(overrides: Partial<McpServerInfo> = {}): McpServerInfo {
}
}
+function deferred<T = void>(): {
+ promise: Promise<T>
+ resolve: (value: T) => void
+ reject: (reason?: unknown) => void
+} {
+ let resolve!: (value: T) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
+}
+
describe('McpManager status tracking — disabled / not-ready paths', () => {
it('markDisabled when enabled=false', async () => {
const m = new McpManager()
@@ -82,11 +96,13 @@ describe('McpManager status tracking — disabled / not-ready paths', () => {
expect(m.status.get(server.name)).toBeDefined()
expect((m as any).serverInfos.has(server.name)).toBe(true)
expect(m.getConnectedServers()).toEqual([])
+ expect(m.getKnownServers()).toEqual([server.name])
await m.removeServer(server.name)
expect(m.status.get(server.name)).toBeUndefined()
expect((m as any).serverInfos.has(server.name)).toBe(false)
+ expect(m.getKnownServers()).toEqual([])
}
)
})
@@ -146,7 +162,7 @@ describe('McpManager status tracking — connect success/failure', () => {
this.tools = [{ name: 'old-tool', inputSchema: {}, serverName: 'svc' }]
})
.mockRejectedValueOnce(new Error('replacement connect failed'))
- vi.spyOn(McpClient.prototype, 'disconnect').mockResolvedValue(undefined)
+ vi.spyOn(McpClient.prototype, 'retire').mockReturnValue(async () => undefined)
const previous = serverInfo()
const replacement = serverInfo({
transport: { type: 'streamableHttp', url: 'http://replacement/mcp' },
@@ -176,7 +192,7 @@ describe('McpManager status tracking — connect success/failure', () => {
this.connected = true
this.tools = [{ name: 'new-tool', inputSchema: {}, serverName: 'svc' }]
})
- vi.spyOn(McpClient.prototype, 'disconnect').mockImplementation(async () => {
+ vi.spyOn(McpClient.prototype, 'retire').mockImplementation(() => async () => {
effects.push('disconnect-previous')
})
const previous = serverInfo()
@@ -192,6 +208,291 @@ describe('McpManager status tracking — connect success/failure', () => {
expect((m as any).serverInfos.get('svc')).toEqual(replacement)
expect(m.getAllTools().map(tool => tool.name)).toEqual(['svc__new-tool'])
})
+
+ it('discards a candidate that becomes stale while connect is in flight', async () => {
+ const { McpClient } = await import('../client')
+ const connectStarted = deferred()
+ const releaseConnect = deferred()
+ vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async function (this: any) {
+ connectStarted.resolve()
+ await releaseConnect.promise
+ this.connected = true
+ this.tools = [{ name: 'stale-tool', inputSchema: {}, serverName: 'svc' }]
+ })
+ const cleanup = vi.fn().mockResolvedValue(undefined)
+ const retire = vi.spyOn(McpClient.prototype, 'retire').mockReturnValue(cleanup)
+ const scheduledCleanups: Array<() => Promise<void>> = []
+ let current = true
+ const onCommit = vi.fn()
+ const m = new McpManager()
+ const admission = m.addServer(serverInfo(), undefined, {
+ isCurrent: () => current,
+ onCommit,
+ scheduleCleanup: scheduledCleanup => scheduledCleanups.push(scheduledCleanup),
+ })
+
+ await connectStarted.promise
+ expect(m.getKnownServers()).toEqual(['svc'])
+ current = false
+ releaseConnect.resolve()
+
+ await expect(admission).resolves.toBe('stale')
+ expect(retire).toHaveBeenCalledTimes(1)
+ expect(scheduledCleanups).toHaveLength(1)
+ expect(cleanup).not.toHaveBeenCalled()
+ expect(onCommit).not.toHaveBeenCalled()
+ expect(m.getConnectedServers()).toEqual([])
+ expect(m.getKnownServers()).toEqual([])
+ expect(m.status.get('svc')).toBeUndefined()
+ })
+
+ it('does not record a stale connect failure', async () => {
+ const { McpClient } = await import('../client')
+ const connectStarted = deferred()
+ const rejectConnect = deferred()
+ vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async () => {
+ connectStarted.resolve()
+ await rejectConnect.promise
+ })
+ vi.spyOn(McpClient.prototype, 'retire').mockReturnValue(async () => undefined)
+ let current = true
+ const m = new McpManager()
+ const admission = m.addServer(serverInfo(), undefined, {
+ isCurrent: () => current,
+ })
+
+ await connectStarted.promise
+ current = false
+ rejectConnect.reject(new Error('stale failure'))
+
+ await expect(admission).resolves.toBe('stale')
+ expect(m.getKnownServers()).toEqual([])
+ expect(m.status.get('svc')).toBeUndefined()
+ })
+
+ it('revokes inventory and tools before a detached client finishes disconnecting', async () => {
+ const { McpClient } = await import('../client')
+ vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async function (this: any) {
+ this.connected = true
+ this.tools = [{ name: 'tool', inputSchema: {}, serverName: 'svc' }]
+ })
+ const releaseCleanup = deferred()
+ const retire = vi
+ .spyOn(McpClient.prototype, 'retire')
+ .mockReturnValue(() => releaseCleanup.promise)
+ const m = new McpManager()
+ await m.addServer(serverInfo())
+
+ const cleanup = m.detachServer('svc')
+
+ expect(m.getConnectedServers()).toEqual([])
+ expect(m.getKnownServers()).toEqual([])
+ expect(m.getAllTools()).toEqual([])
+ expect(m.status.get('svc')).toBeUndefined()
+ expect(retire).toHaveBeenCalledTimes(1)
+
+ const cleaning = cleanup()
+ releaseCleanup.resolve()
+ await cleaning
+ })
+
+ it('disconnectAll fences an admission that was already connecting', async () => {
+ const { McpClient } = await import('../client')
+ const connectStarted = deferred()
+ const releaseConnect = deferred()
+ vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async function (this: any) {
+ connectStarted.resolve()
+ await releaseConnect.promise
+ this.connected = true
+ this.tools = [{ name: 'late-tool', inputSchema: {}, serverName: 'svc' }]
+ })
+ vi.spyOn(McpClient.prototype, 'retire').mockReturnValue(async () => undefined)
+ const m = new McpManager()
+ const admission = m.addServer(serverInfo())
+
+ await connectStarted.promise
+ await m.disconnectAll()
+ releaseConnect.resolve()
+
+ await expect(admission).resolves.toBe('stale')
+ expect(m.getConnectedServers()).toEqual([])
+ expect(m.getKnownServers()).toEqual([])
+ expect(m.status.get('svc')).toBeUndefined()
+ })
+
+ it.each(['detachServer', 'removeServer', 'disconnectAll', 'close'] as const)(
+ '%s retires a pending add synchronously and cleans it exactly once',
+ async revocation => {
+ const { McpClient } = await import('../client')
+ const connectStarted = deferred()
+ const releaseConnect = deferred()
+ vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async function (this: any) {
+ connectStarted.resolve()
+ await releaseConnect.promise
+ this.connected = true
+ this.tools = [{ name: 'late-tool', inputSchema: {}, serverName: 'svc' }]
+ })
+ const cleanup = vi.fn().mockResolvedValue(undefined)
+ const retire = vi.spyOn(McpClient.prototype, 'retire').mockReturnValue(cleanup)
+ const scheduledCleanups: Array<() => Promise<void>> = []
+ const onCommit = vi.fn()
+ const m = new McpManager()
+ const admission = m.addServer(serverInfo(), undefined, {
+ onCommit,
+ scheduleCleanup: scheduledCleanup => scheduledCleanups.push(scheduledCleanup),
+ })
+
+ await connectStarted.promise
+ const revoking =
+ revocation === 'detachServer'
+ ? m.detachServer('svc')()
+ : revocation === 'removeServer'
+ ? m.removeServer('svc')
+ : revocation === 'disconnectAll'
+ ? m.disconnectAll()
+ : m.close()
+
+ expect(retire).toHaveBeenCalledTimes(1)
+ await revoking
+ expect(cleanup).toHaveBeenCalledTimes(1)
+
+ releaseConnect.resolve()
+ await expect(admission).resolves.toBe('stale')
+
+ expect(retire).toHaveBeenCalledTimes(1)
+ expect(cleanup).toHaveBeenCalledTimes(1)
+ expect(scheduledCleanups).toEqual([])
+ expect(onCommit).not.toHaveBeenCalled()
+ expect(m.getConnectedServers()).toEqual([])
+ expect(m.getKnownServers()).toEqual([])
+ expect(m.status.get('svc')).toBeUndefined()
+ }
+ )
+
+ it.each(['detachServer', 'removeServer', 'disconnectAll', 'close'] as const)(
+ '%s retires both the installed client and pending replacement before its handshake completes',
+ async revocation => {
+ const { McpClient } = await import('../client')
+ const replacementConnectStarted = deferred()
+ const releaseReplacementConnect = deferred()
+ vi.spyOn(McpClient.prototype, 'connect')
+ .mockImplementationOnce(async function (this: any) {
+ this.connected = true
+ this.tools = [{ name: 'old-tool', inputSchema: {}, serverName: 'svc' }]
+ })
+ .mockImplementationOnce(async function (this: any) {
+ replacementConnectStarted.resolve()
+ await releaseReplacementConnect.promise
+ this.connected = true
+ this.tools = [{ name: 'late-new-tool', inputSchema: {}, serverName: 'svc' }]
+ })
+ const cleanups: Array<ReturnType<typeof vi.fn>> = []
+ const retire = vi.spyOn(McpClient.prototype, 'retire').mockImplementation(() => {
+ const cleanup = vi.fn().mockResolvedValue(undefined)
+ cleanups.push(cleanup)
+ return cleanup
+ })
+ const scheduledCleanups: Array<() => Promise<void>> = []
+ const onCommit = vi.fn()
+ const m = new McpManager()
+ await m.addServer(serverInfo())
+ const admission = m.replaceServer(
+ serverInfo({
+ transport: { type: 'streamableHttp', url: 'http://replacement/mcp' },
+ }),
+ undefined,
+ {
+ onCommit,
+ scheduleCleanup: scheduledCleanup => scheduledCleanups.push(scheduledCleanup),
+ }
+ )
+
+ await replacementConnectStarted.promise
+ const revoking =
+ revocation === 'detachServer'
+ ? m.detachServer('svc')()
+ : revocation === 'removeServer'
+ ? m.removeServer('svc')
+ : revocation === 'disconnectAll'
+ ? m.disconnectAll()
+ : m.close()
+
+ expect(retire).toHaveBeenCalledTimes(2)
+ await revoking
+ expect(cleanups).toHaveLength(2)
+ expect(cleanups.every(cleanup => cleanup.mock.calls.length === 1)).toBe(true)
+
+ releaseReplacementConnect.resolve()
+ await expect(admission).resolves.toBe('stale')
+
+ expect(retire).toHaveBeenCalledTimes(2)
+ expect(cleanups.every(cleanup => cleanup.mock.calls.length === 1)).toBe(true)
+ expect(scheduledCleanups).toEqual([])
+ expect(onCommit).not.toHaveBeenCalled()
+ expect(m.getConnectedServers()).toEqual([])
+ expect(m.getKnownServers()).toEqual([])
+ expect(m.getAllTools()).toEqual([])
+ expect(m.status.get('svc')).toBeUndefined()
+ }
+ )
+
+ it('permanently rejects admissions after close', async () => {
+ const { McpClient } = await import('../client')
+ const connect = vi.spyOn(McpClient.prototype, 'connect').mockResolvedValue(undefined)
+ vi.spyOn(McpClient.prototype, 'retire').mockReturnValue(async () => undefined)
+ const scheduledCleanups: Array<() => Promise<void>> = []
+ const m = new McpManager()
+ await m.addServer(serverInfo())
+
+ await m.close(cleanup => scheduledCleanups.push(cleanup))
+ await expect(m.addServer(serverInfo({ name: 'late-server' }))).resolves.toBe('stale')
+ m.recordAdmissionFailure(serverInfo({ name: 'late-failure' }), new Error('late'))
+
+ expect(connect).toHaveBeenCalledTimes(1)
+ expect(m.getConnectedServers()).toEqual([])
+ expect(m.getKnownServers()).toEqual([])
+ expect(m.status.size()).toBe(0)
+ expect(scheduledCleanups).toHaveLength(1)
+ await scheduledCleanups[0]()
+ })
+
+ it('commits a replacement without waiting for bounded old-client cleanup', async () => {
+ const { McpClient } = await import('../client')
+ vi.spyOn(McpClient.prototype, 'connect')
+ .mockImplementationOnce(async function (this: any) {
+ this.connected = true
+ this.tools = [{ name: 'old-tool', inputSchema: {}, serverName: 'svc' }]
+ })
+ .mockImplementationOnce(async function (this: any) {
+ this.connected = true
+ this.tools = [{ name: 'new-tool', inputSchema: {}, serverName: 'svc' }]
+ })
+ const releaseCleanup = deferred()
+ vi.spyOn(McpClient.prototype, 'retire').mockReturnValue(() => releaseCleanup.promise)
+ const scheduled: Array<() => Promise<void>> = []
+ const onCommit = vi.fn()
+ const replacement = serverInfo({
+ transport: { type: 'streamableHttp', url: 'http://replacement/mcp' },
+ })
+ const m = new McpManager()
+ await m.addServer(serverInfo())
+
+ await expect(
+ m.replaceServer(replacement, undefined, {
+ onCommit,
+ scheduleCleanup: cleanup => scheduled.push(cleanup),
+ })
+ ).resolves.toBe('applied')
+
+ expect(onCommit).toHaveBeenCalledTimes(1)
+ expect((m as any).serverInfos.get('svc')).toEqual(replacement)
+ expect(m.getAllTools().map(tool => tool.name)).toEqual(['svc__new-tool'])
+ expect(scheduled).toHaveLength(1)
+
+ const cleanup = scheduled[0]()
+ releaseCleanup.resolve()
+ await cleanup
+ })
})
describe('McpManager.refreshAllServerStatus', () => {
@@ -226,6 +527,7 @@ describe('McpManager.refreshAllServerStatus', () => {
vi.spyOn(McpClient.prototype, 'probeTools').mockResolvedValue({
ok: false,
error: { code: 500 },
+ stale: false,
})
const m = new McpManager()
@@ -238,11 +540,74 @@ describe('McpManager.refreshAllServerStatus', () => {
expect(s.reason).toBe('upstream_5xx')
})
+ it('does not let a probe from a superseded epoch degrade the same connected client', async () => {
+ const { McpClient } = await import('../client')
+ vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async function (this: any) {
+ this.connected = true
+ this.tools = [
+ { name: 'tool-1', inputSchema: {}, serverName: 'svc' },
+ { name: 'tool-2', inputSchema: {}, serverName: 'svc' },
+ ]
+ })
+ vi.spyOn(McpClient.prototype, 'probeTools').mockResolvedValue({
+ ok: false,
+ error: new Error('MCP client svc is superseded'),
+ stale: true,
+ })
+ const m = new McpManager()
+ await m.addServer(serverInfo())
+
+ await m.refreshAllServerStatus()
+
+ expect(m.status.get('svc')).toMatchObject({
+ state: 'connected',
+ toolCount: 2,
+ reason: null,
+ })
+ })
+
it('returns 0 and is a no-op when no servers are connected', async () => {
const m = new McpManager()
const n = await m.refreshAllServerStatus()
expect(n).toBe(0)
})
+
+ it('does not let a stale probe overwrite a replacement connection status', async () => {
+ const { McpClient } = await import('../client')
+ vi.spyOn(McpClient.prototype, 'connect')
+ .mockImplementationOnce(async function (this: any) {
+ this.connected = true
+ this.tools = [{ name: 'old-tool', inputSchema: {}, serverName: 'svc' }]
+ })
+ .mockImplementationOnce(async function (this: any) {
+ this.connected = true
+ this.tools = [
+ { name: 'new-tool-1', inputSchema: {}, serverName: 'svc' },
+ { name: 'new-tool-2', inputSchema: {}, serverName: 'svc' },
+ ]
+ })
+ const probeStarted = deferred()
+ const releaseProbe = deferred<{ ok: true; toolCount: number }>()
+ vi.spyOn(McpClient.prototype, 'probeTools').mockImplementation(async () => {
+ probeStarted.resolve()
+ return releaseProbe.promise
+ })
+ const m = new McpManager()
+ await m.addServer(serverInfo())
+ const refresh = m.refreshAllServerStatus()
+ await probeStarted.promise
+
+ await m.replaceServer(
+ serverInfo({ transport: { type: 'streamableHttp', url: 'http://replacement/mcp' } }),
+ undefined,
+ { scheduleCleanup: vi.fn() }
+ )
+ expect(m.status.get('svc')).toMatchObject({ state: 'connected', toolCount: 2 })
+
+ releaseProbe.resolve({ ok: true, toolCount: 99 })
+ await refresh
+ expect(m.status.get('svc')).toMatchObject({ state: 'connected', toolCount: 2 })
+ })
})
describe('McpManager.disconnectAll resets the tracker', () => {
@@ -254,7 +619,7 @@ describe('McpManager.disconnectAll resets the tracker', () => {
this.connected = true
this.tools = []
})
- vi.spyOn(McpClient.prototype, 'disconnect').mockResolvedValue(undefined)
+ vi.spyOn(McpClient.prototype, 'retire').mockReturnValue(async () => undefined)
const m = new McpManager()
await m.addServer(serverInfo({ name: 'a' }))
@@ -272,11 +637,13 @@ describe('McpManager.disconnectAll resets the tracker', () => {
this.tools = []
})
const cleanupError = new Error('first disconnect failed')
- const disconnect = vi
- .spyOn(McpClient.prototype, 'disconnect')
- .mockImplementation(async function (this: any) {
+ const cleanupCalls: string[] = []
+ const retire = vi.spyOn(McpClient.prototype, 'retire').mockImplementation(function (this: any) {
+ return async () => {
+ cleanupCalls.push(this.name)
if (this.name === 'a') throw cleanupError
- })
+ }
+ })
const m = new McpManager()
await m.addServer(serverInfo({ name: 'a' }))
@@ -284,8 +651,42 @@ describe('McpManager.disconnectAll resets the tracker', () => {
await expect(m.disconnectAll()).rejects.toBe(cleanupError)
- expect(disconnect).toHaveBeenCalledTimes(2)
+ expect(retire).toHaveBeenCalledTimes(2)
+ expect(cleanupCalls).toEqual(['a', 'b'])
+ expect(m.getConnectedServers()).toEqual([])
+ expect(m.status.size()).toBe(0)
+ })
+
+ it('detaches every client before awaiting the first disconnect', async () => {
+ const { McpClient } = await import('../client')
+ vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async function (this: any) {
+ this.connected = true
+ this.tools = [{ name: `${this.name}-tool`, inputSchema: {}, serverName: this.name }]
+ })
+ const releaseFirstCleanup = deferred()
+ const cleanupCalls: string[] = []
+ const retire = vi.spyOn(McpClient.prototype, 'retire').mockImplementation(function (this: any) {
+ return async () => {
+ cleanupCalls.push(this.name)
+ if (this.name === 'a') await releaseFirstCleanup.promise
+ }
+ })
+ const m = new McpManager()
+ await m.addServer(serverInfo({ name: 'a' }))
+ await m.addServer(serverInfo({ name: 'b' }))
+
+ const shutdown = m.disconnectAll()
+ await Promise.resolve()
+
expect(m.getConnectedServers()).toEqual([])
+ expect(m.getKnownServers()).toEqual([])
+ expect(m.getAllTools()).toEqual([])
expect(m.status.size()).toBe(0)
+ expect(retire).toHaveBeenCalledTimes(2)
+ expect(cleanupCalls).toEqual(['a'])
+
+ releaseFirstCleanup.resolve()
+ await shutdown
+ expect(cleanupCalls).toEqual(['a', 'b'])
})
})
diff --git a/mcp-host/src/mcp/authoritativeFleet.ts b/mcp-host/src/mcp/authoritativeFleet.ts
new file mode 100644
index 000000000..e4ad9c185
--- /dev/null
+++ b/mcp-host/src/mcp/authoritativeFleet.ts
@@ -0,0 +1,873 @@
+import type { ContextMapperClient } from '../contextMapperClient'
+import type { McpServerInfo } from '../types'
+import type { McpAdmissionControl, McpAdmissionOutcome } from './manager'
+
+/**
+ * Initialize MCP servers for the host's context using skill-mapper.
+ */
+export async function runAuthoritativeMcpInitialization(options: {
+ contextRef: string
+ client: Pick<ContextMapperClient, 'healthCheck' | 'listServersByContext'>
+ replaceFleet: (servers: McpServerInfo[]) => Promise<void>
+ isCurrent?: () => boolean
+ sleep?: (milliseconds: number) => Promise<void>
+ maxRetries?: number
+}): Promise<void> {
+ const maxRetries = options.maxRetries ?? 5
+ const sleep =
+ options.sleep ??
+ ((milliseconds: number) => new Promise(resolve => setTimeout(resolve, milliseconds)))
+
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
+ const ready = await options.client.healthCheck()
+ if (options.isCurrent?.() === false) return
+ if (ready) {
+ const servers = await options.client.listServersByContext(options.contextRef)
+ if (options.isCurrent?.() === false) return
+ await options.replaceFleet(servers)
+ return
+ }
+
+ console.log(`[Main] Waiting for Context Mapper... (${attempt}/${maxRetries})`)
+ if (attempt < maxRetries) {
+ await sleep(2000)
+ }
+ }
+
+ throw new Error(`Context Mapper was not ready after ${maxRetries} attempts`)
+}
+
+interface AuthoritativeMcpFleetManager {
+ addServer(
+ server: McpServerInfo,
+ authToken?: string,
+ control?: McpAdmissionControl
+ ): Promise<McpAdmissionOutcome>
+ disconnectAll(): Promise<void>
+ recordAdmissionFailure(server: McpServerInfo, error: unknown): void
+}
+
+export const DEFAULT_MCP_FLEET_RECONCILE_MAX_CONCURRENCY = 10
+const DEFAULT_MCP_CLEANUP_TIMEOUT_MS = 30_000
+const DEFAULT_MCP_ADMISSION_DRAIN_TIMEOUT_MS = 30_000
+
+interface McpSnapshotLease {
+ isCurrent(serverName: string): boolean
+ isAbsentCurrent(serverName: string): boolean
+ admissionEpoch(serverName: string): symbol | undefined
+}
+
+type McpAuthorityEntry = {
+ fingerprint: string
+ admissionEpoch: symbol
+}
+
+type McpAdmissionRequest = {
+ epoch: symbol
+ lease: McpSnapshotLease
+ effect: (isCurrent: () => boolean) => Promise<void>
+}
+
+type McpScheduledAdmission = {
+ request: McpAdmissionRequest
+ started: boolean
+ promise: Promise<void>
+ cancelWaiting?: () => boolean
+}
+
+type McpAdmissionSlot = {
+ scheduled?: McpScheduledAdmission
+ pending?: McpAdmissionRequest
+}
+
+type McpPermitWaiter = {
+ grant: () => void
+}
+
+/**
+ * Coordinates overlapping initial discovery and authoritative polls.
+ *
+ * Every snapshot gets a new token. Identical desired admissions on the same
+ * manager adopt their existing admission epoch so a poll coalesces onto the
+ * in-flight connect; any status/config change, delete/recreate, manager swap,
+ * or explicit invalidation creates a new epoch and makes the old candidate
+ * fail its pre-commit guard.
+ */
+export class AuthoritativeMcpFleetCoordinator {
+ private manager: object | null = null
+ private managerEpoch = Symbol('initial-manager')
+ private snapshotToken = Symbol('initial-snapshot')
+ private fleetRevision = Symbol('initial-fleet')
+ private desired = new Map<string, McpAuthorityEntry>()
+ private admissions = new WeakMap<object, Map<string, McpAdmissionSlot>>()
+ private admissionTasks = new Set<Promise<void>>()
+ private admissionActive = 0
+ private admissionWaiters: McpPermitWaiter[] = []
+ private cleanupActive = 0
+ private cleanupWaiters: McpPermitWaiter[] = []
+ private cleanupTasks = new Set<Promise<void>>()
+ private closedManagers = new WeakSet<object>()
+
+ constructor(
+ private readonly maxAdmissions = DEFAULT_MCP_FLEET_RECONCILE_MAX_CONCURRENCY,
+ private readonly maxCleanups = DEFAULT_MCP_FLEET_RECONCILE_MAX_CONCURRENCY,
+ private readonly backgroundReconciliation = false,
+ private readonly cleanupTimeoutMs = DEFAULT_MCP_CLEANUP_TIMEOUT_MS,
+ private readonly admissionDrainTimeoutMs = DEFAULT_MCP_ADMISSION_DRAIN_TIMEOUT_MS
+ ) {
+ resolveMcpFleetConcurrency(maxAdmissions)
+ resolveMcpFleetConcurrency(maxCleanups)
+ if (!Number.isFinite(cleanupTimeoutMs) || cleanupTimeoutMs < 1) {
+ throw new Error('MCP cleanup timeout must be a positive finite number')
+ }
+ if (!Number.isFinite(admissionDrainTimeoutMs) || admissionDrainTimeoutMs < 1) {
+ throw new Error('MCP admission drain timeout must be a positive finite number')
+ }
+ }
+
+ get reconcilesInBackground(): boolean {
+ return this.backgroundReconciliation
+ }
+
+ publishSnapshot(manager: object, servers: readonly McpServerInfo[]): McpSnapshotLease {
+ if (this.closedManagers.has(manager)) {
+ return {
+ isCurrent: () => false,
+ isAbsentCurrent: () => false,
+ admissionEpoch: () => undefined,
+ }
+ }
+ const managerChanged = this.manager !== manager
+ if (managerChanged) {
+ if (this.manager) {
+ this.pruneObsoleteAdmissions(this.manager, new Map())
+ }
+ this.manager = manager
+ this.managerEpoch = Symbol('manager')
+ this.desired = new Map()
+ }
+
+ const capturedManagerEpoch = this.managerEpoch
+ const capturedSnapshotToken = Symbol('snapshot')
+ this.snapshotToken = capturedSnapshotToken
+ const nextDesired = new Map<string, McpAuthorityEntry>()
+ for (const server of servers) {
+ const fingerprint = canonicalJson(server)
+ const previous = this.desired.get(server.name)
+ nextDesired.set(server.name, {
+ fingerprint,
+ admissionEpoch:
+ previous?.fingerprint === fingerprint ? previous.admissionEpoch : Symbol(server.name),
+ })
+ }
+ const fleetChanged =
+ managerChanged ||
+ nextDesired.size !== this.desired.size ||
+ [...nextDesired].some(
+ ([name, entry]) => this.desired.get(name)?.fingerprint !== entry.fingerprint
+ )
+ if (fleetChanged) {
+ this.fleetRevision = Symbol('fleet')
+ }
+ this.desired = nextDesired
+ this.pruneObsoleteAdmissions(manager, nextDesired)
+ const capturedEpochs = new Map(
+ [...nextDesired].map(([name, entry]) => [name, entry.admissionEpoch])
+ )
+
+ return {
+ isCurrent: serverName =>
+ this.manager === manager &&
+ this.managerEpoch === capturedManagerEpoch &&
+ this.desired.get(serverName)?.admissionEpoch === capturedEpochs.get(serverName),
+ isAbsentCurrent: serverName =>
+ this.manager === manager &&
+ this.managerEpoch === capturedManagerEpoch &&
+ this.snapshotToken === capturedSnapshotToken &&
+ !this.desired.has(serverName),
+ admissionEpoch: serverName => capturedEpochs.get(serverName),
+ }
+ }
+
+ closeManager(manager: object): void {
+ this.closedManagers.add(manager)
+ this.pruneObsoleteAdmissions(manager, new Map())
+ if (this.manager !== manager) return
+ this.managerEpoch = Symbol('invalidated-manager')
+ this.snapshotToken = Symbol('invalidated-snapshot')
+ this.desired.clear()
+ }
+
+ captureManagerRevision(manager: object): () => boolean {
+ const capturedManagerEpoch = this.managerEpoch
+ const capturedFleetRevision = this.fleetRevision
+ return () =>
+ this.manager === manager &&
+ this.managerEpoch === capturedManagerEpoch &&
+ this.fleetRevision === capturedFleetRevision
+ }
+
+ async runAdmission(
+ manager: object,
+ serverName: string,
+ lease: McpSnapshotLease,
+ effect: (isCurrent: () => boolean) => Promise<void>
+ ): Promise<void> {
+ const epoch = lease.admissionEpoch(serverName)
+ if (!epoch || !lease.isCurrent(serverName)) return
+
+ let byName = this.admissions.get(manager)
+ if (!byName) {
+ byName = new Map()
+ this.admissions.set(manager, byName)
+ }
+ let slot = byName.get(serverName)
+ if (!slot) {
+ slot = {}
+ byName.set(serverName, slot)
+ }
+ const request: McpAdmissionRequest = { epoch, lease, effect }
+ const scheduled = slot.scheduled
+ if (!scheduled) {
+ await this.startAdmission(serverName, byName, slot, request)
+ return
+ }
+
+ if (scheduled.request.epoch === epoch || slot.pending?.epoch === epoch) {
+ return
+ }
+
+ // A permit-waiting request has not started any external effect, so adopt
+ // the newest epoch in place instead of allocating another global waiter.
+ if (!scheduled.started) {
+ scheduled.request = request
+ return
+ }
+
+ // At most one latest-wins successor is retained while the active request
+ // is doing I/O. Further snapshots replace it without growing a stale FIFO.
+ slot.pending = request
+ }
+
+ private startAdmission(
+ serverName: string,
+ byName: Map<string, McpAdmissionSlot>,
+ slot: McpAdmissionSlot,
+ request: McpAdmissionRequest
+ ): Promise<void> {
+ const scheduled: McpScheduledAdmission = {
+ request,
+ started: false,
+ promise: Promise.resolve(),
+ }
+ const promise = this.withPermit(
+ 'admission',
+ async () => {
+ scheduled.started = true
+ const latest = scheduled.request
+ if (!latest.lease.isCurrent(serverName)) return
+ await latest.effect(() => latest.lease.isCurrent(serverName))
+ },
+ cancelWaiting => {
+ scheduled.cancelWaiting = cancelWaiting
+ }
+ ).finally(() => {
+ if (slot.scheduled !== scheduled) return
+ slot.scheduled = undefined
+ const pending = slot.pending
+ slot.pending = undefined
+ if (pending?.lease.isCurrent(serverName)) {
+ const next = this.startAdmission(serverName, byName, slot, pending)
+ void next.catch(error => {
+ console.error(`[Main] MCP queued admission failed: ${serverName}`, error)
+ })
+ } else {
+ byName.delete(serverName)
+ }
+ })
+ scheduled.promise = promise
+ slot.scheduled = scheduled
+ this.admissionTasks.add(promise)
+ void promise
+ .finally(() => {
+ this.admissionTasks.delete(promise)
+ })
+ .catch(() => undefined)
+ return promise
+ }
+
+ private pruneObsoleteAdmissions(
+ manager: object,
+ nextDesired: ReadonlyMap<string, McpAuthorityEntry>
+ ): void {
+ const byName = this.admissions.get(manager)
+ if (!byName) return
+
+ // Remove only work that has not acquired a permit. Active effects keep
+ // their generation fence, while surviving waiters retain FIFO order.
+ for (const [serverName, slot] of byName) {
+ const nextEpoch = nextDesired.get(serverName)?.admissionEpoch
+ if (slot.pending?.epoch !== nextEpoch) {
+ slot.pending = undefined
+ }
+
+ const scheduled = slot.scheduled
+ if (!scheduled) {
+ byName.delete(serverName)
+ continue
+ }
+ if (scheduled.request.epoch === nextEpoch || scheduled.started) {
+ continue
+ }
+ if (scheduled.cancelWaiting?.() !== true) {
+ continue
+ }
+
+ scheduled.cancelWaiting = undefined
+ slot.scheduled = undefined
+ byName.delete(serverName)
+ this.admissionTasks.delete(scheduled.promise)
+ }
+ }
+
+ scheduleCleanup(cleanup: () => Promise<void>): void {
+ let task!: Promise<void>
+ task = this.withPermit('cleanup', () => this.runCleanupWithTimeout(cleanup))
+ .catch(error => {
+ console.error('[Main] MCP detached client cleanup failed:', error)
+ })
+ .finally(() => {
+ this.cleanupTasks.delete(task)
+ })
+ this.cleanupTasks.add(task)
+ }
+
+ async drainCleanups(): Promise<void> {
+ while (this.cleanupTasks.size > 0) {
+ await Promise.all([...this.cleanupTasks])
+ }
+ }
+
+ async drainForShutdown(): Promise<void> {
+ const admissionsDrained = this.drainAdmissions()
+ const timedOut = Symbol('admission-drain-timeout')
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const timeout = new Promise<typeof timedOut>(resolve => {
+ timer = setTimeout(() => resolve(timedOut), this.admissionDrainTimeoutMs)
+ })
+ try {
+ const result = await Promise.race([admissionsDrained, timeout])
+ if (result === timedOut) {
+ console.warn(
+ `[Main] MCP admission drain exceeded ${this.admissionDrainTimeoutMs}ms; abandoning transport wait`
+ )
+ }
+ } finally {
+ if (timer) clearTimeout(timer)
+ }
+ await this.drainCleanups()
+ }
+
+ private async drainAdmissions(): Promise<void> {
+ while (this.admissionTasks.size > 0) {
+ await Promise.allSettled([...this.admissionTasks])
+ }
+ }
+
+ private async runCleanupWithTimeout(cleanup: () => Promise<void>): Promise<void> {
+ const timedOut = Symbol('cleanup-timeout')
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const cleanupResult = Promise.resolve()
+ .then(cleanup)
+ .then(() => undefined)
+ const timeoutResult = new Promise<typeof timedOut>(resolve => {
+ timer = setTimeout(() => resolve(timedOut), this.cleanupTimeoutMs)
+ })
+ try {
+ const result = await Promise.race([cleanupResult, timeoutResult])
+ if (result === timedOut) {
+ console.warn(
+ `[Main] MCP detached client cleanup exceeded ${this.cleanupTimeoutMs}ms; abandoning wait`
+ )
+ }
+ } finally {
+ if (timer) clearTimeout(timer)
+ }
+ }
+
+ private async withPermit(
+ lane: 'admission' | 'cleanup',
+ effect: () => Promise<void>,
+ setCancelWaiting?: (cancelWaiting: (() => boolean) | undefined) => void
+ ): Promise<void> {
+ const activeKey = lane === 'admission' ? 'admissionActive' : 'cleanupActive'
+ const waiters = lane === 'admission' ? this.admissionWaiters : this.cleanupWaiters
+ const limit = lane === 'admission' ? this.maxAdmissions : this.maxCleanups
+ if (this[activeKey] >= limit) {
+ const acquired = await new Promise<boolean>(resolve => {
+ const waiter: McpPermitWaiter = {
+ grant: () => resolve(true),
+ }
+ waiters.push(waiter)
+ setCancelWaiting?.(() => {
+ const waiterIndex = waiters.indexOf(waiter)
+ if (waiterIndex < 0) return false
+ waiters.splice(waiterIndex, 1)
+ resolve(false)
+ return true
+ })
+ })
+ setCancelWaiting?.(undefined)
+ if (!acquired) return
+ } else {
+ this[activeKey] += 1
+ }
+ try {
+ await effect()
+ } finally {
+ const next = waiters.shift()
+ if (next) {
+ next.grant()
+ } else {
+ this[activeKey] -= 1
+ }
+ }
+ }
+}
+
+function resolveMcpFleetConcurrency(maxConcurrency?: number): number {
+ const resolved = maxConcurrency ?? DEFAULT_MCP_FLEET_RECONCILE_MAX_CONCURRENCY
+ if (!Number.isInteger(resolved) || resolved < 1) {
+ throw new Error('MCP fleet reconciliation concurrency must be a positive integer')
+ }
+ return resolved
+}
+
+async function runMcpFleetEffects<T>(
+ items: readonly T[],
+ maxConcurrency: number,
+ effect: (item: T) => Promise<void>
+): Promise<void> {
+ let nextIndex = 0
+ const workers = Array.from({ length: Math.min(maxConcurrency, items.length) }, async () => {
+ while (nextIndex < items.length) {
+ const item = items[nextIndex]
+ nextIndex += 1
+ await effect(item)
+ }
+ })
+ await Promise.all(workers)
+}
+
+async function resolveRequiredMcpAuthToken(
+ server: McpServerInfo,
+ getAuthToken: (serverName: string) => Promise<string | undefined>
+): Promise<string | undefined> {
+ if (
+ !server.enabled ||
+ !server.status?.ready ||
+ server.status.authoritative === false ||
+ !server.auth?.secretRef
+ ) {
+ return undefined
+ }
+
+ const authToken = await getAuthToken(server.name)
+ if (!authToken) {
+ throw new Error(`Required auth token is unavailable for MCP server ${server.name}`)
+ }
+ return authToken
+}
+
+/**
+ * Apply an authoritative MCP fleet snapshot with per-server admission.
+ *
+ * On cold start, healthy and intentionally skipped servers are published
+ * immediately while failed revisions remain retryable. When a prior manager
+ * exists, replacement remains atomic: any admission failure rejects and
+ * cleans up the candidate without retiring the live fleet.
+ */
+export async function replaceAuthoritativeMcpFleet<
+ TManager extends AuthoritativeMcpFleetManager,
+>(options: {
+ servers: McpServerInfo[]
+ previousManager: { disconnectAll(): Promise<void> } | null
+ createManager: () => TManager
+ getAuthToken: (serverName: string) => Promise<string | undefined>
+ installFleet: (manager: TManager, serverState: Map<string, string>) => void
+ maxConcurrency?: number
+ coordinator?: AuthoritativeMcpFleetCoordinator
+ onColdStartPublished?: () => void
+ isPreviousManagerCurrent?: () => boolean
+ isFleetLifecycleCurrent?: () => boolean
+}): Promise<void> {
+ const maxConcurrency = resolveMcpFleetConcurrency(options.maxConcurrency)
+ if (options.isFleetLifecycleCurrent?.() === false) return
+ const nextManager = options.createManager()
+ // A replacement candidate must not supersede the live manager's authority
+ // epoch until its complete fleet has admitted and installFleet commits it.
+ const coordinator = options.previousManager
+ ? new AuthoritativeMcpFleetCoordinator(maxConcurrency, maxConcurrency)
+ : (options.coordinator ?? new AuthoritativeMcpFleetCoordinator(maxConcurrency, maxConcurrency))
+ const previousAuthorityIsCurrent =
+ options.previousManager && options.coordinator
+ ? options.coordinator.captureManagerRevision(options.previousManager)
+ : undefined
+ const lease = coordinator.publishSnapshot(nextManager, options.servers)
+ const nextServerState = new Map<string, string>()
+ const admissionFailures: unknown[] = []
+ const coldStart = options.previousManager === null
+
+ try {
+ // Publish the empty manager before cold-start admission begins. The agent
+ // reads this manager by reference, so independently admitted healthy peers
+ // become usable immediately instead of waiting for the slowest fleet
+ // member. Replacements keep the prior manager installed until the complete
+ // candidate succeeds below.
+ if (coldStart) {
+ if (options.isFleetLifecycleCurrent?.() === false) {
+ throw new Error('MCP fleet initialization was superseded before publish')
+ }
+ options.installFleet(nextManager, nextServerState)
+ options.onColdStartPublished?.()
+ }
+
+ const admitServer = async (server: McpServerInfo, isCurrent: () => boolean): Promise<void> => {
+ if (!isCurrent()) return
+ let authToken: string | undefined
+ try {
+ authToken = await resolveRequiredMcpAuthToken(server, options.getAuthToken)
+ } catch (error) {
+ if (!isCurrent()) return
+ // Auth discovery fails before addServer can own the status transition.
+ nextManager.recordAdmissionFailure(server, error)
+ admissionFailures.push(error)
+ console.error(`[Main] MCP server admission failed; will retry: ${server.name}`, error)
+ return
+ }
+
+ try {
+ await nextManager.addServer(server, authToken, {
+ isCurrent,
+ onCommit: () => {
+ if (isCurrent()) {
+ nextServerState.set(server.name, JSON.stringify(server))
+ }
+ },
+ scheduleCleanup: cleanup => coordinator.scheduleCleanup(cleanup),
+ })
+ } catch (error) {
+ if (!isCurrent()) return
+ // addServer owns connection-failure status. Avoid recording the same
+ // transition twice while keeping the desired revision retryable.
+ admissionFailures.push(error)
+ console.error(`[Main] MCP server admission failed; will retry: ${server.name}`, error)
+ }
+ }
+
+ // Distinct McpServers own disjoint client/status/tool-map entries. Admit
+ // them independently through a finite worker pool so one slow connection
+ // cannot head-of-line block a healthy peer and a large fleet cannot create
+ // an unbounded connection burst. Each failure remains retryable above.
+ await runMcpFleetEffects(options.servers, maxConcurrency, server =>
+ coordinator.runAdmission(nextManager, server.name, lease, isCurrent =>
+ admitServer(server, () => isCurrent() && options.isFleetLifecycleCurrent?.() !== false)
+ )
+ )
+
+ // Cold start may publish healthy peers so HCC readiness is independent of
+ // full-fleet convergence. A live prior fleet is safer to preserve
+ // atomically until its complete replacement candidate is admitted.
+ if (options.previousManager) {
+ if (admissionFailures.length > 0) {
+ throw admissionFailures[0]
+ }
+ if (
+ options.isFleetLifecycleCurrent?.() === false ||
+ options.isPreviousManagerCurrent?.() === false ||
+ previousAuthorityIsCurrent?.() === false
+ ) {
+ throw new Error('MCP fleet replacement candidate was superseded before commit')
+ }
+ }
+
+ if (!coldStart) {
+ options.installFleet(nextManager, nextServerState)
+ options.coordinator?.publishSnapshot(nextManager, options.servers)
+ }
+ } catch (error) {
+ coordinator.closeManager(nextManager)
+ try {
+ await nextManager.disconnectAll()
+ } catch (cleanupError) {
+ console.error('[Main] Failed to clean up rejected MCP fleet candidate:', cleanupError)
+ }
+ throw error
+ }
+
+ // installFleet is the commit point. Once the accepted candidate is visible,
+ // failure to retire stale connections must not invalidate or retry the
+ // already-committed authoritative fleet.
+ if (options.previousManager && options.previousManager !== nextManager) {
+ try {
+ await options.previousManager.disconnectAll()
+ } catch (cleanupError) {
+ console.error('[Main] Failed to retire previous MCP fleet after replacement:', cleanupError)
+ }
+ }
+}
+
+interface AuthoritativeMcpSnapshotManager {
+ addServer(
+ server: McpServerInfo,
+ authToken?: string,
+ control?: McpAdmissionControl
+ ): Promise<McpAdmissionOutcome>
+ replaceServer(
+ server: McpServerInfo,
+ authToken?: string,
+ control?: McpAdmissionControl
+ ): Promise<McpAdmissionOutcome>
+ removeServer(serverName: string): Promise<void>
+ detachServer?(serverName: string): () => Promise<void>
+ getConnectedServers(): string[]
+ getKnownServers(): string[]
+ recordAdmissionFailure(server: McpServerInfo, error: unknown): void
+}
+
+function canonicalJson(value: unknown): string {
+ if (Array.isArray(value)) {
+ return `[${value.map(canonicalJson).join(',')}]`
+ }
+ if (value !== null && typeof value === 'object') {
+ const entries = Object.entries(value as Record<string, unknown>)
+ .filter(([, entryValue]) => entryValue !== undefined)
+ .sort(([left], [right]) => left.localeCompare(right))
+ return `{${entries
+ .map(([key, entryValue]) => `${JSON.stringify(key)}:${canonicalJson(entryValue)}`)
+ .join(',')}}`
+ }
+ return JSON.stringify(value) ?? 'null'
+}
+
+function mcpServerDesiredRevision(server: McpServerInfo): string {
+ const { status: _observedStatus, ...desired } = server
+ return canonicalJson(desired)
+}
+
+/**
+ * Apply one authoritative inventory snapshot without confusing transient
+ * observed readiness with a desired server revision.
+ */
+export async function reconcileAuthoritativeMcpSnapshot(options: {
+ servers: McpServerInfo[]
+ manager: AuthoritativeMcpSnapshotManager
+ serverState: Map<string, string>
+ getAuthToken: (serverName: string) => Promise<string | undefined>
+ maxConcurrency?: number
+ coordinator?: AuthoritativeMcpFleetCoordinator
+}): Promise<void> {
+ const maxConcurrency = resolveMcpFleetConcurrency(options.maxConcurrency)
+ const coordinator =
+ options.coordinator ?? new AuthoritativeMcpFleetCoordinator(maxConcurrency, maxConcurrency)
+ // Snapshot publication is synchronous and precedes every manager read or
+ // network effect. It invalidates stale initial/poll candidates immediately.
+ const lease = coordinator.publishSnapshot(options.manager, options.servers)
+ const currentNames = new Set(options.servers.map(server => server.name))
+ // Failed admission revisions intentionally stay out of serverState so an
+ // identical later snapshot retries them. They are still manager-known
+ // inventory/status entries and must participate in authoritative deletion,
+ // otherwise a removed failed-only server remains ghosted forever.
+ const previousNames = new Set([
+ ...options.serverState.keys(),
+ ...options.manager.getKnownServers(),
+ ])
+ const connectedNames = new Set(options.manager.getConnectedServers())
+
+ // Revoke live exposure synchronously for every authoritative delete,
+ // disabled server, or authoritative not-ready server before starting any
+ // admission/cleanup I/O. Cleanup is scheduled through its own bounded lane,
+ // so a hung disconnect cannot delay the rest of the snapshot.
+ if (options.manager.detachServer) {
+ for (const name of previousNames) {
+ if (!currentNames.has(name) && lease.isAbsentCurrent(name)) {
+ coordinator.scheduleCleanup(options.manager.detachServer(name))
+ options.serverState.delete(name)
+ }
+ }
+ for (const server of options.servers) {
+ const previousState = options.serverState.get(server.name)
+ const desiredChanged =
+ previousState !== undefined &&
+ mcpServerDesiredRevision(JSON.parse(previousState) as McpServerInfo) !==
+ mcpServerDesiredRevision(server)
+ const revokesLiveConnection =
+ connectedNames.has(server.name) &&
+ (!server.enabled ||
+ (server.status?.authoritative !== false && server.status?.ready === false) ||
+ (server.status?.authoritative === false && desiredChanged))
+ if (revokesLiveConnection && lease.isCurrent(server.name)) {
+ coordinator.scheduleCleanup(options.manager.detachServer(server.name))
+ }
+ }
+ }
+
+ const resolveAuthToken = async (
+ server: McpServerInfo,
+ isCurrent: () => boolean
+ ): Promise<string | undefined> => {
+ try {
+ return await resolveRequiredMcpAuthToken(server, options.getAuthToken)
+ } catch (error) {
+ // Auth discovery fails before manager admission. Preserve a live
+ // connection's status during replacement; otherwise publish the
+ // admission failure exactly once.
+ if (isCurrent() && !connectedNames.has(server.name)) {
+ options.manager.recordAdmissionFailure(server, error)
+ }
+ throw error
+ }
+ }
+
+ const reconcileServer = async (
+ server: McpServerInfo,
+ isCurrent: () => boolean
+ ): Promise<void> => {
+ if (!isCurrent()) return
+ const previousState = options.serverState.get(server.name)
+ const currentState = JSON.stringify(server)
+ const control: Required<McpAdmissionControl> = {
+ isCurrent,
+ onCommit: () => {
+ if (isCurrent()) {
+ options.serverState.set(server.name, currentState)
+ }
+ },
+ scheduleCleanup: cleanup => coordinator.scheduleCleanup(cleanup),
+ }
+
+ if (!previousState) {
+ const authToken = await resolveAuthToken(server, isCurrent)
+ await options.manager.addServer(server, authToken, control)
+ return
+ }
+
+ const previousServer = JSON.parse(previousState) as McpServerInfo
+ const desiredChanged =
+ mcpServerDesiredRevision(previousServer) !== mcpServerDesiredRevision(server)
+
+ if (desiredChanged) {
+ if (server.status?.authoritative === false) {
+ await options.manager.removeServer(server.name)
+ // Reuse the manager's fail-closed admission path to keep the expected
+ // server visible as not_ready without opening a connection.
+ await options.manager.addServer(server, undefined, control)
+ return
+ }
+
+ if (!server.enabled || !server.status?.ready) {
+ await options.manager.removeServer(server.name)
+ await options.manager.addServer(server, undefined, control)
+ return
+ }
+
+ // A ready authoritative desired revision is connected before commit.
+ // Failure leaves the previous connection and recorded revision intact,
+ // so an identical later snapshot retries it.
+ const authToken = await resolveAuthToken(server, isCurrent)
+ await options.manager.replaceServer(server, authToken, control)
+ return
+ }
+
+ if (server.status?.authoritative === false) {
+ // The producer explicitly could not establish status authority. Record
+ // the snapshot, but never use it to open a connection. An existing live
+ // connection remains valid until authoritative status or desired/delete
+ // state says otherwise.
+ if (isCurrent()) {
+ options.serverState.set(server.name, currentState)
+ }
+ return
+ }
+
+ if (!server.status?.ready) {
+ // An authoritative ready=false, and a legacy ready=false with no
+ // authority marker, retain the existing fail-closed behavior. Re-adding
+ // a not-ready server does not connect; it updates observed status.
+ if (connectedNames.has(server.name)) {
+ await options.manager.removeServer(server.name)
+ }
+ await options.manager.addServer(server, undefined, control)
+ return
+ }
+
+ // A previously not-ready server was intentionally recorded without a
+ // connection. Admit it once the authoritative snapshot reports it ready.
+ if (!connectedNames.has(server.name) && server.enabled) {
+ const authToken = await resolveAuthToken(server, isCurrent)
+ await options.manager.addServer(server, authToken, control)
+ return
+ }
+
+ // Status-only degradation is still an authoritative observation, but it
+ // must not tear down a live connection that may remain healthy.
+ if (isCurrent()) {
+ options.serverState.set(server.name, currentState)
+ }
+ }
+
+ const effects: Array<() => Promise<void>> = []
+ // Authoritative absence is a revocation signal. Queue deletions before
+ // admissions so a full budget of slow new peers cannot delay retiring
+ // servers that are no longer desired.
+ for (const name of previousNames) {
+ if (!currentNames.has(name)) {
+ if (options.manager.detachServer) continue
+ effects.push(async () => {
+ try {
+ if (!lease.isAbsentCurrent(name)) return
+ await options.manager.removeServer(name)
+ if (lease.isAbsentCurrent(name)) {
+ options.serverState.delete(name)
+ }
+ } catch (error) {
+ console.error(`[Main] MCP server deletion failed; will retry: ${name}`, error)
+ }
+ })
+ }
+ }
+ for (const server of options.servers) {
+ effects.push(async () => {
+ try {
+ await coordinator.runAdmission(options.manager, server.name, lease, isCurrent =>
+ reconcileServer(server, isCurrent)
+ )
+ } catch (error) {
+ console.error(`[Main] MCP server reconciliation failed; will retry: ${server.name}`, error)
+ }
+ })
+ }
+
+ // A coalesced poll owns one authoritative snapshot at a time. Within that
+ // snapshot each server key is unique, and desired keys are disjoint from
+ // deletion keys, so effects can progress independently under one bounded
+ // fleet-wide budget without weakening same-server ordering.
+ const reconciliation = runMcpFleetEffects(effects, maxConcurrency, effect => effect())
+ if (coordinator.reconcilesInBackground) {
+ void reconciliation.catch(error => {
+ console.error('[Main] MCP background snapshot reconciliation failed:', error)
+ })
+ return
+ }
+ await reconciliation
+}
+
+export async function pollAuthoritativeMcpSnapshotIfCurrent(options: {
+ poll: () => Promise<{ servers: McpServerInfo[] }>
+ isCurrent: () => boolean
+ reconcile: (servers: McpServerInfo[]) => Promise<void>
+}): Promise<void> {
+ const { servers } = await options.poll()
+ if (!options.isCurrent()) return
+ await options.reconcile(servers)
+}
diff --git a/mcp-host/src/mcp/client.ts b/mcp-host/src/mcp/client.ts
index 278f8a122..f0d9a7161 100644
--- a/mcp-host/src/mcp/client.ts
+++ b/mcp-host/src/mcp/client.ts
@@ -5,7 +5,6 @@
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 { McpServerInfo, McpTool } from '../types'
const DEFAULT_MCP_TOOL_TIMEOUT_MS = 3_600_000
@@ -13,6 +12,8 @@ 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'
+type SupportedMcpTransport = SSEClientTransport | StreamableHTTPClientTransport
+
export interface McpToolCallOptions {
timeoutMs?: number
signal?: AbortSignal
@@ -24,6 +25,10 @@ interface McpSdkRequestOptions {
signal?: AbortSignal
}
+type McpProbeResult =
+ | { ok: true; toolCount: number }
+ | { ok: false; error: unknown; stale: boolean }
+
function readPositiveSafeIntegerEnv(name: string, defaultValue: number): number {
const raw = process.env[name]
if (raw === undefined || raw === '') return defaultValue
@@ -128,13 +133,16 @@ function requestOptions(
export class McpClient {
private client: Client | null = null
- private transport: Transport | null = null
+ private transport: SupportedMcpTransport | null = null
private serverConfig: McpServerInfo
private authToken?: string
private proxyUrl?: string
private tools: McpTool[] = []
private connected: boolean = false
private reconnectPromise: Promise<void> | null = null
+ private connectionEpoch = 0
+ private retired = false
+ private readonly transportCleanups = new WeakMap<SupportedMcpTransport, Promise<void>>()
constructor(serverConfig: McpServerInfo, authToken?: string, proxyUrl?: string) {
this.serverConfig = serverConfig
@@ -154,6 +162,70 @@ export class McpClient {
return this.tools
}
+ private lifecycleError(reason: 'closed' | 'superseded'): Error {
+ return new Error(`MCP client ${this.name} is ${reason}`)
+ }
+
+ private ensureNotRetired(): void {
+ if (this.retired) throw this.lifecycleError('closed')
+ }
+
+ private isCurrentConnection(
+ epoch: number,
+ client: Client,
+ transport: SupportedMcpTransport
+ ): boolean {
+ return (
+ !this.retired &&
+ this.connectionEpoch === epoch &&
+ this.client === client &&
+ this.transport === transport
+ )
+ }
+
+ private isCallCurrent(epoch: number, client: Client): boolean {
+ return (
+ !this.retired && this.connectionEpoch === epoch && this.client === client && this.connected
+ )
+ }
+
+ private ensureCallCurrent(epoch: number, client: Client): void {
+ if (this.isCallCurrent(epoch, client)) return
+ throw this.lifecycleError(this.retired ? 'closed' : 'superseded')
+ }
+
+ private detachConnection(): () => Promise<void> {
+ const transport = this.transport
+ this.connectionEpoch += 1
+ this.client = null
+ this.transport = null
+ this.connected = false
+ this.tools = []
+
+ // Start physical I/O revocation now. The cleanup lane owns only awaiting
+ // this shared promise, so a saturated cleanup queue cannot leave an
+ // authenticated transport active after local authority was revoked.
+ const cleanup = transport ? this.closeCapturedTransport(transport) : Promise.resolve()
+ return () => cleanup
+ }
+
+ private closeCapturedTransport(transport: SupportedMcpTransport): Promise<void> {
+ const existingCleanup = this.transportCleanups.get(transport)
+ if (existingCleanup) return existingCleanup
+
+ let cleanup: Promise<void>
+ try {
+ // Both supported SDK transports abort their active I/O synchronously
+ // inside close(). Invoke it before returning while sharing the resulting
+ // cleanup across retirement and late connection continuations.
+ cleanup = transport.close().catch(() => undefined)
+ } catch {
+ cleanup = Promise.resolve()
+ }
+ this.transportCleanups.set(transport, cleanup)
+ return cleanup
+ }
+
/**
* Create the appropriate transport based on server configuration.
*/
@@ -167,7 +239,7 @@ export class McpClient {
return transport.url || `http://${this.serverConfig.name}.mcp-server.svc.cluster.local:3000/mcp`
}
- private createTransport(): Transport {
+ private createTransport(): SupportedMcpTransport {
const { transport } = this.serverConfig
const headers: Record<string, string> = {}
@@ -203,39 +275,55 @@ export class McpClient {
console.log(`[MCP:${this.name}] Connecting to ${transport.url} (${transport.type})...`)
+ this.ensureNotRetired()
+ const connectionEpoch = ++this.connectionEpoch
+ const nextTransport = this.createTransport()
+ const nextClient = new Client(
+ {
+ name: 'clerum-mcp-host',
+ version: '1.0.0',
+ },
+ {
+ capabilities: {},
+ }
+ )
+ this.transport = nextTransport
+ this.client = nextClient
+
try {
ensureNotAborted(options.signal)
- this.transport = this.createTransport()
-
- // Create MCP client
- this.client = new Client(
- {
- name: 'clerum-mcp-host',
- version: '1.0.0',
- },
- {
- capabilities: {},
- }
- )
// MCP SDK Client.connect() does not currently accept request options.
// Race it against the caller budget/signal so workflow setup cannot
// outlive the step deadline if initialize hangs.
await withRequestTimeout(
- this.client.connect(this.transport),
+ nextClient.connect(nextTransport),
options,
'MCP SDK connect timeout'
)
+ if (!this.isCurrentConnection(connectionEpoch, nextClient, nextTransport)) {
+ throw this.lifecycleError(this.retired ? 'closed' : 'superseded')
+ }
this.connected = true
console.log(`[MCP:${this.name}] Connected successfully`)
// Fetch available tools
await this.refreshTools(options)
+ if (!this.isCurrentConnection(connectionEpoch, nextClient, nextTransport)) {
+ throw this.lifecycleError(this.retired ? 'closed' : 'superseded')
+ }
} catch (error) {
console.error(`[MCP:${this.name}] Failed to connect:`, error)
- this.connected = false
- await this.disconnect().catch(() => undefined)
+ if (this.client === nextClient && this.transport === nextTransport) {
+ this.connectionEpoch += 1
+ this.client = null
+ this.transport = null
+ this.connected = false
+ this.tools = []
+ }
+ await this.closeCapturedTransport(nextTransport)
+ if (this.retired) throw this.lifecycleError('closed')
throw error
}
}
@@ -244,27 +332,29 @@ export class McpClient {
* Disconnect from the MCP server.
*/
async disconnect(): Promise<void> {
- if (this.client) {
- try {
- await this.client.close()
- } catch {
- // Ignore close errors
- }
- this.client = null
- }
- if (this.transport) {
- try {
- await this.transport.close()
- } catch {
- // Ignore close errors
- }
- this.transport = null
- }
- this.connected = false
- this.tools = []
+ // Revoke local authority before close I/O. The SDK Client owns this same
+ // transport and Client.close() only delegates to transport.close(); calling
+ // both duplicates the close and can strand revocation behind a wrapper
+ // promise. The two transports created above abort their EventSource/fetch
+ // synchronously inside close(), and their onclose hook clears Client state.
+ const cleanup = this.detachConnection()
+ await cleanup()
console.log(`[MCP:${this.name}] Disconnected`)
}
+ /**
+ * Permanently revoke this client before scheduling transport cleanup.
+ *
+ * Unlike disconnect(), retirement cannot be followed by an internal
+ * reconnect. Transport abort begins before this method returns; the returned
+ * cleanup only awaits the shared close result, so bounded cleanup lanes do
+ * not delay physical revocation.
+ */
+ retire(): () => Promise<void> {
+ this.retired = true
+ return this.detachConnection()
+ }
+
/**
* Refresh the list of available tools from the server.
*/
@@ -274,27 +364,31 @@ export class McpClient {
return
}
+ const refreshClient = this.client
+ const refreshEpoch = this.connectionEpoch
const sdkRequestOptions = requestOptions(options.timeoutMs, options.signal)
+ let response: Awaited<ReturnType<Client['listTools']>>
try {
- const response = await this.client.listTools(undefined, sdkRequestOptions)
- this.tools = (response.tools || []).map(tool => ({
- name: tool.name,
- description: tool.description,
- inputSchema: tool.inputSchema as Record<string, unknown>,
- serverName: this.name,
- }))
-
- console.log(`[MCP:${this.name}] Found ${this.tools.length} tool(s):`)
- for (const tool of this.tools) {
- console.log(
- `[MCP:${this.name}] - ${tool.name}: ${tool.description || '(no description)'}`
- )
- }
+ response = await refreshClient.listTools(undefined, sdkRequestOptions)
} catch (error) {
+ this.ensureCallCurrent(refreshEpoch, refreshClient)
console.error(`[MCP:${this.name}] Failed to list tools:`, error)
this.tools = []
throw error
}
+
+ this.ensureCallCurrent(refreshEpoch, refreshClient)
+ this.tools = (response.tools || []).map(tool => ({
+ name: tool.name,
+ description: tool.description,
+ inputSchema: tool.inputSchema as Record<string, unknown>,
+ serverName: this.name,
+ }))
+
+ console.log(`[MCP:${this.name}] Found ${this.tools.length} tool(s):`)
+ for (const tool of this.tools) {
+ console.log(`[MCP:${this.name}] - ${tool.name}: ${tool.description || '(no description)'}`)
+ }
}
/**
@@ -315,21 +409,33 @@ export class McpClient {
* transient probe error during a heartbeat doesn't clobber the last known
* tool list.
*/
- async probeTools(
- options: McpToolCallOptions = {}
- ): Promise<{ ok: true; toolCount: number } | { ok: false; error: unknown }> {
+ async probeTools(options: McpToolCallOptions = {}): Promise<McpProbeResult> {
if (!this.client || !this.connected) {
- return { ok: false, error: new Error(`${this.name} is not connected`) }
+ return {
+ ok: false,
+ error: new Error(`${this.name} is not connected`),
+ stale: false,
+ }
}
+ const probeClient = this.client
+ const probeEpoch = this.connectionEpoch
try {
- const response = await this.client.listTools(
+ const response = await probeClient.listTools(
undefined,
requestOptions(options.timeoutMs, options.signal)
)
+ this.ensureCallCurrent(probeEpoch, probeClient)
const toolCount = (response.tools || []).length
return { ok: true, toolCount }
} catch (error) {
- return { ok: false, error }
+ if (!this.isCallCurrent(probeEpoch, probeClient)) {
+ return {
+ ok: false,
+ error: this.lifecycleError(this.retired ? 'closed' : 'superseded'),
+ stale: true,
+ }
+ }
+ return { ok: false, error, stale: false }
}
}
@@ -359,12 +465,14 @@ export class McpClient {
* Reconnect by tearing down the existing client/transport and creating new ones.
*/
async reconnect(options: McpToolCallOptions = {}): Promise<void> {
+ this.ensureNotRetired()
if (this.reconnectPromise) {
return this.reconnectPromise
}
this.reconnectPromise = (async () => {
console.log(`[MCP:${this.name}] Reconnecting...`)
await this.disconnect()
+ this.ensureNotRetired()
await this.connect(options)
})()
try {
@@ -386,6 +494,9 @@ export class McpClient {
if (!this.client || !this.connected) {
throw new Error(`MCP server ${this.name} is not connected`)
}
+ this.ensureNotRetired()
+ const callClient = this.client
+ const callEpoch = this.connectionEpoch
console.log(`[MCP:${this.name}] Calling tool: ${toolName}`)
console.log(`[MCP:${this.name}] Args:`, JSON.stringify(args).substring(0, 200))
@@ -398,7 +509,7 @@ export class McpClient {
try {
ensureNotAborted(options.signal)
- const result = await this.client.callTool(
+ const result = await callClient.callTool(
{
name: toolName,
arguments: args,
@@ -406,22 +517,35 @@ export class McpClient {
undefined,
callRequestOptions()
)
+ this.ensureCallCurrent(callEpoch, callClient)
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')
+ }
if (this.isSessionError(error)) {
console.warn(`[MCP:${this.name}] Session lost, reconnecting and retrying after delay...`)
try {
// Brief delay before reconnect to avoid hammering the server
const retryDelayMs = Math.min(1000, remainingBudgetMs(deadlineMs) ?? 1000)
await new Promise(resolve => setTimeout(resolve, retryDelayMs))
+ this.ensureCallCurrent(callEpoch, callClient)
await this.reconnect({
timeoutMs: remainingBudgetMs(deadlineMs),
signal: options.signal,
})
ensureNotAborted(options.signal)
- const result = await this.client!.callTool(
+ const retryClient = this.client
+ if (!retryClient || !this.connected) throw this.lifecycleError('superseded')
+ const retryEpoch = this.connectionEpoch
+ const result = await retryClient.callTool(
{
name: toolName,
arguments: args,
@@ -429,6 +553,7 @@ export class McpClient {
undefined,
callRequestOptions()
)
+ this.ensureCallCurrent(retryEpoch, retryClient)
console.log(
`[MCP:${this.name}] Tool result (after reconnect):`,
JSON.stringify(result).substring(0, 200)
diff --git a/mcp-host/src/mcp/manager.ts b/mcp-host/src/mcp/manager.ts
index a13a18717..ab295411d 100644
--- a/mcp-host/src/mcp/manager.ts
+++ b/mcp-host/src/mcp/manager.ts
@@ -5,10 +5,32 @@ import { McpServerInfo, McpTool, ToolCallResult } from '../types'
import { McpClient, type McpToolCallOptions } from './client'
import { ServerStatusTracker } from './serverStatus'
+export type McpAdmissionOutcome = 'applied' | 'stale'
+export interface McpAdmissionControl {
+ isCurrent?: () => boolean
+ onCommit?: () => void
+ scheduleCleanup?: (cleanup: McpDetachedServerCleanup) => void
+}
+export type McpDetachedServerCleanup = () => Promise<void>
+
+interface PendingAdmission {
+ attempt: symbol
+ client: McpClient
+}
+
+interface ClientRetirement {
+ cleanup: McpDetachedServerCleanup
+ claimed: boolean
+}
+
export class McpManager {
private clients: Map<string, McpClient> = new Map()
private serverInfos: Map<string, McpServerInfo> = new Map()
private toolToServerMap: Map<string, string> = new Map()
+ private pendingAdmissions: Map<string, PendingAdmission> = new Map()
+ private clientRetirements = new WeakMap<McpClient, ClientRetirement>()
+ private lifecycleEpoch = 0
+ private closed = false
private proxyUrl?: string
private statusTracker: ServerStatusTracker
@@ -49,11 +71,47 @@ export class McpManager {
this.statusTracker.markConnected(serverConfig.name, client.availableTools.length)
}
+ private claimClientCleanup(client: McpClient): McpDetachedServerCleanup | undefined {
+ let retirement = this.clientRetirements.get(client)
+ if (!retirement) {
+ const cleanupClient = client.retire()
+ let cleanupPromise: Promise<void> | undefined
+ retirement = {
+ claimed: false,
+ cleanup: () => {
+ if (!cleanupPromise) {
+ try {
+ cleanupPromise = Promise.resolve(cleanupClient())
+ } catch (error) {
+ cleanupPromise = Promise.reject(error)
+ }
+ }
+ return cleanupPromise
+ },
+ }
+ this.clientRetirements.set(client, retirement)
+ }
+ if (retirement.claimed) return undefined
+ retirement.claimed = true
+ return retirement.cleanup
+ }
+
+ private scheduleClientCleanup(client: McpClient, control: McpAdmissionControl): Promise<void> {
+ const cleanup = this.claimClientCleanup(client)
+ if (!cleanup) return Promise.resolve()
+ if (control.scheduleCleanup) {
+ control.scheduleCleanup(cleanup)
+ return Promise.resolve()
+ }
+ return cleanup().catch(() => undefined)
+ }
+
/**
* Retain an admission failure for inventory/status reporting when failure
* occurs before McpClient.connect (for example, auth-token discovery).
*/
recordAdmissionFailure(serverConfig: McpServerInfo, error: unknown): void {
+ if (this.closed) return
this.serverInfos.set(serverConfig.name, serverConfig)
this.statusTracker.markFailed(serverConfig.name, error)
}
@@ -61,13 +119,24 @@ export class McpManager {
/**
* Add and connect to an MCP server.
*/
- async addServer(serverConfig: McpServerInfo, authToken?: string): Promise<void> {
+ async addServer(
+ serverConfig: McpServerInfo,
+ authToken?: string,
+ control: McpAdmissionControl = {}
+ ): Promise<McpAdmissionOutcome> {
+ const admissionLifecycleEpoch = this.lifecycleEpoch
+ const externalIsCurrent = control.isCurrent ?? (() => true)
+ const isCurrent = (): boolean =>
+ !this.closed && this.lifecycleEpoch === admissionLifecycleEpoch && externalIsCurrent()
+ if (!isCurrent()) return 'stale'
+
// Skip disabled servers — operator intent, not infra failure.
if (!serverConfig.enabled) {
console.log(`[McpManager] Skipping disabled server: ${serverConfig.name}`)
this.serverInfos.set(serverConfig.name, serverConfig)
this.statusTracker.markDisabled(serverConfig.name)
- return
+ control.onCommit?.()
+ return 'applied'
}
// Explicitly non-authoritative readiness is a fail-closed admission
@@ -78,7 +147,8 @@ export class McpManager {
)
this.serverInfos.set(serverConfig.name, serverConfig)
this.statusTracker.markNotReady(serverConfig.name, serverConfig.status?.message)
- return
+ control.onCommit?.()
+ return 'applied'
}
// Skip servers that aren't ready yet — transient infra, surfaced as not_ready.
@@ -88,23 +158,45 @@ export class McpManager {
)
this.serverInfos.set(serverConfig.name, serverConfig)
this.statusTracker.markNotReady(serverConfig.name, serverConfig.status?.message)
- return
+ control.onCommit?.()
+ return 'applied'
}
// Check if already connected
if (this.clients.has(serverConfig.name)) {
- console.log(`[McpManager] Server already connected: ${serverConfig.name}`)
- return
+ const installed = this.serverInfos.get(serverConfig.name)
+ if (installed && JSON.stringify(installed) === JSON.stringify(serverConfig)) {
+ console.log(`[McpManager] Server already connected: ${serverConfig.name}`)
+ control.onCommit?.()
+ return 'applied'
+ }
+ return this.replaceServer(serverConfig, authToken, control)
}
const client = new McpClient(serverConfig, authToken, this.proxyUrl)
+ const attempt = Symbol(serverConfig.name)
+ this.pendingAdmissions.set(serverConfig.name, { attempt, client })
this.statusTracker.markConnecting(serverConfig.name)
try {
await client.connect()
+ if (!isCurrent() || this.pendingAdmissions.get(serverConfig.name)?.attempt !== attempt) {
+ await this.scheduleClientCleanup(client, control)
+ this.discardPendingAdmission(serverConfig.name, attempt)
+ return 'stale'
+ }
+ this.pendingAdmissions.delete(serverConfig.name)
this.installConnectedClient(serverConfig, client)
+ control.onCommit?.()
console.log(`[McpManager] Added server: ${serverConfig.name}`)
+ return 'applied'
} catch (error) {
+ if (!isCurrent() || this.pendingAdmissions.get(serverConfig.name)?.attempt !== attempt) {
+ await this.scheduleClientCleanup(client, control)
+ this.discardPendingAdmission(serverConfig.name, attempt)
+ return 'stale'
+ }
+ this.pendingAdmissions.delete(serverConfig.name)
console.error(`[McpManager] Failed to add server ${serverConfig.name}:`, error)
this.recordAdmissionFailure(serverConfig, error)
// Surface the failed admission so callers can leave this server's
@@ -118,60 +210,89 @@ export class McpManager {
* connection. A candidate failure leaves the previous client, tools,
* serverInfo, and connected status untouched.
*/
- async replaceServer(serverConfig: McpServerInfo, authToken?: string): Promise<void> {
+ async replaceServer(
+ serverConfig: McpServerInfo,
+ authToken?: string,
+ control: McpAdmissionControl = {}
+ ): Promise<McpAdmissionOutcome> {
+ const admissionLifecycleEpoch = this.lifecycleEpoch
+ const externalIsCurrent = control.isCurrent ?? (() => true)
+ const isCurrent = (): boolean =>
+ !this.closed && this.lifecycleEpoch === admissionLifecycleEpoch && externalIsCurrent()
+ if (!isCurrent()) return 'stale'
+
const previousClient = this.clients.get(serverConfig.name)
if (!previousClient) {
- await this.addServer(serverConfig, authToken)
- return
+ return this.addServer(serverConfig, authToken, control)
}
const candidate = new McpClient(serverConfig, authToken, this.proxyUrl)
+ const attempt = Symbol(serverConfig.name)
+ this.pendingAdmissions.set(serverConfig.name, { attempt, client: candidate })
try {
await candidate.connect()
} catch (error) {
- await candidate.disconnect().catch(() => undefined)
+ await this.scheduleClientCleanup(candidate, control)
+ if (!isCurrent() || this.pendingAdmissions.get(serverConfig.name)?.attempt !== attempt) {
+ this.discardPendingAdmission(serverConfig.name, attempt)
+ return 'stale'
+ }
+ this.pendingAdmissions.delete(serverConfig.name)
throw error
}
+ if (!isCurrent() || this.pendingAdmissions.get(serverConfig.name)?.attempt !== attempt) {
+ await this.scheduleClientCleanup(candidate, control)
+ this.discardPendingAdmission(serverConfig.name, attempt)
+ return 'stale'
+ }
+ this.pendingAdmissions.delete(serverConfig.name)
+
// Commit is synchronous: readers see either the complete previous
// revision or the complete connected candidate, never a missing server.
this.installConnectedClient(serverConfig, candidate)
+ control.onCommit?.()
- try {
- await previousClient.disconnect()
- } catch (cleanupError) {
- console.error(
- `[McpManager] Failed to retire previous server ${serverConfig.name}:`,
- cleanupError
- )
- }
+ await this.scheduleClientCleanup(previousClient, control)
console.log(`[McpManager] Replaced server: ${serverConfig.name}`)
+ return 'applied'
}
/**
- * Remove and disconnect from an MCP server.
+ * Revoke an MCP server synchronously, returning bounded async cleanup.
+ *
+ * Callers can detach every server in an authoritative revocation snapshot
+ * before awaiting any potentially slow disconnect. This makes tools and
+ * status fail closed immediately without creating an unbounded cleanup burst.
*/
- async removeServer(serverName: string): Promise<void> {
- const client = this.clients.get(serverName)
- let disconnectError: unknown
- let disconnectFailed = false
+ detachServer(serverName: string): McpDetachedServerCleanup {
+ const pending = this.pendingAdmissions.get(serverName)
+ const clients = new Set(
+ [this.clients.get(serverName), pending?.client].filter(
+ (client): client is McpClient => client !== undefined
+ )
+ )
+ const cleanups = [...clients]
+ .map(client => this.claimClientCleanup(client))
+ .filter((cleanup): cleanup is McpDetachedServerCleanup => cleanup !== undefined)
this.clearToolMappings(serverName)
- try {
- await client?.disconnect()
- } catch (error) {
- disconnectFailed = true
- disconnectError = error
- } finally {
- this.clients.delete(serverName)
- this.serverInfos.delete(serverName)
- this.statusTracker.remove(serverName)
+ this.clients.delete(serverName)
+ this.serverInfos.delete(serverName)
+ this.pendingAdmissions.delete(serverName)
+ this.statusTracker.remove(serverName)
+
+ return async () => {
+ await this.runDetachedCleanups(cleanups)
+ console.log(`[McpManager] Removed server: ${serverName}`)
}
+ }
- console.log(`[McpManager] Removed server: ${serverName}`)
- if (disconnectFailed) {
- throw disconnectError
- }
+ /**
+ * Remove and disconnect from an MCP server.
+ */
+ async removeServer(serverName: string): Promise<void> {
+ await this.detachServer(serverName)()
}
/**
@@ -179,20 +300,48 @@ export class McpManager {
* the one path that allows `connecting` to reappear afterwards.
*/
async disconnectAll(): Promise<void> {
- const serverNames = [...this.clients.keys()]
+ await this.runDetachedCleanups(this.detachAllServers())
+ }
+
+ /**
+ * Permanently close this manager. Unlike disconnectAll(), a closed manager
+ * cannot be authorized again by a delayed poll or direct admission.
+ */
+ async close(scheduleCleanup?: (cleanup: McpDetachedServerCleanup) => void): Promise<void> {
+ if (this.closed) return
+ this.closed = true
+ const cleanups = this.detachAllServers()
+ if (scheduleCleanup) {
+ for (const cleanup of cleanups) {
+ scheduleCleanup(cleanup)
+ }
+ return
+ }
+ await this.runDetachedCleanups(cleanups)
+ }
+
+ private detachAllServers(): McpDetachedServerCleanup[] {
+ this.lifecycleEpoch += 1
+ const serverNames = [...new Set([...this.clients.keys(), ...this.pendingAdmissions.keys()])]
+ const cleanups = serverNames.map(name => this.detachServer(name))
+ this.toolToServerMap.clear()
+ this.serverInfos.clear()
+ this.pendingAdmissions.clear()
+ this.statusTracker.reset()
+ return cleanups
+ }
+
+ private async runDetachedCleanups(cleanups: McpDetachedServerCleanup[]): Promise<void> {
let firstError: unknown
let cleanupFailed = false
- for (const name of serverNames) {
+ for (const cleanup of cleanups) {
try {
- await this.removeServer(name)
+ await cleanup()
} catch (error) {
if (!cleanupFailed) firstError = error
cleanupFailed = true
}
}
- this.toolToServerMap.clear()
- this.serverInfos.clear()
- this.statusTracker.reset()
if (cleanupFailed) {
throw firstError
}
@@ -309,6 +458,8 @@ export class McpManager {
await Promise.all(
entries.map(async ([name, client]) => {
const result = await client.probeTools()
+ if (this.clients.get(name) !== client) return
+ if (!result.ok && result.stale) return
if (result.ok) {
this.statusTracker.updateToolCount(name, result.toolCount)
} else {
@@ -326,6 +477,22 @@ export class McpManager {
return [...this.clients.keys()]
}
+ /**
+ * Get every server represented in manager inventory, including disabled,
+ * not-ready, and failed-admission entries that have no connected client.
+ */
+ getKnownServers(): string[] {
+ return [...new Set([...this.serverInfos.keys(), ...this.pendingAdmissions.keys()])]
+ }
+
+ private discardPendingAdmission(serverName: string, attempt: symbol): void {
+ if (this.pendingAdmissions.get(serverName)?.attempt !== attempt) return
+ this.pendingAdmissions.delete(serverName)
+ if (!this.clients.has(serverName) && !this.serverInfos.has(serverName)) {
+ this.statusTracker.remove(serverName)
+ }
+ }
+
/**
* Check if any servers are connected.
*/