Skip to content

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

TypeScript

chore(pr-205): split mcp-host and rpc-proxy out to #232 and #233

Alfredo Lopezd9bf34894f0c
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index acd624289..d1d1b6c6e 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.220",
+ "version": "0.1.211",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.220",
+ "version": "0.1.211",
"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 576ac3fa7..966d53d88 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.220",
+ "version": "0.1.211",
"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
deleted file mode 100644
index c90bad869..000000000
--- a/mcp-host/src/__tests__/main.mcpInitialization.test.ts
+++ /dev/null
@@ -1,1934 +0,0 @@
-import { describe, expect, it, vi } from 'vitest'
-import {
- admitDevelopmentMcpServers,
- createCoalescedPollRunner,
- startContextMapperPolling,
- stopContextMapperPolling,
-} from '../main'
-import {
- AuthoritativeMcpFleetCoordinator,
- pollAuthoritativeMcpSnapshotIfCurrent,
- reconcileAuthoritativeMcpSnapshot,
- replaceAuthoritativeMcpFleet,
- runAuthoritativeMcpInitialization,
-} from '../mcp/authoritativeFleet'
-import { McpManager } from '../mcp/manager'
-import type { McpServerInfo } from '../types'
-
-function readyServer(overrides: Partial<McpServerInfo> = {}): McpServerInfo {
- return {
- name: 'secured-server',
- contextRef: 'production',
- transport: { type: 'streamableHttp', url: 'http://secured-server.test/mcp' },
- auth: { type: 'bearer', secretRef: 'secured-server-auth' },
- enabled: true,
- status: { deployed: true, ready: true },
- ...overrides,
- }
-}
-
-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 = appliedAdmission(async server => {
- if (server.name === failedServer.name) {
- throw new Error('MCP connect failed')
- }
- })
-
- await expect(
- admitDevelopmentMcpServers([firstServer, failedServer, thirdServer], { addServer })
- ).resolves.toBeUndefined()
-
- expect(addServer).toHaveBeenCalledTimes(3)
- expect(addServer).toHaveBeenNthCalledWith(1, firstServer)
- expect(addServer).toHaveBeenNthCalledWith(2, failedServer)
- expect(addServer).toHaveBeenNthCalledWith(3, thirdServer)
- })
-})
-
-describe('runAuthoritativeMcpInitialization', () => {
- it('obtains an authoritative snapshot before replacing the current fleet', async () => {
- const effects: string[] = []
- const client = {
- healthCheck: vi.fn(async () => {
- effects.push('ready')
- return true
- }),
- listServersByContext: vi.fn(async () => {
- effects.push('snapshot')
- return []
- }),
- }
-
- await runAuthoritativeMcpInitialization({
- contextRef: 'production',
- client,
- replaceFleet: async servers => {
- effects.push('replace')
- expect(servers).toEqual([])
- },
- sleep: vi.fn(),
- maxRetries: 2,
- })
-
- expect(effects).toEqual(['ready', 'snapshot', 'replace'])
- })
-
- it('preserves the prior fleet when authoritative discovery rejects', async () => {
- const priorManager = { id: 'prior-manager' }
- const priorState = new Map([['existing-server', 'existing-state']])
- let currentManager = priorManager
- let currentState = priorState
- const discoveryError = new Error('HTTP 503: Service Unavailable')
- const replaceFleet = vi.fn(async () => {
- currentManager = { id: 'replacement-manager' }
- currentState = new Map()
- })
-
- await expect(
- runAuthoritativeMcpInitialization({
- contextRef: 'production',
- client: {
- healthCheck: vi.fn().mockResolvedValue(true),
- listServersByContext: vi.fn().mockRejectedValue(discoveryError),
- },
- replaceFleet,
- sleep: vi.fn(),
- maxRetries: 2,
- })
- ).rejects.toBe(discoveryError)
-
- expect(replaceFleet).not.toHaveBeenCalled()
- expect(currentManager).toBe(priorManager)
- 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)
- const healthCheck = vi.fn().mockResolvedValue(false)
- const listServersByContext = vi.fn()
-
- await expect(
- runAuthoritativeMcpInitialization({
- contextRef: 'production',
- client: { healthCheck, listServersByContext },
- replaceFleet,
- sleep,
- maxRetries: 2,
- })
- ).rejects.toThrow('Context Mapper was not ready after 2 attempts')
-
- expect(healthCheck).toHaveBeenCalledTimes(2)
- expect(sleep).toHaveBeenCalledTimes(1)
- expect(listServersByContext).not.toHaveBeenCalled()
- expect(replaceFleet).not.toHaveBeenCalled()
- })
-})
-
-describe('createCoalescedPollRunner', () => {
- it('coalesces overlapping ticks into one bounded trailing poll', async () => {
- let resolveFirst!: () => void
- let resolveSecond!: () => void
- const poll = vi
- .fn()
- .mockImplementationOnce(() => new Promise<void>(resolve => (resolveFirst = resolve)))
- .mockImplementationOnce(() => new Promise<void>(resolve => (resolveSecond = resolve)))
- .mockResolvedValue(undefined)
- const runner = createCoalescedPollRunner(poll)
-
- runner.trigger()
- runner.trigger()
- runner.trigger()
- expect(poll).toHaveBeenCalledTimes(1)
-
- resolveFirst()
- await vi.waitFor(() => expect(poll).toHaveBeenCalledTimes(2))
- resolveSecond()
- await vi.waitFor(() => expect(poll).toHaveBeenCalledTimes(2))
-
- runner.trigger()
- await vi.waitFor(() => expect(poll).toHaveBeenCalledTimes(3))
- })
-
- it('drops a pending trailing poll after stop', async () => {
- let resolveFirst!: () => void
- const poll = vi
- .fn()
- .mockImplementationOnce(() => new Promise<void>(resolve => (resolveFirst = resolve)))
- const runner = createCoalescedPollRunner(poll)
-
- runner.trigger()
- runner.trigger()
- runner.stop()
- resolveFirst()
- await Promise.resolve()
- await Promise.resolve()
-
- expect(poll).toHaveBeenCalledTimes(1)
- })
-})
-
-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()
- try {
- startContextMapperPolling('first-context')
- expect(vi.getTimerCount()).toBe(1)
-
- startContextMapperPolling('replacement-context')
- expect(vi.getTimerCount()).toBe(1)
- } finally {
- stopContextMapperPolling()
- vi.useRealTimers()
- }
- })
-})
-
-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()
- let initializationSettled = false
- const initialization = replaceAuthoritativeMcpFleet({
- servers: [slowServer, healthyServer],
- previousManager: null,
- createManager: () => candidateManager,
- getAuthToken: vi.fn(),
- installFleet: (_manager, serverState) => {
- installedState = serverState
- },
- coordinator,
- onColdStartPublished: pollingStarted,
- maxConcurrency: 2,
- }).finally(() => {
- initializationSettled = true
- })
-
- await slowStarted.promise
- await vi.waitFor(() => expect(connected).toContain(healthyServer.name))
- expect(pollingStarted).toHaveBeenCalledTimes(1)
- await vi.waitFor(() => expect(initializationSettled).toBe(true))
-
- 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
- await vi.waitFor(() =>
- expect(
- (
- coordinator as unknown as {
- admissionTasks: Set<Promise<void>>
- }
- ).admissionTasks.size
- ).toBe(0)
- )
- 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: appliedAdmission(async server => {
- if (server.name === failedServer.name) throw connectError
- }),
- disconnectAll: vi.fn(),
- recordAdmissionFailure: vi.fn(),
- }
- const installFleet = vi.fn()
-
- await replaceAuthoritativeMcpFleet({
- servers: [firstServer, failedServer, thirdServer],
- previousManager: null,
- createManager: () => candidateManager,
- getAuthToken: vi.fn(),
- installFleet,
- })
-
- expect(candidateManager.addServer).toHaveBeenCalledTimes(3)
- // addServer owns connection-failure status; the fleet helper must not
- // duplicate that transition.
- expect(candidateManager.recordAdmissionFailure).not.toHaveBeenCalled()
- expect(installFleet).toHaveBeenCalledWith(
- candidateManager,
- new Map([
- [firstServer.name, JSON.stringify(firstServer)],
- [thirdServer.name, JSON.stringify(thirdServer)],
- ])
- )
- expect(candidateManager.disconnectAll).not.toHaveBeenCalled()
- })
-
- it('publishes a failed auth status without recording its revision', async () => {
- const authError = new Error('HTTP 503: Service Unavailable')
- const candidateManager = {
- addServer: appliedAdmission(),
- disconnectAll: vi.fn().mockResolvedValue(undefined),
- recordAdmissionFailure: vi.fn(),
- }
- const installFleet = vi.fn()
-
- const server = readyServer()
- await replaceAuthoritativeMcpFleet({
- servers: [server],
- previousManager: null,
- createManager: () => candidateManager,
- getAuthToken: vi.fn().mockRejectedValue(authError),
- installFleet,
- })
-
- expect(candidateManager.addServer).not.toHaveBeenCalled()
- expect(candidateManager.recordAdmissionFailure).toHaveBeenCalledWith(server, authError)
- expect(installFleet).toHaveBeenCalledWith(candidateManager, new Map())
- expect(candidateManager.disconnectAll).not.toHaveBeenCalled()
- })
-
- it('preserves an existing fleet when a replacement candidate has an admission failure', async () => {
- const connectError = new Error('MCP connect failed')
- const firstServer = readyServer({ name: 'first-server', auth: { type: 'none' } })
- const failingServer = readyServer({ name: 'failing-server', auth: { type: 'none' } })
- const previousManager = {
- addServer: appliedAdmission(),
- disconnectAll: vi.fn().mockResolvedValue(undefined),
- }
- const candidateManager = {
- addServer: appliedAdmission(async server => {
- if (server.name === failingServer.name) throw connectError
- }),
- disconnectAll: vi.fn().mockResolvedValue(undefined),
- recordAdmissionFailure: vi.fn(),
- }
- const installFleet = vi.fn()
-
- await expect(
- replaceAuthoritativeMcpFleet({
- servers: [firstServer, failingServer],
- previousManager,
- createManager: () => candidateManager,
- getAuthToken: vi.fn(),
- installFleet,
- })
- ).rejects.toBe(connectError)
-
- 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: appliedAdmission(),
- disconnectAll: vi.fn(async () => {
- effects.push('retire-prior')
- }),
- }
- const candidateManager = {
- addServer: appliedAdmission(),
- disconnectAll: vi.fn(),
- recordAdmissionFailure: vi.fn(),
- }
-
- await replaceAuthoritativeMcpFleet({
- servers: [],
- previousManager,
- createManager: () => candidateManager,
- getAuthToken: vi.fn(),
- installFleet: (manager, serverState) => {
- effects.push('install')
- expect(manager).toBe(candidateManager)
- expect(serverState).toEqual(new Map())
- },
- })
-
- expect(effects).toEqual(['install', 'retire-prior'])
- })
-
- it('records an intentional not-ready admission without treating it as a hard failure', async () => {
- const notReady = readyServer({
- status: { deployed: true, ready: false, message: 'Deployment is progressing' },
- })
- const previousManager = {
- addServer: appliedAdmission(),
- disconnectAll: vi.fn().mockResolvedValue(undefined),
- }
- const candidateManager = {
- addServer: appliedAdmission(),
- disconnectAll: vi.fn(),
- recordAdmissionFailure: vi.fn(),
- }
- const installFleet = vi.fn()
-
- await replaceAuthoritativeMcpFleet({
- servers: [notReady],
- previousManager,
- createManager: () => candidateManager,
- getAuthToken: vi.fn(() => {
- throw new Error('auth must not be fetched until the server is ready for admission')
- }),
- installFleet,
- })
-
- expect(candidateManager.addServer).toHaveBeenCalledWith(notReady, undefined, expect.any(Object))
- expect(installFleet).toHaveBeenCalledWith(
- candidateManager,
- new Map([[notReady.name, JSON.stringify(notReady)]])
- )
- expect(previousManager.disconnectAll).toHaveBeenCalledTimes(1)
- })
-
- it('records but never admits an explicitly non-authoritative ready server', async () => {
- const nonAuthoritative = readyServer({
- status: {
- deployed: true,
- ready: true,
- authoritative: false,
- message: 'Status identity could not be verified',
- },
- })
- const previousManager = {
- addServer: appliedAdmission(),
- disconnectAll: vi.fn().mockResolvedValue(undefined),
- }
- const candidateManager = {
- addServer: appliedAdmission(),
- disconnectAll: vi.fn(),
- recordAdmissionFailure: vi.fn(),
- }
- const getAuthToken = vi.fn()
- const installFleet = vi.fn()
-
- await replaceAuthoritativeMcpFleet({
- servers: [nonAuthoritative],
- previousManager,
- createManager: () => candidateManager,
- getAuthToken,
- installFleet,
- })
-
- expect(getAuthToken).not.toHaveBeenCalled()
- expect(candidateManager.addServer).toHaveBeenCalledWith(
- nonAuthoritative,
- undefined,
- expect.any(Object)
- )
- expect(installFleet).toHaveBeenCalledWith(
- candidateManager,
- new Map([[nonAuthoritative.name, JSON.stringify(nonAuthoritative)]])
- )
- })
-
- it('publishes a real not-ready health entry for a non-authoritative cold snapshot', async () => {
- const nonAuthoritative = readyServer({
- status: {
- deployed: true,
- ready: true,
- authoritative: false,
- message: 'Status identity could not be verified',
- },
- })
- let installedManager: McpManager | undefined
-
- await replaceAuthoritativeMcpFleet({
- servers: [nonAuthoritative],
- previousManager: null,
- createManager: () => new McpManager(),
- getAuthToken: vi.fn(),
- installFleet: manager => {
- installedManager = manager
- },
- })
-
- expect(installedManager?.getConnectedServers()).toEqual([])
- expect(installedManager?.status.snapshot()).toEqual([
- expect.objectContaining({
- name: nonAuthoritative.name,
- state: 'failed',
- expected: true,
- reason: 'not_ready',
- message: 'Status identity could not be verified',
- }),
- ])
- })
-
- it('keeps the committed fleet when retiring the prior manager fails', async () => {
- const cleanupError = new Error('disconnect failed')
- const previousManager = {
- addServer: appliedAdmission(),
- disconnectAll: vi.fn().mockRejectedValue(cleanupError),
- }
- const candidateManager = {
- addServer: appliedAdmission(),
- disconnectAll: vi.fn(),
- recordAdmissionFailure: vi.fn(),
- }
- const installFleet = vi.fn()
-
- await expect(
- replaceAuthoritativeMcpFleet({
- servers: [],
- previousManager,
- createManager: () => candidateManager,
- getAuthToken: vi.fn(),
- installFleet,
- })
- ).resolves.toBeUndefined()
-
- expect(installFleet).toHaveBeenCalledWith(candidateManager, new Map())
- expect(previousManager.disconnectAll).toHaveBeenCalledTimes(1)
- expect(candidateManager.disconnectAll).not.toHaveBeenCalled()
- })
-})
-
-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({
- auth: { type: 'none' },
- transport: { type: 'streamableHttp', url: 'http://replacement.test/mcp' },
- status: { deployed: true, ready: true, authoritative: true },
- })
- const connectError = new Error('replacement connect failed')
- const serverState = new Map([[previous.name, JSON.stringify(previous)]])
- const manager = {
- 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 = {
- servers: [modified],
- manager,
- serverState,
- getAuthToken: vi.fn(),
- }
-
- await expect(reconcileAuthoritativeMcpSnapshot(options)).resolves.toBeUndefined()
-
- expect(manager.replaceServer).toHaveBeenCalledWith(modified, undefined, expect.any(Object))
- expect(manager.removeServer).not.toHaveBeenCalled()
- expect(manager.addServer).not.toHaveBeenCalled()
- expect(manager.recordAdmissionFailure).not.toHaveBeenCalled()
- expect(serverState.get(previous.name)).toBe(JSON.stringify(previous))
-
- await expect(reconcileAuthoritativeMcpSnapshot(options)).resolves.toBeUndefined()
- expect(manager.replaceServer).toHaveBeenCalledTimes(2)
- expect(serverState.get(modified.name)).toBe(JSON.stringify(modified))
- })
-
- it('does not tear down a healthy connection for a status-only readiness degradation', async () => {
- const previous = readyServer()
- const degraded = readyServer({
- status: {
- deployed: false,
- ready: false,
- authoritative: false,
- message: 'Deployment status unknown',
- },
- })
- const serverState = new Map([[previous.name, JSON.stringify(previous)]])
- const manager = {
- addServer: appliedAdmission(),
- replaceServer: appliedAdmission(),
- removeServer: vi.fn(),
- getConnectedServers: vi.fn(() => [previous.name]),
- getKnownServers: vi.fn(() => [previous.name]),
- recordAdmissionFailure: vi.fn(),
- }
-
- await reconcileAuthoritativeMcpSnapshot({
- servers: [degraded],
- manager,
- serverState,
- getAuthToken: vi.fn(),
- })
-
- expect(manager.removeServer).not.toHaveBeenCalled()
- expect(manager.addServer).not.toHaveBeenCalled()
- expect(serverState.get(previous.name)).toBe(JSON.stringify(degraded))
- })
-
- it('disconnects and marks not-ready when the false status is authoritative', async () => {
- const effects: string[] = []
- const previous = readyServer()
- const notReady = readyServer({
- status: {
- deployed: true,
- ready: false,
- authoritative: true,
- message: 'Secret validation failed',
- },
- })
- const serverState = new Map([[previous.name, JSON.stringify(previous)]])
- const manager = {
- addServer: appliedAdmission(async () => {
- effects.push('mark-not-ready')
- }),
- replaceServer: appliedAdmission(),
- removeServer: vi.fn(async () => {
- effects.push('remove')
- }),
- getConnectedServers: vi.fn(() => [previous.name]),
- getKnownServers: vi.fn(() => [previous.name]),
- recordAdmissionFailure: vi.fn(),
- }
-
- await reconcileAuthoritativeMcpSnapshot({
- servers: [notReady],
- manager,
- serverState,
- getAuthToken: vi.fn(),
- })
-
- expect(effects).toEqual(['remove', 'mark-not-ready'])
- expect(manager.addServer).toHaveBeenCalledWith(notReady, undefined, expect.any(Object))
- expect(serverState.get(previous.name)).toBe(JSON.stringify(notReady))
- })
-
- it.each([
- [
- 'disabled',
- readyServer({
- enabled: false,
- status: { deployed: true, ready: true, authoritative: true },
- }),
- ],
- [
- 'authoritatively not-ready',
- readyServer({
- status: { deployed: true, ready: false, authoritative: true },
- }),
- ],
- // Absent `authoritative` must keep the legacy fail-closed contract on the
- // synchronous revoke path too. Without this row the condition can be
- // narrowed to `authoritative === true` and every other test still passes.
- [
- 'not-ready without an authoritative field',
- readyServer({
- status: { deployed: false, ready: false, message: 'Deployment not ready' },
- }),
- ],
- ])(
- 'synchronously detaches a connected %s server before asynchronous reconciliation',
- async (_reason, next) => {
- const previous = readyServer()
- const detachServer = vi.fn(() => vi.fn().mockResolvedValue(undefined))
- const manager = {
- addServer: appliedAdmission(),
- replaceServer: appliedAdmission(),
- removeServer: vi.fn().mockResolvedValue(undefined),
- detachServer,
- getConnectedServers: vi.fn(() => [previous.name]),
- getKnownServers: vi.fn(() => [previous.name]),
- recordAdmissionFailure: vi.fn(),
- }
-
- const reconciliation = reconcileAuthoritativeMcpSnapshot({
- servers: [next],
- manager,
- serverState: new Map([[previous.name, JSON.stringify(previous)]]),
- getAuthToken: vi.fn(),
- })
-
- expect(detachServer).toHaveBeenCalledWith(previous.name)
- await reconciliation
- }
- )
-
- it('preserves the legacy fail-closed revocation contract when HCC omits authoritative', async () => {
- const previous = readyServer()
- const legacyNotReady = readyServer({
- status: { deployed: false, ready: false, message: 'Deployment not ready' },
- })
- const serverState = new Map([[previous.name, JSON.stringify(previous)]])
- const manager = {
- addServer: appliedAdmission(),
- replaceServer: appliedAdmission(),
- removeServer: vi.fn().mockResolvedValue(undefined),
- getConnectedServers: vi.fn(() => [previous.name]),
- getKnownServers: vi.fn(() => [previous.name]),
- recordAdmissionFailure: vi.fn(),
- }
-
- await reconcileAuthoritativeMcpSnapshot({
- servers: [legacyNotReady],
- manager,
- serverState,
- getAuthToken: vi.fn(),
- })
-
- expect(manager.removeServer).toHaveBeenCalledWith(previous.name)
- expect(manager.addServer).toHaveBeenCalledWith(
- legacyNotReady,
- undefined,
- expect.objectContaining({ isCurrent: expect.any(Function) })
- )
- expect(serverState.get(previous.name)).toBe(JSON.stringify(legacyNotReady))
- })
-
- it('admits an unconnected server when its observed readiness becomes true', async () => {
- const notReady = readyServer({
- auth: { type: 'none' },
- status: { deployed: true, ready: false },
- })
- const ready = readyServer({
- auth: { type: 'none' },
- status: { deployed: true, ready: true, authoritative: true },
- })
- const serverState = new Map([[notReady.name, JSON.stringify(notReady)]])
- const manager = {
- addServer: appliedAdmission(),
- replaceServer: appliedAdmission(),
- removeServer: vi.fn(),
- getConnectedServers: vi.fn(() => []),
- getKnownServers: vi.fn(() => [notReady.name]),
- recordAdmissionFailure: vi.fn(),
- }
-
- await reconcileAuthoritativeMcpSnapshot({
- servers: [ready],
- manager,
- serverState,
- getAuthToken: vi.fn(),
- })
-
- expect(manager.removeServer).not.toHaveBeenCalled()
- expect(manager.addServer).toHaveBeenCalledWith(ready, undefined, expect.any(Object))
- expect(serverState.get(ready.name)).toBe(JSON.stringify(ready))
- })
-
- it('records but never admits a new explicitly non-authoritative ready snapshot', async () => {
- const nonAuthoritative = readyServer({
- status: {
- deployed: true,
- ready: true,
- authoritative: false,
- message: 'Status identity could not be verified',
- },
- })
- const serverState = new Map<string, string>()
- const manager = {
- addServer: appliedAdmission(),
- replaceServer: appliedAdmission(),
- removeServer: vi.fn(),
- getConnectedServers: vi.fn(() => []),
- getKnownServers: vi.fn(() => []),
- recordAdmissionFailure: vi.fn(),
- }
- const getAuthToken = vi.fn()
-
- await reconcileAuthoritativeMcpSnapshot({
- servers: [nonAuthoritative],
- manager,
- serverState,
- getAuthToken,
- })
-
- expect(getAuthToken).not.toHaveBeenCalled()
- expect(manager.addServer).toHaveBeenCalledWith(nonAuthoritative, undefined, expect.any(Object))
- expect(manager.removeServer).not.toHaveBeenCalled()
- expect(serverState.get(nonAuthoritative.name)).toBe(JSON.stringify(nonAuthoritative))
- })
-
- it('retires a changed desired revision without admitting non-authoritative status', async () => {
- const previous = readyServer()
- const modified = readyServer({
- transport: { type: 'streamableHttp', url: 'http://replacement.test/mcp' },
- status: {
- deployed: true,
- ready: true,
- authoritative: false,
- message: 'Status identity could not be verified',
- },
- })
- const serverState = new Map([[previous.name, JSON.stringify(previous)]])
- const manager = {
- 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()
-
- await reconcileAuthoritativeMcpSnapshot({
- servers: [modified],
- manager,
- serverState,
- getAuthToken,
- })
-
- expect(manager.removeServer).toHaveBeenCalledWith(previous.name)
- expect(getAuthToken).not.toHaveBeenCalled()
- expect(manager.addServer).toHaveBeenCalledWith(modified, undefined, expect.any(Object))
- expect(serverState.get(modified.name)).toBe(JSON.stringify(modified))
- })
-
- it('does not reconnect when desired objects differ only by key insertion order', async () => {
- const current = readyServer({
- auth: { type: 'bearer', secretRef: 'secured-server-auth', secretKey: 'token' },
- })
- const previousWithDifferentKeyOrder = {
- enabled: true,
- transport: {
- url: 'http://secured-server.test/mcp',
- type: 'streamableHttp',
- },
- contextRef: 'production',
- name: 'secured-server',
- auth: { secretKey: 'token', secretRef: 'secured-server-auth', type: 'bearer' },
- status: { ready: true, deployed: true },
- } as McpServerInfo
- const serverState = new Map([[current.name, JSON.stringify(previousWithDifferentKeyOrder)]])
- const manager = {
- addServer: appliedAdmission(),
- replaceServer: appliedAdmission(),
- removeServer: vi.fn(),
- getConnectedServers: vi.fn(() => [current.name]),
- getKnownServers: vi.fn(() => [current.name]),
- recordAdmissionFailure: vi.fn(),
- }
-
- await reconcileAuthoritativeMcpSnapshot({
- servers: [current],
- manager,
- serverState,
- getAuthToken: vi.fn(),
- })
-
- expect(manager.replaceServer).not.toHaveBeenCalled()
- expect(manager.removeServer).not.toHaveBeenCalled()
- expect(manager.addServer).not.toHaveBeenCalled()
- expect(serverState.get(current.name)).toBe(JSON.stringify(current))
- })
-
- it('retains reconnect semantics for a desired transport change', async () => {
- const effects: string[] = []
- const previous = readyServer({ auth: { type: 'none' } })
- const modified = readyServer({
- auth: { type: 'none' },
- transport: { type: 'streamableHttp', url: 'http://replacement.test/mcp' },
- status: {
- deployed: false,
- ready: false,
- authoritative: true,
- message: 'Deployment not ready',
- },
- })
- const serverState = new Map([[previous.name, JSON.stringify(previous)]])
- const manager = {
- addServer: appliedAdmission(async () => {
- effects.push('add')
- }),
- replaceServer: appliedAdmission(),
- removeServer: vi.fn(async () => {
- effects.push('remove')
- }),
- getConnectedServers: vi.fn(() => [previous.name]),
- getKnownServers: vi.fn(() => [previous.name]),
- recordAdmissionFailure: vi.fn(),
- }
-
- await reconcileAuthoritativeMcpSnapshot({
- servers: [modified],
- manager,
- serverState,
- getAuthToken: vi.fn(),
- })
-
- expect(effects).toEqual(['remove', 'add'])
- expect(serverState.get(modified.name)).toBe(JSON.stringify(modified))
- })
-
- it('retains authoritative deletion semantics', async () => {
- const previous = readyServer({ auth: { type: 'none' } })
- const serverState = new Map([[previous.name, JSON.stringify(previous)]])
- const manager = {
- addServer: appliedAdmission(),
- replaceServer: appliedAdmission(),
- removeServer: vi.fn().mockResolvedValue(undefined),
- getConnectedServers: vi.fn(() => [previous.name]),
- getKnownServers: vi.fn(() => [previous.name]),
- recordAdmissionFailure: vi.fn(),
- }
-
- await reconcileAuthoritativeMcpSnapshot({
- servers: [],
- manager,
- serverState,
- getAuthToken: vi.fn(),
- })
-
- expect(manager.removeServer).toHaveBeenCalledWith(previous.name)
- expect(serverState.has(previous.name)).toBe(false)
- })
-
- it('does not record a failed connection twice and leaves its revision retryable', async () => {
- const server = readyServer({ auth: { type: 'none' } })
- const serverState = new Map<string, string>()
- const connectError = new Error('MCP connect failed')
- const manager = {
- addServer: appliedAdmission(vi.fn().mockRejectedValueOnce(connectError)),
- replaceServer: appliedAdmission(),
- removeServer: vi.fn(),
- getConnectedServers: vi.fn(() => []),
- getKnownServers: vi.fn(() => []),
- recordAdmissionFailure: vi.fn(),
- }
- const options = {
- servers: [server],
- manager,
- serverState,
- getAuthToken: vi.fn(),
- }
-
- await expect(reconcileAuthoritativeMcpSnapshot(options)).resolves.toBeUndefined()
- expect(serverState.has(server.name)).toBe(false)
- expect(manager.recordAdmissionFailure).not.toHaveBeenCalled()
-
- await expect(reconcileAuthoritativeMcpSnapshot(options)).resolves.toBeUndefined()
- expect(manager.addServer).toHaveBeenCalledTimes(2)
- expect(serverState.get(server.name)).toBe(JSON.stringify(server))
- })
-
- it('records an auth-discovery failure once and leaves its revision retryable', async () => {
- const server = readyServer()
- const serverState = new Map<string, string>()
- const authError = new Error('auth discovery failed')
- const manager = {
- addServer: appliedAdmission(),
- replaceServer: appliedAdmission(),
- removeServer: vi.fn(),
- getConnectedServers: vi.fn(() => []),
- getKnownServers: vi.fn(() => []),
- recordAdmissionFailure: vi.fn(),
- }
-
- await reconcileAuthoritativeMcpSnapshot({
- servers: [server],
- manager,
- serverState,
- getAuthToken: vi.fn().mockRejectedValue(authError),
- })
-
- expect(manager.addServer).not.toHaveBeenCalled()
- expect(manager.recordAdmissionFailure).toHaveBeenCalledTimes(1)
- expect(manager.recordAdmissionFailure).toHaveBeenCalledWith(server, authError)
- expect(serverState.has(server.name)).toBe(false)
- })
-})
diff --git a/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts b/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts
index b96dfcdda..c474903d1 100644
--- a/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts
+++ b/mcp-host/src/__tests__/mcp/mcpClient.timeout.test.ts
@@ -3,15 +3,12 @@ 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', () => ({
@@ -24,8 +21,6 @@ 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[]) {
@@ -46,21 +41,13 @@ vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({
StreamableHTTPClientTransport: class MockStreamableHTTP {
- async close(...args: unknown[]) {
- sdkState.transportCloseCalls.push([this, ...args])
- const next = sdkState.transportCloseQueue.shift()
- if (next) return next()
- }
+ close = vi.fn().mockResolvedValue(undefined)
},
}))
vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({
SSEClientTransport: class MockSSE {
- async close(...args: unknown[]) {
- sdkState.transportCloseCalls.push([this, ...args])
- const next = sdkState.transportCloseQueue.shift()
- if (next) return next()
- }
+ close = vi.fn().mockResolvedValue(undefined)
},
}))
@@ -74,37 +61,15 @@ 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(() => {
@@ -125,7 +90,7 @@ describe('McpClient SDK request timeouts', () => {
])
})
- it('preserves the caller budget for retry while shared recovery uses its lifecycle budget', async () => {
+ it('preserves timeout options across reconnect retry', async () => {
vi.useFakeTimers()
sdkState.callToolQueue.push(
() => {
@@ -144,202 +109,7 @@ describe('McpClient SDK request timeouts', () => {
expect(sdkState.callToolCalls).toHaveLength(2)
expect(sdkState.callToolCalls[0][2]).toEqual(expect.objectContaining({ timeout: 30_000 }))
expect(sdkState.callToolCalls[1][2]).toEqual(expect.objectContaining({ timeout: 29_000 }))
- expect(sdkState.listToolsCalls[1][1]).toEqual(expect.objectContaining({ timeout: 3_600_000 }))
- })
-
- it('lets a slower peer adopt the completed recovery of their shared session', async () => {
- vi.useFakeTimers()
- sdkState.callToolQueue.push(
- () => {
- throw Object.assign(new Error('session not found'), { code: -32003 })
- },
- () => {
- throw Object.assign(new Error('session not found'), { code: -32003 })
- },
- () => ({ content: [{ type: 'text', text: 'first-after-reconnect' }] }),
- () => ({ content: [{ type: 'text', text: 'second-after-reconnect' }] })
- )
- const c = client()
- await c.connect()
-
- const first = c.callTool('read', { id: 1 }, { timeoutMs: 30_000 })
- await vi.advanceTimersByTimeAsync(500)
- const second = c.callTool('read', { id: 2 }, { timeoutMs: 30_000 })
- const settled = Promise.allSettled([first, second])
- await vi.advanceTimersByTimeAsync(500)
-
- // The first call has already completed the one shared reconnect while the
- // slower peer is still inside its independently budgeted retry delay.
- expect(sdkState.connectCalls).toHaveLength(2)
- expect(sdkState.callToolCalls).toHaveLength(3)
- await vi.advanceTimersByTimeAsync(500)
-
- await expect(settled).resolves.toEqual([
- {
- status: 'fulfilled',
- value: { content: [{ type: 'text', text: 'first-after-reconnect' }] },
- },
- {
- status: 'fulfilled',
- value: { content: [{ type: 'text', text: 'second-after-reconnect' }] },
- },
- ])
- expect(sdkState.connectCalls).toHaveLength(2)
- expect(sdkState.callToolCalls).toHaveLength(4)
- })
-
- it('retries a session error that arrives after a peer has recovered their source', async () => {
- vi.useFakeTimers()
- const lateSessionError = deferred<unknown>()
- sdkState.callToolQueue.push(
- () => {
- throw Object.assign(new Error('session not found'), { code: -32003 })
- },
- () => lateSessionError.promise,
- () => ({ content: [{ type: 'text', text: 'first-after-reconnect' }] }),
- () => ({ content: [{ type: 'text', text: 'late-after-reconnect' }] })
- )
- const c = client()
- await c.connect()
-
- const settled = Promise.allSettled([
- c.callTool('read', { id: 1 }, { timeoutMs: 30_000 }),
- c.callTool('read', { id: 2 }, { timeoutMs: 30_000 }),
- ])
- await vi.advanceTimersByTimeAsync(1000)
- expect(sdkState.connectCalls).toHaveLength(2)
- expect(sdkState.callToolCalls).toHaveLength(3)
-
- lateSessionError.reject(Object.assign(new Error('session not found'), { code: -32003 }))
- await vi.advanceTimersByTimeAsync(1000)
-
- await expect(settled).resolves.toEqual([
- {
- status: 'fulfilled',
- value: { content: [{ type: 'text', text: 'first-after-reconnect' }] },
- },
- {
- status: 'fulfilled',
- value: { content: [{ type: 'text', text: 'late-after-reconnect' }] },
- },
- ])
- expect(sdkState.connectCalls).toHaveLength(2)
- expect(sdkState.callToolCalls).toHaveLength(4)
- })
-
- it('fails all shared recovery waiters closed when the client is retired', async () => {
- vi.useFakeTimers()
- const reconnectHandshake = deferred()
- sdkState.callToolQueue.push(
- () => {
- throw Object.assign(new Error('session not found'), { code: -32003 })
- },
- () => {
- throw Object.assign(new Error('session not found'), { code: -32003 })
- },
- () => ({ content: [{ type: 'text', text: 'must-not-run' }] }),
- () => ({ content: [{ type: 'text', text: 'must-not-run' }] })
- )
- const c = client()
- await c.connect()
- sdkState.connectQueue.push(() => reconnectHandshake.promise)
-
- const settled = Promise.allSettled([
- c.callTool('write', { id: 1 }, { timeoutMs: 30_000 }),
- c.callTool('write', { id: 2 }, { timeoutMs: 30_000 }),
- ])
- await vi.advanceTimersByTimeAsync(1000)
- expect(sdkState.connectCalls).toHaveLength(2)
-
- const closing = retirePermanently(c)
- reconnectHandshake.resolve()
- await closing
- await vi.advanceTimersByTimeAsync(0)
-
- await expect(settled).resolves.toEqual([
- {
- status: 'rejected',
- reason: expect.objectContaining({ message: expect.stringMatching(/closed|superseded/) }),
- },
- {
- status: 'rejected',
- reason: expect.objectContaining({ message: expect.stringMatching(/closed|superseded/) }),
- },
- ])
- expect(sdkState.callToolCalls).toHaveLength(2)
- expect(c.isConnected).toBe(false)
- })
-
- it('keeps shared recovery alive when its first caller exhausts a shorter budget', async () => {
- vi.useFakeTimers()
- const reconnectHandshake = deferred()
- sdkState.callToolQueue.push(
- () => {
- throw Object.assign(new Error('session not found'), { code: -32003 })
- },
- () => {
- throw Object.assign(new Error('session not found'), { code: -32003 })
- },
- () => ({ content: [{ type: 'text', text: 'long-budget-peer-recovered' }] })
- )
- const c = client()
- await c.connect()
- sdkState.connectQueue.push(() => reconnectHandshake.promise)
-
- const shortBudget = c.callTool('read', { id: 1 }, { timeoutMs: 1_500 })
- const shortAssertion = expect(shortBudget).rejects.toThrow('step-timeout')
- const longBudget = c.callTool('read', { id: 2 }, { timeoutMs: 30_000 })
- await vi.advanceTimersByTimeAsync(1000)
- expect(sdkState.connectCalls).toHaveLength(2)
-
- await vi.advanceTimersByTimeAsync(500)
- await shortAssertion
- expect(sdkState.callToolCalls).toHaveLength(2)
-
- reconnectHandshake.resolve()
- await vi.advanceTimersByTimeAsync(0)
- await expect(longBudget).resolves.toEqual({
- content: [{ type: 'text', text: 'long-budget-peer-recovered' }],
- })
- expect(sdkState.connectCalls).toHaveLength(2)
- expect(sdkState.callToolCalls).toHaveLength(3)
- })
-
- it('lets an aborted peer leave shared recovery without cancelling it for another caller', async () => {
- vi.useFakeTimers()
- const reconnectHandshake = deferred()
- const peerController = new AbortController()
- sdkState.callToolQueue.push(
- () => {
- throw Object.assign(new Error('session not found'), { code: -32003 })
- },
- () => {
- throw Object.assign(new Error('session not found'), { code: -32003 })
- },
- () => ({ content: [{ type: 'text', text: 'leader-recovered' }] })
- )
- const c = client()
- await c.connect()
- sdkState.connectQueue.push(() => reconnectHandshake.promise)
-
- const leader = c.callTool('read', { id: 1 }, { timeoutMs: 30_000 })
- const peer = c.callTool('read', { id: 2 }, { timeoutMs: 30_000, signal: peerController.signal })
- const peerAssertion = expect(peer).rejects.toThrow('peer-aborted')
- await vi.advanceTimersByTimeAsync(1000)
- expect(sdkState.connectCalls).toHaveLength(2)
-
- peerController.abort('peer-aborted')
- await peerAssertion
- expect(sdkState.connectCalls).toHaveLength(2)
- expect(sdkState.callToolCalls).toHaveLength(2)
-
- reconnectHandshake.resolve()
- await vi.advanceTimersByTimeAsync(0)
- await expect(leader).resolves.toEqual({
- content: [{ type: 'text', text: 'leader-recovered' }],
- })
- expect(sdkState.connectCalls).toHaveLength(2)
- expect(sdkState.callToolCalls).toHaveLength(3)
+ expect(sdkState.listToolsCalls[1][1]).toEqual(expect.objectContaining({ timeout: 29_000 }))
})
it('does not start reconnect retry after the caller budget is exhausted', async () => {
@@ -359,32 +129,6 @@ describe('McpClient SDK request timeouts', () => {
expect(sdkState.listToolsCalls).toHaveLength(1)
})
- it('does not start reconnect after the caller aborts during the retry delay', async () => {
- vi.useFakeTimers()
- sdkState.callToolQueue.push(() => {
- throw Object.assign(new Error('session not found'), { code: -32003 })
- })
- const controller = new AbortController()
- const c = client()
- await c.connect()
-
- const pending = c.callTool(
- 'write',
- { value: 'side-effect' },
- { timeoutMs: 30_000, signal: controller.signal }
- )
- const assertion = expect(pending).rejects.toThrow('caller-aborted')
- await vi.advanceTimersByTimeAsync(500)
- controller.abort('caller-aborted')
- await vi.advanceTimersByTimeAsync(500)
-
- await assertion
- expect(sdkState.connectCalls).toHaveLength(1)
- expect(sdkState.transportCloseCalls).toHaveLength(0)
- expect(sdkState.callToolCalls).toHaveLength(1)
- expect(c.isConnected).toBe(true)
- })
-
it('fails closed for invalid timeout env before SDK tool discovery', async () => {
vi.stubEnv('CLERUM_MCP_TOOL_TIMEOUT_MS', '0')
const c = client()
@@ -450,7 +194,7 @@ describe('McpClient SDK request timeouts', () => {
expect(sdkState.listToolsCalls[0][1]).toEqual(
expect.objectContaining({ timeout: 5_000, maxTotalTimeout: 5_000 })
)
- expect(sdkState.transportCloseCalls).toHaveLength(1)
+ expect(sdkState.closeCalls).toHaveLength(1)
})
it('abandons SDK connect when the caller budget expires during handshake', async () => {
@@ -466,7 +210,7 @@ describe('McpClient SDK request timeouts', () => {
expect(c.isConnected).toBe(false)
expect(sdkState.connectCalls).toHaveLength(1)
expect(sdkState.listToolsCalls).toHaveLength(0)
- expect(sdkState.transportCloseCalls).toHaveLength(1)
+ expect(sdkState.closeCalls).toHaveLength(1)
})
it('abandons SDK connect when the caller signal aborts during handshake', async () => {
@@ -481,243 +225,6 @@ describe('McpClient SDK request timeouts', () => {
expect(c.isConnected).toBe(false)
expect(sdkState.connectCalls).toHaveLength(1)
expect(sdkState.listToolsCalls).toHaveLength(0)
- 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('rejects all recovery waiters promptly when retired while reconnect never settles', async () => {
- vi.useFakeTimers()
- const reconnectHandshake = deferred()
- sdkState.callToolQueue.push(
- () => {
- throw Object.assign(new Error('session not found'), { code: -32003 })
- },
- () => {
- throw Object.assign(new Error('session not found'), { code: -32003 })
- }
- )
- const c = client()
- await c.connect()
- sdkState.connectQueue.push(() => reconnectHandshake.promise)
-
- const settled = Promise.allSettled([
- c.callTool('write', { id: 1 }, { timeoutMs: 30_000 }),
- c.callTool('write', { id: 2 }, { timeoutMs: 30_000 }),
- ])
- await vi.advanceTimersByTimeAsync(1000)
- expect(sdkState.connectCalls).toHaveLength(2)
-
- await retirePermanently(c)
- await vi.advanceTimersByTimeAsync(0)
-
- await expect(settled).resolves.toEqual([
- {
- status: 'rejected',
- reason: expect.objectContaining({ message: expect.stringMatching(/closed/) }),
- },
- {
- status: 'rejected',
- reason: expect.objectContaining({ message: expect.stringMatching(/closed/) }),
- },
- ])
- expect(sdkState.callToolCalls).toHaveLength(2)
- expect(c.isConnected).toBe(false)
- })
-
- it('does not publish tools discovered after permanent close', async () => {
- const discovery = deferred<{
- tools: Array<{ name: string; description: string; inputSchema: Record<string, unknown> }>
- }>()
- 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,
- })
+ expect(sdkState.closeCalls).toHaveLength(1)
})
})
diff --git a/mcp-host/src/__tests__/mcp/mcpTransportClose.contract.test.ts b/mcp-host/src/__tests__/mcp/mcpTransportClose.contract.test.ts
deleted file mode 100644
index 928e4d169..000000000
--- a/mcp-host/src/__tests__/mcp/mcpTransportClose.contract.test.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-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/__tests__/workflow/workflowRouter.test.ts b/mcp-host/src/__tests__/workflow/workflowRouter.test.ts
index 8c978bc6e..99dd7ca44 100644
--- a/mcp-host/src/__tests__/workflow/workflowRouter.test.ts
+++ b/mcp-host/src/__tests__/workflow/workflowRouter.test.ts
@@ -92,13 +92,7 @@ async function createTestApp(
app.use('/api/v1/workflow', createWorkflowRouter(service as never))
return new Promise(resolve => {
- // Bind to 127.0.0.1 explicitly, not the wildcard listen(0). macOS's
- // ephemeral allocator can hand a wildcard bind a port a daemon (Docker,
- // VS Code) already holds on 127.0.0.1, and the kernel routes loopback to
- // the more-specific bind — so this test's fetch would reach that foreign
- // process and see its response instead of ours. A specific bind cannot be
- // handed an occupied port, which removes the flake at its source.
- const server = app.listen(0, '127.0.0.1', () => {
+ const server = app.listen(0, () => {
const addr = server.address() as AddressInfo
resolve({ baseUrl: `http://127.0.0.1:${addr.port}`, server })
})
diff --git a/mcp-host/src/contextMapperClient.test.ts b/mcp-host/src/contextMapperClient.test.ts
deleted file mode 100644
index 61c78e97c..000000000
--- a/mcp-host/src/contextMapperClient.test.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { ContextMapperClient } from './contextMapperClient'
-
-describe('ContextMapperClient readiness and discovery', () => {
- afterEach(() => {
- vi.restoreAllMocks()
- vi.unstubAllGlobals()
- })
-
- it('uses the readiness endpoint before treating inventory as authoritative', async () => {
- const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
- vi.stubGlobal('fetch', fetchMock)
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.healthCheck()).resolves.toBe(true)
- expect(fetchMock).toHaveBeenCalledWith(
- 'http://context-mapper.test/ready',
- expect.objectContaining({ signal: expect.any(AbortSignal) })
- )
- })
-
- it('rejects an HTTP 503 during initial discovery instead of returning an empty fleet', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue(
- new Response(
- JSON.stringify({
- error: 'Service Unavailable',
- message: 'Context mapper provider inventory is not authoritative',
- }),
- { status: 503, statusText: 'Service Unavailable' }
- )
- )
- )
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.listServersByContext('production')).rejects.toThrow(
- 'HTTP 503: Service Unavailable'
- )
- })
-
- it('rejects a network failure during initial discovery instead of returning an empty fleet', async () => {
- const networkError = new Error('connection reset')
- vi.stubGlobal('fetch', vi.fn().mockRejectedValue(networkError))
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.listServersByContext('production')).rejects.toBe(networkError)
- })
-
- it('accepts an HTTP 200 empty initial inventory as authoritative', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue(
- new Response(
- JSON.stringify({
- servers: [],
- contextRef: 'production',
- timestamp: '2026-07-29T10:00:00.000Z',
- }),
- { status: 200 }
- )
- )
- )
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.listServersByContext('production')).resolves.toEqual([])
- })
-
- it('does not convert a failed all-server request into an authoritative empty fleet', async () => {
- const networkError = new Error('connection reset')
- vi.stubGlobal('fetch', vi.fn().mockRejectedValue(networkError))
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.listAllServers()).rejects.toBe(networkError)
- })
-
- it('does not convert an unavailable controller into an authoritative empty fleet', async () => {
- // The rejection case above never reaches the `!response.ok` branch, so a
- // 503 from an unready controller was uncovered: swapping that throw for
- // `return []` left the whole suite green while turning "I cannot tell you"
- // into an authoritative "there are none".
- vi.stubGlobal(
- 'fetch',
- vi
- .fn()
- .mockResolvedValue(new Response('', { status: 503, statusText: 'Service Unavailable' }))
- )
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.listAllServers()).rejects.toThrow(/503/)
- })
-})
-
-describe('ContextMapperClient.pollServers', () => {
- afterEach(() => {
- vi.restoreAllMocks()
- vi.unstubAllGlobals()
- })
-
- it('rejects an HTTP 503 instead of fabricating an authoritative empty fleet', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue(
- new Response(
- JSON.stringify({
- error: 'Service Unavailable',
- message: 'Context mapper provider inventory is not authoritative',
- }),
- { status: 503, statusText: 'Service Unavailable' }
- )
- )
- )
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.pollServers('production')).rejects.toThrow('HTTP 503: Service Unavailable')
- })
-
- it('rejects a network failure instead of fabricating an authoritative empty fleet', async () => {
- const networkError = new Error('connection reset')
- vi.stubGlobal('fetch', vi.fn().mockRejectedValue(networkError))
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.pollServers('production')).rejects.toBe(networkError)
- })
-
- it('bounds a silent HCC request so authoritative polling cannot stall indefinitely', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockImplementation((_url: string, init?: RequestInit) => {
- return new Promise((_resolve, reject) => {
- const signal = init?.signal
- if (!signal) return
- signal.addEventListener(
- 'abort',
- () =>
- reject(signal.reason ?? new DOMException('The operation was aborted', 'AbortError')),
- { once: true }
- )
- })
- })
- )
- const client = new ContextMapperClient('http://context-mapper.test', 10)
-
- await expect(client.pollServers('production')).rejects.toMatchObject({ name: 'TimeoutError' })
- })
-
- it('accepts an HTTP 200 empty fleet as an authoritative deletion snapshot', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue(
- new Response(
- JSON.stringify({
- servers: [],
- contextRef: 'production',
- timestamp: '2026-07-29T10:00:00.000Z',
- }),
- { status: 200 }
- )
- )
- )
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.pollServers('production')).resolves.toEqual({
- servers: [],
- timestamp: '2026-07-29T10:00:00.000Z',
- })
- })
-})
-
-describe('ContextMapperClient.getAuthToken', () => {
- afterEach(() => {
- vi.restoreAllMocks()
- vi.unstubAllGlobals()
- })
-
- it('rejects an HTTP failure instead of treating it as an unauthenticated server', async () => {
- vi.stubGlobal(
- 'fetch',
- vi
- .fn()
- .mockResolvedValue(new Response(null, { status: 503, statusText: 'Service Unavailable' }))
- )
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.getAuthToken('secured-server')).rejects.toThrow(
- 'HTTP 503: Service Unavailable'
- )
- })
-
- it('rejects a network failure instead of treating it as an unauthenticated server', async () => {
- const networkError = new Error('connection reset')
- vi.stubGlobal('fetch', vi.fn().mockRejectedValue(networkError))
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.getAuthToken('secured-server')).rejects.toBe(networkError)
- })
-
- it('rejects an authoritative missing token for a server that requested auth', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue(new Response(null, { status: 404, statusText: 'Not Found' }))
- )
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.getAuthToken('secured-server')).rejects.toThrow('HTTP 404: Not Found')
- })
-
- it('retains HTTP 200 token:null as the explicit no-auth response', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue(new Response(JSON.stringify({ token: null }), { status: 200 }))
- )
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.getAuthToken('open-server')).resolves.toBeUndefined()
- })
-})
diff --git a/mcp-host/src/contextMapperClient.ts b/mcp-host/src/contextMapperClient.ts
index 6aeefb5d0..0acfedf7d 100644
--- a/mcp-host/src/contextMapperClient.ts
+++ b/mcp-host/src/contextMapperClient.ts
@@ -4,38 +4,29 @@
* The Context Mapper provides McpServer CRDs via REST API, so mcp-host
* doesn't need direct K8s access to McpServer resources.
*/
-import { config } from './config'
-import { McpServerInfo } from './types'
+
+import { McpServerInfo } from "./types";
+import { config } from "./config";
export interface McpServersResponse {
- servers: McpServerInfo[]
- contextRef: string
- timestamp: string
+ servers: McpServerInfo[];
+ contextRef: string;
+ timestamp: string;
}
export interface AuthTokenResponse {
- token: string | null
- message?: string
+ token: string | null;
+ message?: string;
}
-const DEFAULT_CONTEXT_MAPPER_REQUEST_TIMEOUT_MS = 10_000
-
/**
* Context Mapper client.
*/
export class ContextMapperClient {
- private baseUrl: string
- private requestTimeoutMs: number
-
- constructor(baseUrl: string, requestTimeoutMs = DEFAULT_CONTEXT_MAPPER_REQUEST_TIMEOUT_MS) {
- this.baseUrl = baseUrl.replace(/\/$/, '') // Remove trailing slash
- this.requestTimeoutMs = requestTimeoutMs
- }
+ private baseUrl: string;
- private fetch(input: string): Promise<Response> {
- return fetch(input, {
- signal: AbortSignal.timeout(this.requestTimeoutMs),
- })
+ constructor(baseUrl: string) {
+ this.baseUrl = baseUrl.replace(/\/$/, ""); // Remove trailing slash
}
/**
@@ -43,108 +34,124 @@ export class ContextMapperClient {
*/
async healthCheck(): Promise<boolean> {
try {
- const response = await this.fetch(`${this.baseUrl}/ready`)
- return response.ok
+ const response = await fetch(`${this.baseUrl}/health`);
+ return response.ok;
} catch (error) {
- console.error('[ContextMapper] Health check failed:', error)
- return false
+ console.error("[ContextMapper] Health check failed:", error);
+ return false;
}
}
/**
* List all McpServers.
- * Rejects transport and HTTP failures so a future caller cannot confuse an
- * unavailable controller with an authoritative empty fleet.
*/
async listAllServers(): Promise<McpServerInfo[]> {
- console.log('[ContextMapper] Fetching all McpServers')
+ try {
+ console.log("[ContextMapper] Fetching all McpServers");
- const response = await this.fetch(`${this.baseUrl}/api/v1/mcpservers`)
+ const response = await fetch(`${this.baseUrl}/api/v1/mcpservers`);
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}: ${response.statusText}`)
- }
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ }
- const data = (await response.json()) as McpServersResponse
- console.log(`[ContextMapper] Found ${data.servers.length} McpServer(s)`)
- return data.servers
+ const data = (await response.json()) as McpServersResponse;
+ console.log(`[ContextMapper] Found ${data.servers.length} McpServer(s)`);
+ return data.servers;
+ } catch (error) {
+ console.error("[ContextMapper] Failed to list servers:", error);
+ return [];
+ }
}
/**
* List McpServers by contextRef.
- * Rejects unavailable or invalid responses so callers cannot confuse a
- * failed discovery request with an authoritative empty inventory.
*/
async listServersByContext(contextRef: string): Promise<McpServerInfo[]> {
- console.log(`[ContextMapper] Fetching McpServers for context: ${contextRef}`)
+ try {
+ console.log(`[ContextMapper] Fetching McpServers for context: ${contextRef}`);
- const response = await this.fetch(
- `${this.baseUrl}/api/v1/mcpservers/context/${encodeURIComponent(contextRef)}`
- )
+ const response = await fetch(
+ `${this.baseUrl}/api/v1/mcpservers/context/${encodeURIComponent(contextRef)}`
+ );
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}: ${response.statusText}`)
- }
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ }
- const data = (await response.json()) as McpServersResponse
- console.log(
- `[ContextMapper] Found ${data.servers.length} McpServer(s) for context ${contextRef}`
- )
- console.log(`[ContextMapper] Response:`, JSON.stringify(data, null, 2))
- return data.servers
+ const data = (await response.json()) as McpServersResponse;
+ console.log(`[ContextMapper] Found ${data.servers.length} McpServer(s) for context ${contextRef}`);
+ console.log(`[ContextMapper] Response:`, JSON.stringify(data, null, 2));
+ return data.servers;
+ } catch (error) {
+ console.error("[ContextMapper] Failed to list servers by context:", error);
+ return [];
+ }
}
/**
* Get auth token for an McpServer.
*/
async getAuthToken(serverName: string): Promise<string | undefined> {
- console.log(`[ContextMapper] Fetching auth token for server: ${serverName}`)
+ try {
+ console.log(`[ContextMapper] Fetching auth token for server: ${serverName}`);
- const response = await this.fetch(
- `${this.baseUrl}/api/v1/mcpservers/${encodeURIComponent(serverName)}/auth`
- )
+ const response = await fetch(
+ `${this.baseUrl}/api/v1/mcpservers/${encodeURIComponent(serverName)}/auth`
+ );
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}: ${response.statusText}`)
- }
+ if (!response.ok) {
+ if (response.status === 404) {
+ console.warn(`[ContextMapper] Server or auth not found: ${serverName}`);
+ return undefined;
+ }
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ }
- const data = (await response.json()) as AuthTokenResponse
+ const data = (await response.json()) as AuthTokenResponse;
- if (data.token) {
- console.log(`[ContextMapper] Found auth token for server: ${serverName}`)
- return data.token
- }
+ if (data.token) {
+ console.log(`[ContextMapper] Found auth token for server: ${serverName}`);
+ return data.token;
+ }
- console.log(`[ContextMapper] No auth token for server: ${serverName}`)
- return undefined
+ console.log(`[ContextMapper] No auth token for server: ${serverName}`);
+ return undefined;
+ } catch (error) {
+ console.error("[ContextMapper] Failed to get auth token:", error);
+ return undefined;
+ }
}
/**
* Poll for changes to McpServers.
- * Returns only authoritative snapshots. Transport and HTTP failures reject
- * so callers preserve their last known fleet instead of treating an
- * unavailable controller as an authoritative empty inventory.
+ * Returns the list of servers and a timestamp for comparison.
*/
async pollServers(contextRef: string): Promise<{ servers: McpServerInfo[]; timestamp: string }> {
- const response = await this.fetch(
- `${this.baseUrl}/api/v1/mcpservers/context/${encodeURIComponent(contextRef)}`
- )
+ try {
+ const response = await fetch(
+ `${this.baseUrl}/api/v1/mcpservers/context/${encodeURIComponent(contextRef)}`
+ );
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}: ${response.statusText}`)
- }
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
+ }
- const data = (await response.json()) as McpServersResponse
- return { servers: data.servers, timestamp: data.timestamp }
+ const data = (await response.json()) as McpServersResponse;
+ return { servers: data.servers, timestamp: data.timestamp };
+ } catch (error) {
+ console.error("[ContextMapper] Poll failed:", error);
+ return { servers: [], timestamp: new Date().toISOString() };
+ }
}
}
// Default client instance (configured from environment)
-let defaultClient: ContextMapperClient | null = null
+let defaultClient: ContextMapperClient | null = null;
export function getContextMapperClient(): ContextMapperClient {
if (!defaultClient) {
- defaultClient = new ContextMapperClient(config.contextMapperUrl)
+ defaultClient = new ContextMapperClient(config.contextMapperUrl);
}
- return defaultClient
+ return defaultClient;
}
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index 9ae322c02..6556f52fd 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -65,14 +65,6 @@ 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'
@@ -162,7 +154,6 @@ let failoverEngine: FailoverEngine | null = null
let bootFallbackEntry: FallbackEntry | null = null
let hostWatcher: HostWatcher | null = null
let contextMapperPollTimer: ReturnType<typeof setInterval> | null = null
-let contextMapperPollRunner: { trigger(): void; stop(): void } | null = null
let mcpStatusHeartbeatTimer: ReturnType<typeof setInterval> | null = null
let lastServerState: Map<string, string> = new Map()
let rpcServer: RPCServer | null = null
@@ -182,7 +173,6 @@ 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
@@ -749,91 +739,56 @@ async function initializeProvider(
}
}
-const mcpFleetCoordinator = new AuthoritativeMcpFleetCoordinator(
- DEFAULT_MCP_FLEET_RECONCILE_MAX_CONCURRENCY,
- DEFAULT_MCP_FLEET_RECONCILE_MAX_CONCURRENCY,
- true
-)
-
/**
- * Admit development MCP servers independently.
- *
- * McpManager.addServer propagates connection failures so production fleet
- * reconciliation can leave a failed revision retryable. Development startup
- * has no authoritative polling loop, so one unavailable optional server must
- * not prevent the remaining servers or the host itself from starting.
+ * Initialize MCP servers for the host's context using skill-mapper.
*/
-export async function admitDevelopmentMcpServers(
- servers: McpServerInfo[],
- manager: Pick<McpManager, 'addServer'>
-): Promise<void> {
- for (const server of servers) {
- try {
- await manager.addServer(server)
- } catch (error) {
- console.error(`[Main] Dev MCP server admission failed; continuing: ${server.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,
- createManager: () => new McpManager(config.mcpProxyEnabled ? config.mcpProxyUrl : undefined),
- getAuthToken: async serverName => {
- if (!contextMapperClient) {
- throw new Error('Context Mapper client is required to fetch MCP server auth')
- }
- return contextMapperClient.getAuthToken(serverName)
- },
- installFleet: (nextManager, nextServerState) => {
- mcpManager = nextManager
- lastServerState = nextServerState
- agent?.setMcpManager(nextManager)
- },
- coordinator: mcpFleetCoordinator,
- onColdStartPublished: () => ensureContextMapperPolling(contextRef),
- isPreviousManagerCurrent: () => mcpManager === previousManager,
- isFleetLifecycleCurrent: isInitializationCurrent,
- })
+
+ // Clean up existing manager
+ if (mcpManager) {
+ await mcpManager.disconnectAll()
}
+ mcpManager = new McpManager(config.mcpProxyEnabled ? config.mcpProxyUrl : undefined)
+ lastServerState.clear()
- // In production mode, fetch an authoritative snapshot before replacing the
- // current fleet. An unavailable Context Mapper leaves the prior state intact.
+ // In production mode, fetch from context-mapper
if (!config.devMode) {
if (!contextMapperClient) {
contextMapperClient = getContextMapperClient()
}
- await runAuthoritativeMcpInitialization({
- contextRef,
- client: contextMapperClient,
- replaceFleet,
- isCurrent: isInitializationCurrent,
- })
- } else {
- await replaceFleet([])
- }
+ // Wait for context-mapper to be available
+ const maxRetries = 5
+ let retries = 0
+ while (retries < maxRetries) {
+ const healthy = await contextMapperClient.healthCheck()
+ if (healthy) {
+ console.log('[Main] Context Mapper is available')
+ break
+ }
+ retries++
+ console.log(`[Main] Waiting for Context Mapper... (${retries}/${maxRetries})`)
+ await new Promise(resolve => setTimeout(resolve, 2000))
+ }
+
+ const servers = await contextMapperClient.listServersByContext(contextRef)
+
+ for (const server of servers) {
+ let authToken: string | undefined
- // Successful discovery always installs a manager, including an
- // authoritative HTTP 200 empty snapshot.
- if (!mcpManager) {
- throw new Error('MCP manager was not installed after authoritative discovery')
+ // Get auth token if configured
+ if (server.auth?.secretRef) {
+ authToken = await contextMapperClient.getAuthToken(server.name)
+ }
+
+ await mcpManager.addServer(server, authToken)
+ lastServerState.set(server.name, JSON.stringify(server))
+ }
}
+
const connectedServers = mcpManager.getConnectedServers()
- console.log(
- config.devMode
- ? `[Main] Connected to ${connectedServers.length} MCP server(s)`
- : `[Main] Published the initial MCP fleet manager with ${connectedServers.length} currently connected server(s); background reconciliation may still be in progress`
- )
+ console.log(`[Main] Connected to ${connectedServers.length} MCP server(s)`)
if (connectedServers.length > 0) {
const tools = mcpManager.getAllTools()
@@ -850,115 +805,71 @@ async function initializeMcpServers(contextRef: string): Promise<void> {
* Poll context-mapper for McpServer changes.
*/
async function pollContextMapper(contextRef: string): Promise<void> {
- if (!contextMapperClient) return
+ if (!contextMapperClient || !mcpManager) return
try {
- // Cold-start discovery failures intentionally leave the manager unset.
- // Retry the authoritative initialization instead of declaring an empty
- // fleet or permanently no-oping every reconciliation tick.
- if (!mcpManager) {
- await initializeMcpServers(contextRef)
- return
+ const { servers } = await contextMapperClient.pollServers(contextRef)
+ const currentNames = new Set(servers.map(s => s.name))
+ const previousNames = new Set(lastServerState.keys())
+
+ // Detect added or modified servers
+ for (const server of servers) {
+ const previousState = lastServerState.get(server.name)
+ const currentState = JSON.stringify(server)
+
+ if (!previousState) {
+ console.log(`[Main] MCP server added: ${server.name}`)
+ const authToken = server.auth?.secretRef
+ ? await contextMapperClient.getAuthToken(server.name)
+ : undefined
+ await mcpManager.addServer(server, authToken)
+ lastServerState.set(server.name, currentState)
+ } else if (previousState !== currentState) {
+ console.log(`[Main] MCP server modified: ${server.name}`)
+ await mcpManager.removeServer(server.name)
+ const authToken = server.auth?.secretRef
+ ? await contextMapperClient.getAuthToken(server.name)
+ : undefined
+ await mcpManager.addServer(server, authToken)
+ lastServerState.set(server.name, currentState)
+ }
}
- 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,
- }),
- })
+ // Detect deleted servers
+ for (const name of previousNames) {
+ if (!currentNames.has(name)) {
+ console.log(`[Main] MCP server deleted: ${name}`)
+ await mcpManager.removeServer(name)
+ lastServerState.delete(name)
+ }
+ }
} catch (error) {
console.error('[Main] Error polling skill-mapper:', error)
}
}
-/**
- * Serialize periodic polling while coalescing any number of overlapping ticks
- * into at most one trailing run. This keeps reconciliation bounded without
- * losing the latest post-flight snapshot opportunity.
- */
-export function createCoalescedPollRunner(poll: () => Promise<void>): {
- trigger(): void
- stop(): void
-} {
- let inFlight = false
- let trailing = false
- let stopped = false
-
- const trigger = (): void => {
- if (stopped) return
- if (inFlight) {
- trailing = true
- return
- }
-
- inFlight = true
- void poll()
- .catch(error => {
- console.error('[Main] Context Mapper poll runner failed:', error)
- })
- .finally(() => {
- inFlight = false
- if (trailing && !stopped) {
- trailing = false
- trigger()
- }
- })
- }
-
- return {
- trigger,
- stop: () => {
- stopped = true
- trailing = false
- },
- }
-}
-
/**
* 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()
-
+function startContextMapperPolling(contextRef: string): void {
console.log(
`[Main] Starting context-mapper polling (interval: ${config.contextMapperPollInterval}ms)`
)
- contextMapperPollRunner = createCoalescedPollRunner(() => pollContextMapper(contextRef))
contextMapperPollTimer = setInterval(() => {
- contextMapperPollRunner?.trigger()
+ pollContextMapper(contextRef)
}, config.contextMapperPollInterval)
}
-export function ensureContextMapperPolling(contextRef: string): void {
- if (isShuttingDown || (contextMapperPollTimer && contextMapperPollRunner)) return
- startContextMapperPolling(contextRef)
-}
-
/**
* Stop polling context-mapper.
*/
-export function stopContextMapperPolling(): void {
+function stopContextMapperPolling(): void {
if (contextMapperPollTimer) {
console.log('[Main] Stopping context-mapper polling')
clearInterval(contextMapperPollTimer)
contextMapperPollTimer = null
}
- contextMapperPollRunner?.stop()
- contextMapperPollRunner = null
}
/**
@@ -2509,20 +2420,9 @@ 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()
@@ -2563,8 +2463,7 @@ async function shutdown(signal: string): Promise<void> {
cronScheduler?.stop()
spilloverStorage?.stopGc()
- await mcpClosePromise
- await mcpFleetCoordinator.drainForShutdown()
+ await mcpManager?.disconnectAll()
await pluginWorkloadSdkServer?.stop()
await rpcServer?.stop()
@@ -2641,7 +2540,9 @@ async function startDevMode(): Promise<void> {
if (config.devMcpServers && config.devMcpServers.length > 0) {
console.log(`[Main] Adding ${config.devMcpServers.length} dev MCP server(s)`)
- await admitDevelopmentMcpServers(config.devMcpServers, mcpManager)
+ for (const server of config.devMcpServers) {
+ await mcpManager.addServer(server)
+ }
const tools = mcpManager.getAllTools()
console.log(`[Main] Total tools available: ${tools.length}`)
@@ -2722,7 +2623,7 @@ async function startProductionMode(): Promise<void> {
// reconciles the catalog (the platform tolerates the 'connecting' sweep).
startMcpInitializationInBackground({
initialize: () => initializeMcpServers(host.spec.contextRef),
- afterInitialAttempt: () => ensureContextMapperPolling(host.spec.contextRef),
+ afterInitialAttempt: () => startContextMapperPolling(host.spec.contextRef),
})
console.log(`[Main] Approval system: ${config.enableApproval ? 'ENABLED' : 'DISABLED'}`)
@@ -2937,15 +2838,11 @@ async function main(): Promise<void> {
}
}
-// Run main only when this module is the executable entry point. Keeping imports
-// side-effect free allows the authoritative initialization contract to be
-// regression-tested without starting the service.
-if (require.main === module) {
- main().catch(error => {
- console.error('[Main] Fatal error:', error)
- process.exit(1)
- })
-}
+// Run main
+main().catch(error => {
+ console.error('[Main] Fatal error:', error)
+ process.exit(1)
+})
// Export for external access
export { messageQueue, agent, cronScheduler }
diff --git a/mcp-host/src/mcp/__tests__/managerStatus.test.ts b/mcp-host/src/mcp/__tests__/managerStatus.test.ts
index b4e2a4386..6e2178c0f 100644
--- a/mcp-host/src/mcp/__tests__/managerStatus.test.ts
+++ b/mcp-host/src/mcp/__tests__/managerStatus.test.ts
@@ -4,7 +4,7 @@
* Verifies that the manager emits the right tracker events on the full
* lifecycle (disabled, not-ready, connecting, connected, failed, refresh).
*/
-import { afterEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { McpServerInfo } from '../../types'
import { McpManager } from '../manager'
import { MCP_INIT_AUTH_FAILED_MESSAGE, MCP_NOT_READY_MESSAGE } from '../serverStatus'
@@ -20,20 +20,6 @@ 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()
@@ -60,55 +46,18 @@ describe('McpManager status tracking — disabled / not-ready paths', () => {
const s = m.status.get('svc')!
expect(s.message).toBe(MCP_NOT_READY_MESSAGE)
})
+})
- it('does not connect when readiness is explicitly non-authoritative', async () => {
- const { McpClient } = await import('../client')
- const connect = vi.spyOn(McpClient.prototype, 'connect')
- const m = new McpManager()
-
- await m.addServer(
- serverInfo({
- status: {
- deployed: true,
- ready: true,
- authoritative: false,
- message: 'Deployment status unknown',
- },
- })
- )
+describe('McpManager status tracking — connect success/failure', () => {
+ const originalConnect = vi.hoisted(() => vi.fn())
+ let unmockConnect: (() => void) | null = null
- expect(connect).not.toHaveBeenCalled()
- expect(m.status.get('svc')).toMatchObject({
- state: 'failed',
- reason: 'not_ready',
- message: 'Deployment status unknown',
- })
+ beforeEach(() => {
+ unmockConnect = null
})
- it.each([
- ['disabled', serverInfo({ enabled: false })],
- ['not-ready', serverInfo({ status: { deployed: true, ready: false } })],
- ])(
- 'removeServer cleans %s inventory and status even without a client',
- async (_label, server) => {
- const m = new McpManager()
- await m.addServer(server)
- 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([])
- }
- )
-})
-
-describe('McpManager status tracking — connect success/failure', () => {
afterEach(() => {
+ if (unmockConnect) unmockConnect()
vi.restoreAllMocks()
})
@@ -142,356 +91,11 @@ describe('McpManager status tracking — connect success/failure', () => {
})
const m = new McpManager()
- await expect(m.addServer(serverInfo())).rejects.toMatchObject({
- message: 'Unauthorized',
- code: 401,
- })
+ await m.addServer(serverInfo())
const s = m.status.get('svc')!
expect(s.state).toBe('failed')
expect(s.reason).toBe('auth_failed')
expect(s.message).toBe(MCP_INIT_AUTH_FAILED_MESSAGE)
- expect(m.getConnectedServers()).toEqual([])
- })
-
- it('replaceServer keeps the previous connected revision when the candidate fails', async () => {
- const { McpClient } = await import('../client')
- const connect = vi
- .spyOn(McpClient.prototype, 'connect')
- .mockImplementationOnce(async function (this: any) {
- this.connected = true
- this.tools = [{ name: 'old-tool', inputSchema: {}, serverName: 'svc' }]
- })
- .mockRejectedValueOnce(new Error('replacement connect failed'))
- vi.spyOn(McpClient.prototype, 'retire').mockReturnValue(async () => undefined)
- const previous = serverInfo()
- const replacement = serverInfo({
- transport: { type: 'streamableHttp', url: 'http://replacement/mcp' },
- })
- const m = new McpManager()
- await m.addServer(previous)
-
- await expect(m.replaceServer(replacement)).rejects.toThrow('replacement connect failed')
-
- expect(connect).toHaveBeenCalledTimes(2)
- expect(m.getConnectedServers()).toEqual(['svc'])
- expect(m.status.get('svc')).toMatchObject({ state: 'connected', toolCount: 1 })
- expect((m as any).serverInfos.get('svc')).toEqual(previous)
- expect(m.getAllTools().map(tool => tool.name)).toEqual(['svc__old-tool'])
- })
-
- it('replaceServer connects the candidate before retiring the previous client', async () => {
- const effects: string[] = []
- 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) {
- effects.push('connect-candidate')
- this.connected = true
- this.tools = [{ name: 'new-tool', inputSchema: {}, serverName: 'svc' }]
- })
- vi.spyOn(McpClient.prototype, 'retire').mockImplementation(() => async () => {
- effects.push('disconnect-previous')
- })
- const previous = serverInfo()
- const replacement = serverInfo({
- transport: { type: 'streamableHttp', url: 'http://replacement/mcp' },
- })
- const m = new McpManager()
- await m.addServer(previous)
-
- await m.replaceServer(replacement)
-
- expect(effects).toEqual(['connect-candidate', 'disconnect-previous'])
- 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
})
})
@@ -527,7 +131,6 @@ describe('McpManager.refreshAllServerStatus', () => {
vi.spyOn(McpClient.prototype, 'probeTools').mockResolvedValue({
ok: false,
error: { code: 500 },
- stale: false,
})
const m = new McpManager()
@@ -540,74 +143,11 @@ 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', () => {
@@ -619,7 +159,7 @@ describe('McpManager.disconnectAll resets the tracker', () => {
this.connected = true
this.tools = []
})
- vi.spyOn(McpClient.prototype, 'retire').mockReturnValue(async () => undefined)
+ vi.spyOn(McpClient.prototype, 'disconnect').mockResolvedValue(undefined)
const m = new McpManager()
await m.addServer(serverInfo({ name: 'a' }))
@@ -629,64 +169,4 @@ describe('McpManager.disconnectAll resets the tracker', () => {
await m.disconnectAll()
expect(m.status.size()).toBe(0)
})
-
- it('cleans every client when one disconnect fails, then reports the cleanup error', async () => {
- const { McpClient } = await import('../client')
- vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async function (this: any) {
- this.connected = true
- this.tools = []
- })
- const cleanupError = new Error('first disconnect failed')
- 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' }))
- await m.addServer(serverInfo({ name: 'b' }))
-
- await expect(m.disconnectAll()).rejects.toBe(cleanupError)
-
- 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
deleted file mode 100644
index 523fc60d5..000000000
--- a/mcp-host/src/mcp/authoritativeFleet.ts
+++ /dev/null
@@ -1,880 +0,0 @@
-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.
- const reconciliation = runMcpFleetEffects(options.servers, maxConcurrency, server =>
- coordinator.runAdmission(nextManager, server.name, lease, isCurrent =>
- admitServer(server, () => isCurrent() && options.isFleetLifecycleCurrent?.() !== false)
- )
- )
- if (coldStart && coordinator.reconcilesInBackground) {
- void reconciliation.catch(error => {
- console.error('[Main] MCP background cold-start reconciliation failed:', error)
- })
- return
- }
- await reconciliation
-
- // 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) {
- // Explicit authoritative ready=false and legacy ready=false both revoke.
- // Only the negotiated authoritative=false state preserves a live
- // connection; field absence must retain the legacy fail-closed contract.
- 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 febe8b8e4..278f8a122 100644
--- a/mcp-host/src/mcp/client.ts
+++ b/mcp-host/src/mcp/client.ts
@@ -5,6 +5,7 @@
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
@@ -12,8 +13,6 @@ 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
@@ -25,18 +24,6 @@ interface McpSdkRequestOptions {
signal?: AbortSignal
}
-interface McpCallRecovery {
- sourceEpoch: number
- sourceClient: Client
- targetEpoch?: number
- targetClient?: Client
- promise: Promise<void>
-}
-
-type McpProbeResult =
- | { ok: true; toolCount: number }
- | { ok: false; error: unknown; stale: boolean }
-
function readPositiveSafeIntegerEnv(name: string, defaultValue: number): number {
const raw = process.env[name]
if (raw === undefined || raw === '') return defaultValue
@@ -76,11 +63,12 @@ function resolveMcpRequestTimeoutMs(callerTimeoutMs?: number): number {
function ensureNotAborted(signal: AbortSignal | undefined): void {
if (!signal?.aborted) return
- throw abortError(signal, 'aborted')
+ const reason =
+ typeof signal.reason === 'string' && signal.reason.trim() ? signal.reason : 'aborted'
+ throw new Error(reason)
}
function abortError(signal: AbortSignal | undefined, fallback: string): Error {
- if (signal?.reason instanceof Error) return signal.reason
const reason =
typeof signal?.reason === 'string' && signal.reason.trim() ? signal.reason : fallback
return new Error(reason)
@@ -140,18 +128,13 @@ function requestOptions(
export class McpClient {
private client: Client | null = null
- private transport: SupportedMcpTransport | null = null
+ private transport: Transport | 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 reconnectCallRecovery: McpCallRecovery | null = null
- private connectionEpoch = 0
- private retired = false
- private readonly retirementController = new AbortController()
- private readonly transportCleanups = new WeakMap<SupportedMcpTransport, Promise<void>>()
constructor(serverConfig: McpServerInfo, authToken?: string, proxyUrl?: string) {
this.serverConfig = serverConfig
@@ -171,70 +154,6 @@ 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.
*/
@@ -248,7 +167,7 @@ export class McpClient {
return transport.url || `http://${this.serverConfig.name}.mcp-server.svc.cluster.local:3000/mcp`
}
- private createTransport(): SupportedMcpTransport {
+ private createTransport(): Transport {
const { transport } = this.serverConfig
const headers: Record<string, string> = {}
@@ -284,55 +203,39 @@ 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(
- nextClient.connect(nextTransport),
+ this.client.connect(this.transport),
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)
- 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')
+ this.connected = false
+ await this.disconnect().catch(() => undefined)
throw error
}
}
@@ -341,30 +244,27 @@ export class McpClient {
* Disconnect from the MCP server.
*/
async disconnect(): Promise<void> {
- // 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()
+ 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 = []
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
- this.retirementController.abort(this.lifecycleError('closed'))
- return this.detachConnection()
- }
-
/**
* Refresh the list of available tools from the server.
*/
@@ -374,31 +274,27 @@ 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 {
- response = await refreshClient.listTools(undefined, sdkRequestOptions)
+ 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)'}`
+ )
+ }
} 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)'}`)
- }
}
/**
@@ -419,33 +315,21 @@ export class McpClient {
* transient probe error during a heartbeat doesn't clobber the last known
* tool list.
*/
- async probeTools(options: McpToolCallOptions = {}): Promise<McpProbeResult> {
+ async probeTools(
+ options: McpToolCallOptions = {}
+ ): Promise<{ ok: true; toolCount: number } | { ok: false; error: unknown }> {
if (!this.client || !this.connected) {
- return {
- ok: false,
- error: new Error(`${this.name} is not connected`),
- stale: false,
- }
+ return { ok: false, error: new Error(`${this.name} is not connected`) }
}
- const probeClient = this.client
- const probeEpoch = this.connectionEpoch
try {
- const response = await probeClient.listTools(
+ const response = await this.client.listTools(
undefined,
requestOptions(options.timeoutMs, options.signal)
)
- this.ensureCallCurrent(probeEpoch, probeClient)
const toolCount = (response.tools || []).length
return { ok: true, toolCount }
} catch (error) {
- if (!this.isCallCurrent(probeEpoch, probeClient)) {
- return {
- ok: false,
- error: this.lifecycleError(this.retired ? 'closed' : 'superseded'),
- stale: true,
- }
- }
- return { ok: false, error, stale: false }
+ return { ok: false, error }
}
}
@@ -475,21 +359,12 @@ 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
}
- // A caller-independent reconnect supersedes any completed session
- // recovery. Calls from that older source must not adopt this connection.
- this.reconnectCallRecovery = null
- await this.startReconnect(options)
- }
-
- private async startReconnect(options: McpToolCallOptions): Promise<void> {
this.reconnectPromise = (async () => {
console.log(`[MCP:${this.name}] Reconnecting...`)
await this.disconnect()
- this.ensureNotRetired()
await this.connect(options)
})()
try {
@@ -499,92 +374,6 @@ export class McpClient {
}
}
- /**
- * Join a session recovery only when it was started by another call from the
- * exact same connection. An unrelated reconnect or replacement must keep
- * stale calls fenced off. The completed source-to-target marker also lets a
- * slower peer adopt a recovery that finished before its retry delay elapsed.
- * Each joining caller retains its own budget and abort signal.
- */
- private async reconnectForCall(
- callEpoch: number,
- callClient: Client,
- options: McpToolCallOptions
- ): Promise<void> {
- this.ensureNotRetired()
- const existingRecovery = this.reconnectCallRecovery
- if (
- existingRecovery?.sourceEpoch === callEpoch &&
- existingRecovery.sourceClient === callClient
- ) {
- await this.waitForCallRecovery(existingRecovery, options)
- return
- }
-
- if (this.reconnectPromise) {
- throw this.lifecycleError('superseded')
- }
-
- this.ensureCallCurrent(callEpoch, callClient)
- const recovery: McpCallRecovery = {
- sourceEpoch: callEpoch,
- sourceClient: callClient,
- promise: Promise.resolve(),
- }
- recovery.promise = (async () => {
- try {
- // Recovery belongs to the connection lifecycle, not to whichever
- // affected call happens to win the race. Callers independently bound
- // their wait below without cancelling recovery for healthier peers.
- await this.startReconnect({})
- const targetClient = this.client
- const targetEpoch = this.connectionEpoch
- if (!targetClient) throw this.lifecycleError('superseded')
- this.ensureCallCurrent(targetEpoch, targetClient)
- if (this.reconnectCallRecovery !== recovery) {
- throw this.lifecycleError(this.retired ? 'closed' : 'superseded')
- }
- recovery.targetEpoch = targetEpoch
- recovery.targetClient = targetClient
- } catch (error) {
- if (this.reconnectCallRecovery === recovery) {
- this.reconnectCallRecovery = null
- }
- throw error
- }
- })()
- this.reconnectCallRecovery = recovery
- await this.waitForCallRecovery(recovery, options)
- }
-
- private async waitForCallRecovery(
- recovery: McpCallRecovery,
- options: McpToolCallOptions
- ): Promise<void> {
- const signal = options.signal
- ? AbortSignal.any([options.signal, this.retirementController.signal])
- : this.retirementController.signal
- await withRequestTimeout(recovery.promise, { ...options, signal }, 'MCP reconnect timeout')
- const { targetEpoch, targetClient } = recovery
- if (
- targetEpoch === undefined ||
- !targetClient ||
- !this.isCallCurrent(targetEpoch, targetClient)
- ) {
- throw this.lifecycleError(this.retired ? 'closed' : 'superseded')
- }
- }
-
- private canAdoptCallRecovery(callEpoch: number, callClient: Client): boolean {
- const recovery = this.reconnectCallRecovery
- if (recovery?.sourceEpoch !== callEpoch || recovery.sourceClient !== callClient) {
- return false
- }
- if (recovery.targetEpoch === undefined && !recovery.targetClient) return true
- if (recovery.targetEpoch === undefined || !recovery.targetClient) return false
- return this.isCallCurrent(recovery.targetEpoch, recovery.targetClient)
- }
-
/**
* Call a tool on the MCP server.
* On session errors (e.g. server pod restarted), reconnects and retries once.
@@ -597,9 +386,6 @@ 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))
@@ -612,7 +398,7 @@ export class McpClient {
try {
ensureNotAborted(options.signal)
- const result = await callClient.callTool(
+ const result = await this.client.callTool(
{
name: toolName,
arguments: args,
@@ -620,35 +406,22 @@ 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) {
- const sessionError = this.isSessionError(error)
- if (this.retired) {
- throw this.lifecycleError('closed')
- }
- const callCurrent = this.isCallCurrent(callEpoch, callClient)
- if (!callCurrent && (!sessionError || !this.canAdoptCallRecovery(callEpoch, callClient))) {
- throw this.lifecycleError('superseded')
- }
- if (sessionError) {
+ 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))
- ensureNotAborted(options.signal)
- await this.reconnectForCall(callEpoch, callClient, {
+ await this.reconnect({
timeoutMs: remainingBudgetMs(deadlineMs),
signal: options.signal,
})
ensureNotAborted(options.signal)
- const retryClient = this.client
- if (!retryClient || !this.connected) throw this.lifecycleError('superseded')
- const retryEpoch = this.connectionEpoch
- const result = await retryClient.callTool(
+ const result = await this.client!.callTool(
{
name: toolName,
arguments: args,
@@ -656,7 +429,6 @@ 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 ab295411d..b498bdf1e 100644
--- a/mcp-host/src/mcp/manager.ts
+++ b/mcp-host/src/mcp/manager.ts
@@ -5,32 +5,10 @@ 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
@@ -50,105 +28,15 @@ export class McpManager {
return this.statusTracker
}
- private clearToolMappings(serverName: string): void {
- for (const [toolName, server] of this.toolToServerMap.entries()) {
- if (server === serverName) {
- this.toolToServerMap.delete(toolName)
- }
- }
- }
-
- private installConnectedClient(serverConfig: McpServerInfo, client: McpClient): void {
- this.clearToolMappings(serverConfig.name)
- this.clients.set(serverConfig.name, client)
- this.serverInfos.set(serverConfig.name, serverConfig)
-
- for (const tool of client.availableTools) {
- const fullToolName = `${serverConfig.name}__${tool.name}`
- this.toolToServerMap.set(fullToolName, serverConfig.name)
- }
-
- 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)
- }
-
/**
* Add and connect to an MCP server.
*/
- 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'
-
+ async addServer(serverConfig: McpServerInfo, authToken?: string): Promise<void> {
// 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)
- control.onCommit?.()
- return 'applied'
- }
-
- // Explicitly non-authoritative readiness is a fail-closed admission
- // signal, not permission to open a new connection.
- if (serverConfig.status?.authoritative === false) {
- console.log(
- `[McpManager] Skipping server with non-authoritative readiness: ${serverConfig.name}`
- )
- this.serverInfos.set(serverConfig.name, serverConfig)
- this.statusTracker.markNotReady(serverConfig.name, serverConfig.status?.message)
- control.onCommit?.()
- return 'applied'
+ return
}
// Skip servers that aren't ready yet — transient infra, surfaced as not_ready.
@@ -156,143 +44,61 @@ export class McpManager {
console.log(
`[McpManager] Skipping server not ready: ${serverConfig.name} (${serverConfig.status?.message || 'unknown'})`
)
- this.serverInfos.set(serverConfig.name, serverConfig)
this.statusTracker.markNotReady(serverConfig.name, serverConfig.status?.message)
- control.onCommit?.()
- return 'applied'
+ return
}
// Check if already connected
if (this.clients.has(serverConfig.name)) {
- 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)
+ console.log(`[McpManager] Server already connected: ${serverConfig.name}`)
+ return
}
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.clients.set(serverConfig.name, client)
+ this.serverInfos.set(serverConfig.name, serverConfig)
+
+ // Register tools from this server
+ for (const tool of client.availableTools) {
+ const fullToolName = `${serverConfig.name}__${tool.name}`
+ this.toolToServerMap.set(fullToolName, serverConfig.name)
}
- this.pendingAdmissions.delete(serverConfig.name)
- this.installConnectedClient(serverConfig, client)
- control.onCommit?.()
+
+ // tools/list has succeeded at least once → state becomes connected (spec §4.4).
+ this.statusTracker.markConnected(serverConfig.name, client.availableTools.length)
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
- // revision retryable while continuing to publish healthy peers.
- throw error
+ this.statusTracker.markFailed(serverConfig.name, error)
+ // Don't throw - allow other servers to connect
}
}
/**
- * Connect a ready desired revision before committing it over the current
- * connection. A candidate failure leaves the previous client, tools,
- * serverInfo, and connected status untouched.
+ * Remove and disconnect from an MCP server.
*/
- 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) {
- return this.addServer(serverConfig, authToken, control)
+ async removeServer(serverName: string): Promise<void> {
+ const client = this.clients.get(serverName)
+ if (!client) {
+ return
}
- 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 this.scheduleClientCleanup(candidate, control)
- if (!isCurrent() || this.pendingAdmissions.get(serverConfig.name)?.attempt !== attempt) {
- this.discardPendingAdmission(serverConfig.name, attempt)
- return 'stale'
+ // Remove tool mappings
+ for (const [toolName, server] of this.toolToServerMap.entries()) {
+ if (server === serverName) {
+ this.toolToServerMap.delete(toolName)
}
- 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?.()
-
- await this.scheduleClientCleanup(previousClient, control)
- console.log(`[McpManager] Replaced server: ${serverConfig.name}`)
- return 'applied'
- }
-
- /**
- * 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.
- */
- 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)
+ await client.disconnect()
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}`)
- }
- }
-
- /**
- * Remove and disconnect from an MCP server.
- */
- async removeServer(serverName: string): Promise<void> {
- await this.detachServer(serverName)()
+ console.log(`[McpManager] Removed server: ${serverName}`)
}
/**
@@ -300,51 +106,13 @@ export class McpManager {
* the one path that allows `connecting` to reappear afterwards.
*/
async disconnectAll(): Promise<void> {
- 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
+ const serverNames = [...this.clients.keys()]
+ for (const name of serverNames) {
+ await this.removeServer(name)
}
- 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 cleanup of cleanups) {
- try {
- await cleanup()
- } catch (error) {
- if (!cleanupFailed) firstError = error
- cleanupFailed = true
- }
- }
- if (cleanupFailed) {
- throw firstError
- }
}
/**
@@ -458,8 +226,6 @@ 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 {
@@ -477,22 +243,6 @@ 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.
*/
diff --git a/mcp-host/src/types.ts b/mcp-host/src/types.ts
index b4642196e..974feff20 100644
--- a/mcp-host/src/types.ts
+++ b/mcp-host/src/types.ts
@@ -150,12 +150,6 @@ export interface McpServerStatus {
deployed: boolean
/** Whether the Deployment has at least one ready replica. */
ready: boolean
- /**
- * Whether ready/deployed came from a current-identity, current-generation
- * source. Explicit false means admission status is unknown and must not
- * revoke a live connection. Undefined preserves legacy producer semantics.
- */
- authoritative?: boolean
/** Human-readable status message. */
message?: string
}
diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.json
index fae2c8dd2..69bb9f161 100644
--- a/rpc-proxy/package-lock.json
+++ b/rpc-proxy/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.51",
+ "version": "0.1.50",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-rpc-proxy",
- "version": "0.1.51",
+ "version": "0.1.50",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/rpc-proxy/package.json b/rpc-proxy/package.json
index 93641a581..8d54ca64b 100644
--- a/rpc-proxy/package.json
+++ b/rpc-proxy/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.51",
+ "version": "0.1.50",
"description": "External-facing RPC proxy for tenant-scoped MCP access",
"main": "dist/main.js",
"engines": {
diff --git a/rpc-proxy/src/config.hccBaseUrl.test.ts b/rpc-proxy/src/config.hccBaseUrl.test.ts
deleted file mode 100644
index b1cedb606..000000000
--- a/rpc-proxy/src/config.hccBaseUrl.test.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { readFileSync } from 'node:fs'
-import path from 'node:path'
-
-/**
- * The dev default for RPC_PROXY_HCC_BASE_URL must name the same HCC endpoint the
- * deployed configmap injects. They drifted once: the default pointed at
- * host-context-controller.mcp-server (a Service that exists in no overlay, and
- * one the rpc-proxy egress NetworkPolicy would block anyway — it only permits
- * the api-gateway peer), while the real target is
- * host-context-controller-api-gateway.control-plane. NODE_ENV=production is
- * baked into the image so the default is unreachable in-cluster today, but a
- * developer running rpc-proxy locally would inherit the wrong endpoint. Pin the
- * two together so they cannot silently diverge again.
- */
-describe('rpc-proxy HCC base URL default', () => {
- const repoRoot = path.join(__dirname, '../..')
-
- const configSource = readFileSync(path.join(__dirname, 'config.ts'), 'utf8')
- const defaultMatch = configSource.match(
- /requiredOrDevDefault\(\s*'RPC_PROXY_HCC_BASE_URL',\s*(?:\/\/[^\n]*\n\s*)*'([^']+)'/
- )
-
- const configmap = readFileSync(
- path.join(repoRoot, 'deploy/overlays/minikube/configmaps/rpc-proxy-config.yaml'),
- 'utf8'
- )
- const configmapMatch = configmap.match(/RPC_PROXY_HCC_BASE_URL:\s*"?([^"\n]+)"?/)
-
- it('parses both sources', () => {
- expect(defaultMatch?.[1]).toBeTruthy()
- expect(configmapMatch?.[1]).toBeTruthy()
- })
-
- it('dev default matches the deployed configmap endpoint', () => {
- expect(defaultMatch?.[1]).toBe(configmapMatch?.[1]?.trim())
- })
-
- it('targets the api-gateway in control-plane, not a nonexistent Service', () => {
- expect(defaultMatch?.[1]).toContain('host-context-controller-api-gateway.control-plane')
- })
-})
diff --git a/rpc-proxy/src/config.ts b/rpc-proxy/src/config.ts
index 21ac2c62d..51daa721a 100644
--- a/rpc-proxy/src/config.ts
+++ b/rpc-proxy/src/config.ts
@@ -216,12 +216,7 @@ export const config: Config = {
),
hccBaseUrl: requiredOrDevDefault(
'RPC_PROXY_HCC_BASE_URL',
- // Must mirror the real topology: rpc-proxy reaches HCC only through the
- // nginx api-gateway in control-plane. The egress NetworkPolicy in
- // deploy/base/rpc-proxy/networkpolicies.yaml only allows that peer, and no
- // host-context-controller Service exists in mcp-server. Kept in sync with
- // the deployed configmap by config.hccBaseUrl.test.ts.
- 'http://host-context-controller-api-gateway.control-plane.svc.cluster.local:8081'
+ 'http://host-context-controller.mcp-server.svc.cluster.local:8081'
),
hostNamespace: requiredOrDevDefault('RPC_PROXY_HOST_NAMESPACE', 'mcp-host'),
desktopCookieName: process.env.RPC_PROXY_DESKTOP_COOKIE_NAME || 'clerum_desktop_session',