Skip to content

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

TypeScript

fix(mcp-host): isolate server startup admission

Alfredo Lopeza6160473c3c0
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index d1d1b6c6e..744d328c2 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.211",
+ "version": "0.1.212",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.211",
+ "version": "0.1.212",
"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 966d53d88..4662ad56b 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.211",
+ "version": "0.1.212",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/__tests__/main.mcpInitialization.test.ts b/mcp-host/src/__tests__/main.mcpInitialization.test.ts
index c83a4650f..94b3b88f3 100644
--- a/mcp-host/src/__tests__/main.mcpInitialization.test.ts
+++ b/mcp-host/src/__tests__/main.mcpInitialization.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import {
+ admitDevelopmentMcpServers,
createCoalescedPollRunner,
reconcileAuthoritativeMcpSnapshot,
replaceAuthoritativeMcpFleet,
@@ -7,6 +8,7 @@ import {
startContextMapperPolling,
stopContextMapperPolling,
} from '../main'
+import { McpManager } from '../mcp/manager'
import type { McpServerInfo } from '../types'
function readyServer(overrides: Partial<McpServerInfo> = {}): McpServerInfo {
@@ -21,6 +23,28 @@ function readyServer(overrides: Partial<McpServerInfo> = {}): McpServerInfo {
}
}
+describe('admitDevelopmentMcpServers', () => {
+ it('continues admitting peers when one development server is unavailable', async () => {
+ const firstServer = readyServer({ name: 'first-server', auth: { type: 'none' } })
+ const failedServer = readyServer({ name: 'failed-server', auth: { type: 'none' } })
+ const thirdServer = readyServer({ name: 'third-server', auth: { type: 'none' } })
+ const addServer = vi
+ .fn()
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(new Error('MCP connect failed'))
+ .mockResolvedValueOnce(undefined)
+
+ 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[] = []
@@ -348,13 +372,46 @@ describe('replaceAuthoritativeMcpFleet', () => {
})
expect(getAuthToken).not.toHaveBeenCalled()
- expect(candidateManager.addServer).not.toHaveBeenCalled()
+ expect(candidateManager.addServer).toHaveBeenCalledWith(nonAuthoritative, undefined)
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 = {
@@ -570,7 +627,7 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
})
expect(getAuthToken).not.toHaveBeenCalled()
- expect(manager.addServer).not.toHaveBeenCalled()
+ expect(manager.addServer).toHaveBeenCalledWith(nonAuthoritative, undefined)
expect(manager.removeServer).not.toHaveBeenCalled()
expect(serverState.get(nonAuthoritative.name)).toBe(JSON.stringify(nonAuthoritative))
})
@@ -605,10 +662,47 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
expect(manager.removeServer).toHaveBeenCalledWith(previous.name)
expect(getAuthToken).not.toHaveBeenCalled()
- expect(manager.addServer).not.toHaveBeenCalled()
+ expect(manager.addServer).toHaveBeenCalledWith(modified, undefined)
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: vi.fn(),
+ replaceServer: vi.fn(),
+ removeServer: vi.fn(),
+ getConnectedServers: 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' } })
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index 215857ba1..94193f251 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -821,11 +821,6 @@ export async function replaceAuthoritativeMcpFleet<
try {
for (const server of options.servers) {
- if (server.status?.authoritative === false) {
- nextServerState.set(server.name, JSON.stringify(server))
- continue
- }
-
let authToken: string | undefined
try {
authToken = await resolveRequiredMcpAuthToken(server, options.getAuthToken)
@@ -877,6 +872,27 @@ export async function replaceAuthoritativeMcpFleet<
}
}
+/**
+ * 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.
+ */
+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)
+ }
+ }
+}
+
interface AuthoritativeMcpSnapshotManager {
addServer(server: McpServerInfo, authToken?: string): Promise<void>
replaceServer(server: McpServerInfo, authToken?: string): Promise<void>
@@ -885,9 +901,24 @@ interface AuthoritativeMcpSnapshotManager {
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 JSON.stringify(desired)
+ return canonicalJson(desired)
}
/**
@@ -923,11 +954,6 @@ export async function reconcileAuthoritativeMcpSnapshot(options: {
const currentState = JSON.stringify(server)
if (!previousState) {
- if (server.status?.authoritative === false) {
- options.serverState.set(server.name, currentState)
- return
- }
-
const authToken = await resolveAuthToken(server)
await options.manager.addServer(server, authToken)
options.serverState.set(server.name, currentState)
@@ -941,6 +967,9 @@ export async function reconcileAuthoritativeMcpSnapshot(options: {
if (desiredChanged) {
if (server.status?.authoritative === false) {
await options.manager.removeServer(server.name)
+ // Reuse the manager's fail-closed admission path to keep the expected
+ // server visible as not_ready without opening a connection.
+ await options.manager.addServer(server, undefined)
options.serverState.set(server.name, currentState)
return
}
@@ -2840,9 +2869,7 @@ async function startDevMode(): Promise<void> {
if (config.devMcpServers && config.devMcpServers.length > 0) {
console.log(`[Main] Adding ${config.devMcpServers.length} dev MCP server(s)`)
- for (const server of config.devMcpServers) {
- await mcpManager.addServer(server)
- }
+ await admitDevelopmentMcpServers(config.devMcpServers, mcpManager)
const tools = mcpManager.getAllTools()
console.log(`[Main] Total tools available: ${tools.length}`)
diff --git a/mcp-host/src/mcp/__tests__/managerStatus.test.ts b/mcp-host/src/mcp/__tests__/managerStatus.test.ts
index ad8aef646..3ce51b61b 100644
--- a/mcp-host/src/mcp/__tests__/managerStatus.test.ts
+++ b/mcp-host/src/mcp/__tests__/managerStatus.test.ts
@@ -264,4 +264,28 @@ 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 disconnect = vi
+ .spyOn(McpClient.prototype, 'disconnect')
+ .mockImplementation(async function (this: any) {
+ 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(disconnect).toHaveBeenCalledTimes(2)
+ expect(m.getConnectedServers()).toEqual([])
+ expect(m.status.size()).toBe(0)
+ })
})
diff --git a/mcp-host/src/mcp/manager.ts b/mcp-host/src/mcp/manager.ts
index f3ec1ac31..a13a18717 100644
--- a/mcp-host/src/mcp/manager.ts
+++ b/mcp-host/src/mcp/manager.ts
@@ -180,12 +180,22 @@ export class McpManager {
*/
async disconnectAll(): Promise<void> {
const serverNames = [...this.clients.keys()]
+ let firstError: unknown
+ let cleanupFailed = false
for (const name of serverNames) {
- await this.removeServer(name)
+ try {
+ await this.removeServer(name)
+ } catch (error) {
+ if (!cleanupFailed) firstError = error
+ cleanupFailed = true
+ }
}
this.toolToServerMap.clear()
this.serverInfos.clear()
this.statusTracker.reset()
+ if (cleanupFailed) {
+ throw firstError
+ }
}
/**