Skip to content

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

TypeScript

fix(mcp-host): gate lazy per-user admission on enabled/ready/authoritative (R4-B1)

Diego Zacarias103a8b2ed5e1
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index e0bc66edf..9d35f6cba 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.289",
+ "version": "0.1.290",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.289",
+ "version": "0.1.290",
"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 7c4e7032e..db8625311 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.289",
+ "version": "0.1.290",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/mcp/__tests__/managerLazyAdmissionGates.test.ts b/mcp-host/src/mcp/__tests__/managerLazyAdmissionGates.test.ts
new file mode 100644
index 000000000..52533e566
--- /dev/null
+++ b/mcp-host/src/mcp/__tests__/managerLazyAdmissionGates.test.ts
@@ -0,0 +1,159 @@
+/**
+ * R4-B1 — the lazy per-user OAuth admission path must replicate the eager
+ * addServer fail-closed gates (enabled → authoritative → ready, manager.ts
+ * :276-305). serverInfos retains disabled / not-ready / non-authoritative
+ * servers (each eager skip branch does serverInfos.set before returning), so a
+ * callTool with a valid userId used to reach ensureClient → connectAndInstall
+ * and execute the tool against a server the operator had disabled or that was
+ * not ready — opening a real connection with the caller's OAuth token.
+ *
+ * Each case pins the observable result (T4): isError with a cause-precise
+ * message that is NOT the "Authentication required" auth path, AND that no
+ * connection was opened — no per-user provider built, no new transport, and the
+ * server never becomes a connected/live partition.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { McpServerInfo } from '../../types'
+import type { McpTokenProvider } from '../client'
+import { McpManager, type McpPrincipal, type McpTokenProviderFactory } from '../manager'
+
+// ─── SDK mocks (constructable; capture per-transport headers) ────────────────
+
+interface MockTransport {
+ requestHeaders: Record<string, string>
+ close: ReturnType<typeof vi.fn>
+}
+
+const sdk: {
+ transports: MockTransport[]
+} = { transports: [] }
+
+vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
+ Client: class MockClient {
+ private transport: MockTransport | null = null
+ connect = vi.fn(async (t: MockTransport) => {
+ this.transport = t
+ })
+ close = vi.fn().mockResolvedValue(undefined)
+ listTools = vi.fn(async () => ({
+ tools: [{ name: 'do', description: 'demo tool', inputSchema: { type: 'object' } }],
+ }))
+ callTool = vi.fn(async () => {
+ const headers = this.transport?.requestHeaders ?? {}
+ return { content: [{ type: 'text', text: 'ok' }], authorization: headers['Authorization'] }
+ })
+ },
+}))
+
+vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({
+ StreamableHTTPClientTransport: class MockStreamable {
+ requestHeaders: Record<string, string>
+ close = vi.fn().mockResolvedValue(undefined)
+ constructor(_url: URL, opts?: { requestInit?: { headers?: Record<string, string> } }) {
+ this.requestHeaders = opts?.requestInit?.headers ?? {}
+ sdk.transports.push(this as unknown as MockTransport)
+ }
+ },
+}))
+
+vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({
+ SSEClientTransport: class MockSSE {
+ close = vi.fn().mockResolvedValue(undefined)
+ },
+}))
+
+// ─── Helpers ─────────────────────────────────────────────────────────────────
+
+/** Real productor of the oauth-user McpServerInfo shape, mirroring
+ * managerPartition.test.ts. Overrides let a case make it non-admissible. */
+function oauthUserServer(overrides: Partial<McpServerInfo> = {}): McpServerInfo {
+ return {
+ name: 'gh',
+ contextRef: 'ctx-1',
+ transport: { type: 'streamableHttp', url: 'http://gh/mcp' },
+ authKind: 'oauth-user',
+ enabled: true,
+ status: { deployed: true, ready: true },
+ ...overrides,
+ }
+}
+
+/** Records (server, principal) each provider was built for. A per-user
+ * provider being built proves a connection was attempted for that user. */
+function recordingFactory(): {
+ factory: McpTokenProviderFactory
+ built: Array<{ server: string; principal: string }>
+} {
+ const built: Array<{ server: string; principal: string }> = []
+ const factory: McpTokenProviderFactory = (
+ server: McpServerInfo,
+ principal: McpPrincipal
+ ): McpTokenProvider => {
+ if (principal.kind === 'shared') {
+ built.push({ server: server.name, principal: 'shared' })
+ return { resolve: async () => undefined, refresh: async () => undefined }
+ }
+ built.push({ server: server.name, principal: principal.userId })
+ const token = `token-for-${principal.userId}`
+ return { resolve: async () => token, refresh: async () => token }
+ }
+ return { factory, built }
+}
+
+beforeEach(() => {
+ sdk.transports = []
+})
+
+// ─── The three gates on the lazy per-user path ───────────────────────────────
+
+describe('R4-B1 · lazy per-user admission replicates the eager fail-closed gates', () => {
+ interface Case {
+ name: string
+ overrides: Partial<McpServerInfo>
+ errorMatch: RegExp
+ }
+
+ const cases: Case[] = [
+ {
+ name: 'disabled server (operator intent)',
+ overrides: { enabled: false },
+ errorMatch: /disabled/i,
+ },
+ {
+ name: 'non-authoritative readiness',
+ overrides: { status: { deployed: true, ready: true, authoritative: false } },
+ errorMatch: /not ready/i,
+ },
+ {
+ name: 'not-ready server (transient infra)',
+ overrides: { status: { deployed: true, ready: false } },
+ errorMatch: /not ready/i,
+ },
+ ]
+
+ for (const c of cases) {
+ it(`${c.name}: callTool with a valid userId fails closed without connecting`, async () => {
+ const { factory, built } = recordingFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+
+ // Eager admission: the server is skipped (no connection) but retained in
+ // serverInfos — exactly the state that used to be exploitable.
+ await manager.addServer(oauthUserServer(c.overrides))
+ expect(sdk.transports.length).toBe(0)
+
+ const res = await manager.callTool('gh__do', {}, { userId: 'alice' })
+
+ // (T4) Observable result: error, cause-precise, and NOT the auth path.
+ expect(res.isError).toBe(true)
+ const error = String((res.result as { error: string }).error)
+ expect(error).toMatch(c.errorMatch)
+ expect(error).not.toMatch(/authentication required/i)
+
+ // No connection opened: no per-user provider built, no new transport, and
+ // the server never became a live/connected partition.
+ expect(built.filter(b => b.principal !== 'shared')).toEqual([])
+ expect(sdk.transports.length).toBe(0)
+ expect(manager.getConnectedServers()).toEqual([])
+ })
+ }
+})
diff --git a/mcp-host/src/mcp/manager.ts b/mcp-host/src/mcp/manager.ts
index 478c0fb8c..327a7a894 100644
--- a/mcp-host/src/mcp/manager.ts
+++ b/mcp-host/src/mcp/manager.ts
@@ -784,6 +784,31 @@ export class McpManager {
}
}
key = this.userKey(serverName, userId)
+ // Fail-closed: replicate the eager addServer admission gates
+ // (enabled → authoritative → ready, manager.ts:276-305) before opening a
+ // per-user connection with the caller's OAuth token. serverInfos retains
+ // disabled/not-ready/non-authoritative servers (each skip branch there
+ // does serverInfos.set before returning), so without this gate a lazy
+ // per-user admission would connect and execute against a server the
+ // operator disabled or that is not ready. A non-admissible server is
+ // operator intent (disabled) or transient/unauthoritative infra
+ // (not_ready) — NOT an auth failure, so surface it distinctly from the
+ // "Authentication required" cases above.
+ if (!info?.enabled) {
+ return {
+ toolName: fullToolName,
+ result: { error: `MCP server disabled: ${serverName}` },
+ isError: true,
+ }
+ }
+ if (info.status?.authoritative === false || !info.status?.ready) {
+ const detail = info.status?.message ? ` (${info.status.message})` : ''
+ return {
+ toolName: fullToolName,
+ result: { error: `MCP server not ready: ${serverName}${detail}` },
+ isError: true,
+ }
+ }
try {
await this.ensureClient(serverName, userId)
} catch (error) {