Skip to content

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

TypeScript

feat(mcp-host): u4+u6 oauth per-user and shared-identity token injection

Diego Zacariaseecf9dc7f643
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 1d99f9891..365674759 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.231",
+ "version": "0.1.232",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.231",
+ "version": "0.1.232",
"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 5af75af7b..92d6ef984 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.231",
+ "version": "0.1.232",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/__tests__/mcp/mcpClient.test.ts b/mcp-host/src/__tests__/mcp/mcpClient.test.ts
index 54a930463..9bdf40ab7 100644
--- a/mcp-host/src/__tests__/mcp/mcpClient.test.ts
+++ b/mcp-host/src/__tests__/mcp/mcpClient.test.ts
@@ -5,7 +5,7 @@
* Uses vi.mock with actual class stubs so `new Transport(...)` works.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { McpClient } from '../../mcp/client'
+import { McpClient, staticTokenProvider } from '../../mcp/client'
import type { McpServerInfo } from '../../types'
// ─── Stub classes (constructable) ─────────────────────────────────────────────
@@ -114,7 +114,7 @@ describe('McpClient — connect', () => {
it('injects Authorization header when authToken is provided', async () => {
const client = new McpClient(
makeServerInfo({ transport: { type: 'streamableHttp', url: 'http://server/mcp' } }),
- 'my-auth-token'
+ staticTokenProvider('my-auth-token')
)
await client.connect()
const opts = lastStreamableArgs[1] as { requestInit?: { headers?: Record<string, string> } }
diff --git a/mcp-host/src/agent/taskExecutor.ts b/mcp-host/src/agent/taskExecutor.ts
index f78308eac..b959eaf83 100644
--- a/mcp-host/src/agent/taskExecutor.ts
+++ b/mcp-host/src/agent/taskExecutor.ts
@@ -1627,7 +1627,13 @@ export class TaskExecutor {
)
await registerDesktopTools(nativeRegistry)
const mcpRegistry = this.deps.mcpManager
- ? new McpToolRegistryAdapter(this.deps.mcpManager)
+ ? // Thread the authenticated caller identity so oauth grantScope='user'
+ // tools dispatch to the caller's per-user partition (fail-closed when
+ // absent). buildToolRegistry runs per turn, so one userId per adapter.
+ new McpToolRegistryAdapter(
+ this.deps.mcpManager,
+ this.task.sourceMessage?.sender ?? undefined
+ )
: nativeRegistry
const compositeRegistry = this.deps.mcpManager
? new CompositeToolRegistry(nativeRegistry, mcpRegistry)
diff --git a/mcp-host/src/core/adapters/toolRegistryAdapter.ts b/mcp-host/src/core/adapters/toolRegistryAdapter.ts
index 55618c99d..597cb675a 100644
--- a/mcp-host/src/core/adapters/toolRegistryAdapter.ts
+++ b/mcp-host/src/core/adapters/toolRegistryAdapter.ts
@@ -78,7 +78,8 @@ class McpToolAdapter implements Tool {
private readonly fullName: string,
private readonly desc: string,
private readonly schema: Record<string, unknown>,
- private readonly mcpManager: McpManager
+ private readonly mcpManager: McpManager,
+ private readonly userId?: string
) {}
name() {
@@ -107,7 +108,9 @@ class McpToolAdapter implements Tool {
async execute(params: Record<string, unknown>): Promise<ToolOutput> {
const startTime = Date.now()
try {
- const result = await this.mcpManager.callTool(this.fullName, params)
+ const result = await this.mcpManager.callTool(this.fullName, params, {
+ userId: this.userId,
+ })
const { textParts, attachments } = extractMcpContent(result.result, this.fullName)
let content: string
@@ -144,7 +147,16 @@ class McpToolAdapter implements Tool {
export class McpToolRegistryAdapter implements ToolRegistry {
private tools = new Map<string, Tool>()
- constructor(private readonly mcpManager: McpManager) {
+ /**
+ * @param userId caller identity (authenticated session `sender`) threaded to
+ * `manager.callTool` so oauth grantScope='user' tools dispatch to the
+ * caller's per-user partition. A fresh adapter is built per turn, so it
+ * always carries exactly one userId.
+ */
+ constructor(
+ private readonly mcpManager: McpManager,
+ private readonly userId?: string
+ ) {
this.refresh()
}
@@ -184,7 +196,8 @@ export class McpToolRegistryAdapter implements ToolRegistry {
mcpTool.name,
mcpTool.description || '',
mcpTool.inputSchema || {},
- this.mcpManager
+ this.mcpManager,
+ this.userId
)
)
}
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index 6804f6be5..995732c68 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -64,7 +64,13 @@ import { PromptCache } from './llm/promptCache'
import { clerumPromptCacheInvalidationsTotal } from './llm/promptCacheMetrics'
import { ALL_PROVIDERS, type LlmProvider, descriptorFor, isLlmProvider } from './llm/registryCore'
import './logger'
-import { McpManager } from './mcp'
+import {
+ McpManager,
+ type McpPrincipal,
+ type McpTokenProvider,
+ type McpTokenProviderFactory,
+ staticTokenProvider,
+} from './mcp'
import {
AuthoritativeMcpFleetCoordinator,
DEFAULT_MCP_FLEET_RECONCILE_MAX_CONCURRENCY,
@@ -73,6 +79,7 @@ import {
replaceAuthoritativeMcpFleet,
runAuthoritativeMcpInitialization,
} from './mcp/authoritativeFleet'
+import { type BrokerTokenProviderDeps, createBrokerTokenProvider } from './mcp/brokerTokenProvider'
import { startMcpInitializationInBackground } from './mcpBackgroundInit'
import { IncomingMessageHandler, PendingTaskEntry } from './messageHandler'
import {
@@ -136,7 +143,10 @@ import { resolvePendingProviderWorkflowApproval } from './workflow/providerWorkf
import { confirmProviderWorkflowApprovalTelegramVerification } from './workflow/providerWorkflowApprovalTelegramVerificationClient'
import { resolveProviderWorkflowCallerContext } from './workflow/providerWorkflowCallerContextClient'
import { wireWorkflowApprovalRuntimeRoutes } from './workflow/runtimeApprovalRouteWiring'
-import { createMcpHostRuntimeAuth } from './workflow/runtimeAuthFactory'
+import {
+ createMcpHostRuntimeAuth,
+ workflowControlTokenFromConfig,
+} from './workflow/runtimeAuthFactory'
import {
startRuntimeAuthProactiveRefresh,
stopRuntimeAuthProactiveRefresh,
@@ -779,6 +789,67 @@ export async function admitDevelopmentMcpServers(
}
}
+/**
+ * Idle timeout (ms) for oauth grantScope='user' partitions. Bounds revocation
+ * latency for a revoked grant (mini-spec §6): an idle per-user connection is
+ * evicted after this window; a live one keeps its short-lived access token.
+ */
+const OAUTH_USER_PARTITION_IDLE_MS = 15 * 60 * 1000
+/** Hard cap on live oauth-user partitions per manager (LRU eviction beyond it). */
+const OAUTH_USER_PARTITION_MAX = 500
+
+/**
+ * Build the per-connection token-provider factory used by the McpManager for
+ * oauth servers. Static servers do NOT use this (the manager builds their static
+ * provider from the eagerly-resolved secretRef token).
+ *
+ * - oauth grantScope='user', principal=userId → broker (server, userId)
+ * - oauth grantScope='user', principal=SHARED → token-less representative
+ * - oauth grantScope='context', principal=SHARED → broker (server, contextRef)
+ *
+ * The broker is reached via the workflow-approval gateway (decision #6/B): a
+ * POST-only L7 allowlisted location, NOT a new direct egress to control-api.
+ */
+function createMcpTokenProviderFactory(): McpTokenProviderFactory {
+ return (server: McpServerInfo, principal: McpPrincipal): McpTokenProvider => {
+ if (server.auth?.type !== 'oauth') {
+ // Defensive: static providers are built by the manager, not here.
+ return staticTokenProvider(undefined)
+ }
+ const grantScope = server.oauth?.grantScope ?? 'user'
+ if (grantScope === 'context') {
+ // U6 (host): shared identity — one broker grant per (server, context).
+ return createBrokerTokenProvider(
+ server,
+ { contextId: server.contextRef },
+ brokerTokenProviderDeps()
+ )
+ }
+ // grantScope === 'user'
+ if (principal.kind === 'user') {
+ return createBrokerTokenProvider(
+ server,
+ { userId: principal.userId },
+ brokerTokenProviderDeps()
+ )
+ }
+ // SHARED principal on a user-scoped oauth server = catalog representative.
+ return staticTokenProvider(undefined)
+ }
+}
+
+/**
+ * Broker deps shared by every per-connection token provider: reads the gateway
+ * URL and mcp-host control JWT from config at call time (so token rotation is
+ * picked up). See mcp/brokerTokenProvider.ts for the fail-closed contract.
+ */
+function brokerTokenProviderDeps(): BrokerTokenProviderDeps {
+ return {
+ gatewayUrl: () => config.mcpHostGatewayUrl,
+ controlToken: () => workflowControlTokenFromConfig(),
+ }
+}
+
async function initializeMcpServers(contextRef: string): Promise<void> {
console.log(`[Main] Initializing MCP servers for context: ${contextRef}`)
const initializationGeneration = ++mcpInitializationGeneration
@@ -790,7 +861,12 @@ async function initializeMcpServers(contextRef: string): Promise<void> {
await replaceAuthoritativeMcpFleet({
servers,
previousManager,
- createManager: () => new McpManager(config.mcpProxyEnabled ? config.mcpProxyUrl : undefined),
+ createManager: () =>
+ new McpManager(
+ config.mcpProxyEnabled ? config.mcpProxyUrl : undefined,
+ undefined,
+ createMcpTokenProviderFactory()
+ ),
getAuthToken: async serverName => {
if (!contextMapperClient) {
throw new Error('Context Mapper client is required to fetch MCP server auth')
@@ -975,6 +1051,19 @@ function startMcpStatusHeartbeat(): void {
console.log(`[Main] Starting MCP status heartbeat (interval: ${interval}ms)`)
mcpStatusHeartbeatTimer = setInterval(() => {
if (!mcpManager) return
+ // Evict idle oauth grantScope='user' partitions (LRU + TTL, mini-spec §6).
+ // SHARED/static/representative partitions are exempt.
+ try {
+ const evicted = mcpManager.evictIdleUserPartitions(
+ OAUTH_USER_PARTITION_IDLE_MS,
+ OAUTH_USER_PARTITION_MAX
+ )
+ if (evicted > 0) {
+ console.log(`[Main] Evicted ${evicted} idle oauth per-user MCP partition(s)`)
+ }
+ } catch (err: unknown) {
+ console.error('[Main] MCP per-user partition eviction failed:', err)
+ }
mcpManager.refreshAllServerStatus().catch((err: unknown) => {
console.error('[Main] MCP status heartbeat failed:', err)
})
@@ -2589,7 +2678,11 @@ async function startDevMode(): Promise<void> {
await initializeProvider(host, keys)
// Initialize MCP manager
- mcpManager = new McpManager(config.mcpProxyEnabled ? config.mcpProxyUrl : undefined)
+ mcpManager = new McpManager(
+ config.mcpProxyEnabled ? config.mcpProxyUrl : undefined,
+ undefined,
+ createMcpTokenProviderFactory()
+ )
if (config.devMcpServers && config.devMcpServers.length > 0) {
console.log(`[Main] Adding ${config.devMcpServers.length} dev MCP server(s)`)
@@ -2871,7 +2964,7 @@ async function main(): Promise<void> {
console.log(`[Main] Starting in WORKFLOW MODE (recipe: ${config.workflowRecipeName})`)
const { WorkflowService } = await import('./workflow/workflowService')
- const { McpClient } = await import('./mcp/client')
+ const { McpClient, staticTokenProvider } = await import('./mcp/client')
rpcServer = new RPCServer(config.serverPort)
@@ -2886,7 +2979,7 @@ async function main(): Promise<void> {
enabled: true,
status: { deployed: true, ready: true },
} as McpServerInfo
- const client = new McpClient(info, server.authToken)
+ const client = new McpClient(info, staticTokenProvider(server.authToken))
return {
connect: (options?: { timeoutMs?: number; signal?: AbortSignal }) =>
client.connect(options),
diff --git a/mcp-host/src/mcp/__tests__/brokerTokenProvider.test.ts b/mcp-host/src/mcp/__tests__/brokerTokenProvider.test.ts
new file mode 100644
index 000000000..ce8c0f162
--- /dev/null
+++ b/mcp-host/src/mcp/__tests__/brokerTokenProvider.test.ts
@@ -0,0 +1,184 @@
+/**
+ * U4 fix-round — broker token provider fail-closed matrix (T1/T5).
+ *
+ * Tests the REAL provider (mcp/brokerTokenProvider.ts) with only `fetch` stubbed
+ * (never a hand-written double of the provider). Pins the fail-closed contract
+ * and the per-user cache isolation (the load-bearing security invariant).
+ */
+import { describe, expect, it, vi } from 'vitest'
+import { type BrokerTokenProviderDeps, createBrokerTokenProvider } from '../brokerTokenProvider'
+
+interface StubResponse {
+ status: number
+ json?: () => Promise<unknown>
+}
+
+function stubFetch(handler: (url: string, init: RequestInit) => StubResponse) {
+ return vi.fn(async (url: string, init: RequestInit) => handler(url, init) as unknown as Response)
+}
+
+function jsonResponse(status: number, body: unknown): StubResponse {
+ return { status, json: async () => body }
+}
+
+function deps(
+ fetchImpl: ReturnType<typeof stubFetch>,
+ overrides: Partial<BrokerTokenProviderDeps> = {}
+): BrokerTokenProviderDeps {
+ return {
+ gatewayUrl: () => 'http://gateway:8092',
+ controlToken: () => 'control-jwt',
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ ...overrides,
+ }
+}
+
+function bodyOf(fetchImpl: ReturnType<typeof stubFetch>, call = 0): Record<string, unknown> {
+ const init = fetchImpl.mock.calls[call][1] as RequestInit
+ return JSON.parse(init.body as string)
+}
+
+describe('createBrokerTokenProvider — fail-closed contract', () => {
+ it('200 → returns the token and POSTs the subject', async () => {
+ const f = stubFetch(() => jsonResponse(200, { token: 'tok-abc', expiresAt: null }))
+ const p = createBrokerTokenProvider({ name: 'gh' }, { userId: 'alice' }, deps(f))
+ expect(await p.resolve()).toBe('tok-abc')
+ expect(f).toHaveBeenCalledTimes(1)
+ expect(bodyOf(f)).toEqual({ mcpServerName: 'gh', userId: 'alice' })
+ })
+
+ it('reuses a cached token within expiry headroom, refetches once expiry is near', async () => {
+ let clock = 1_000_000
+ const f = stubFetch(() =>
+ jsonResponse(200, { token: 'tok', expiresAt: new Date(clock + 60_000).toISOString() })
+ )
+ const p = createBrokerTokenProvider(
+ { name: 'gh' },
+ { userId: 'alice' },
+ deps(f, { now: () => clock })
+ )
+ expect(await p.resolve()).toBe('tok')
+ // Still >30s headroom → cached, no new POST.
+ clock += 20_000
+ expect(await p.resolve()).toBe('tok')
+ expect(f).toHaveBeenCalledTimes(1)
+ // Now <30s headroom → refetch.
+ clock += 15_000
+ expect(await p.resolve()).toBe('tok')
+ expect(f).toHaveBeenCalledTimes(2)
+ })
+
+ it('refresh() forces a fresh POST even when a valid token is cached', async () => {
+ const f = stubFetch(() => jsonResponse(200, { token: 'tok', expiresAt: null }))
+ const p = createBrokerTokenProvider({ name: 'gh' }, { userId: 'alice' }, deps(f))
+ await p.resolve()
+ expect(f).toHaveBeenCalledTimes(1)
+ await p.resolve() // cached (expiresAt null → no expiry)
+ expect(f).toHaveBeenCalledTimes(1)
+ await p.refresh() // forced
+ expect(f).toHaveBeenCalledTimes(2)
+ })
+
+ it('404 no_grant → resolves undefined (fail-closed, call not forwarded)', async () => {
+ const f = stubFetch(() => jsonResponse(404, { error: 'no_grant' }))
+ const p = createBrokerTokenProvider({ name: 'gh' }, { userId: 'alice' }, deps(f))
+ expect(await p.resolve()).toBeUndefined()
+ })
+
+ it('403 insufficient_scope → resolves undefined (fail-closed)', async () => {
+ const f = stubFetch(() => jsonResponse(403, { error: 'insufficient_scope' }))
+ const p = createBrokerTokenProvider({ name: 'gh' }, { userId: 'alice' }, deps(f))
+ expect(await p.resolve()).toBeUndefined()
+ })
+
+ it('500 → throws (never forwards a stale/empty token)', async () => {
+ const f = stubFetch(() => jsonResponse(500, { error: 'boom' }))
+ const p = createBrokerTokenProvider({ name: 'gh' }, { userId: 'alice' }, deps(f))
+ await expect(p.resolve()).rejects.toThrow(/500/)
+ })
+
+ it('malformed 200 body → throws, never returns a token', async () => {
+ const f = stubFetch(() => ({
+ status: 200,
+ json: async () => {
+ throw new SyntaxError('unexpected token')
+ },
+ }))
+ const p = createBrokerTokenProvider({ name: 'gh' }, { userId: 'alice' }, deps(f))
+ await expect(p.resolve()).rejects.toThrow()
+ })
+
+ it('200 with empty/absent token → throws', async () => {
+ const f = stubFetch(() => jsonResponse(200, { token: '', expiresAt: null }))
+ const p = createBrokerTokenProvider({ name: 'gh' }, { userId: 'alice' }, deps(f))
+ await expect(p.resolve()).rejects.toThrow(/malformed/)
+ })
+
+ it('missing gateway URL → undefined, no fetch', async () => {
+ const f = stubFetch(() => jsonResponse(200, { token: 't', expiresAt: null }))
+ const p = createBrokerTokenProvider(
+ { name: 'gh' },
+ { userId: 'alice' },
+ deps(f, { gatewayUrl: () => undefined })
+ )
+ expect(await p.resolve()).toBeUndefined()
+ expect(f).not.toHaveBeenCalled()
+ })
+
+ it('missing control token → undefined, no fetch', async () => {
+ const f = stubFetch(() => jsonResponse(200, { token: 't', expiresAt: null }))
+ const p = createBrokerTokenProvider(
+ { name: 'gh' },
+ { userId: 'alice' },
+ deps(f, { controlToken: () => undefined })
+ )
+ expect(await p.resolve()).toBeUndefined()
+ expect(f).not.toHaveBeenCalled()
+ })
+
+ it('a hung broker aborts on the timeout signal → throws (fail-closed, no token)', async () => {
+ // Never resolves on its own; rejects only when the provider's timeout signal
+ // fires. Exercises the AbortSignal.timeout → throw → caller fail-closed chain.
+ const f = vi.fn(
+ (_url: string, init: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ init.signal?.addEventListener('abort', () =>
+ reject(new DOMException('The operation was aborted', 'AbortError'))
+ )
+ })
+ )
+ const p = createBrokerTokenProvider(
+ { name: 'gh' },
+ { userId: 'alice' },
+ deps(f as unknown as ReturnType<typeof stubFetch>, { timeoutMs: 5 })
+ )
+ // Throw (not a stale/empty token) → the manager surfaces it as an auth
+ // failure and never forwards the call.
+ await expect(p.resolve()).rejects.toThrow(/abort/i)
+ })
+
+ it('grantScope=context subject POSTs contextId', async () => {
+ const f = stubFetch(() => jsonResponse(200, { token: 'ctx-tok', expiresAt: null }))
+ const p = createBrokerTokenProvider({ name: 'gh' }, { contextId: 'ctx-1' }, deps(f))
+ expect(await p.resolve()).toBe('ctx-tok')
+ expect(bodyOf(f)).toEqual({ mcpServerName: 'gh', contextId: 'ctx-1' })
+ })
+})
+
+describe('createBrokerTokenProvider — per-user cache isolation (security)', () => {
+ it('a token cached for user A is never returned for user B', async () => {
+ // One shared stub fetch: echoes the requested subject back as the token.
+ const f = stubFetch((_url, init) => {
+ const body = JSON.parse((init.body as string) ?? '{}') as { userId?: string }
+ return jsonResponse(200, { token: `tok-${body.userId}`, expiresAt: null })
+ })
+ const a = createBrokerTokenProvider({ name: 'gh' }, { userId: 'alice' }, deps(f))
+ const b = createBrokerTokenProvider({ name: 'gh' }, { userId: 'bob' }, deps(f))
+
+ expect(await a.resolve()).toBe('tok-alice')
+ expect(await b.resolve()).toBe('tok-bob')
+ // A's cache still serves only A; it never leaks B's token.
+ expect(await a.resolve()).toBe('tok-alice')
+ expect(await b.resolve()).toBe('tok-bob')
+ })
+})
diff --git a/mcp-host/src/mcp/__tests__/clientAuthRetry.test.ts b/mcp-host/src/mcp/__tests__/clientAuthRetry.test.ts
new file mode 100644
index 000000000..f06c0e071
--- /dev/null
+++ b/mcp-host/src/mcp/__tests__/clientAuthRetry.test.ts
@@ -0,0 +1,125 @@
+/**
+ * U4 seam — 401-in-tool-call recovery (mini-spec 03 §5).
+ *
+ * - 401 → force tokenProvider.refresh(), reconnect through the SAME fencing,
+ * retry exactly once.
+ * - a second 401 → terminal McpAuthError, NO loop (one forced refresh only).
+ * - 403 → terminal immediately, NO refresh, NO reconnect.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { McpServerInfo } from '../../types'
+import { McpAuthError, McpClient, type McpTokenProvider } from '../client'
+
+const state: { callToolQueue: Array<() => Promise<unknown>>; connectCount: number } = {
+ callToolQueue: [],
+ connectCount: 0,
+}
+
+vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
+ Client: class MockClient {
+ connect = vi.fn(async () => {
+ state.connectCount += 1
+ })
+ close = vi.fn().mockResolvedValue(undefined)
+ listTools = vi.fn().mockResolvedValue({ tools: [{ name: 'do', inputSchema: {} }] })
+ callTool = vi.fn(async () => {
+ const next = state.callToolQueue.shift()
+ if (!next) throw new Error('unexpected extra callTool')
+ return next()
+ })
+ },
+}))
+
+vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({
+ StreamableHTTPClientTransport: class {
+ close = vi.fn().mockResolvedValue(undefined)
+ },
+}))
+
+vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({
+ SSEClientTransport: class {
+ close = vi.fn().mockResolvedValue(undefined)
+ },
+}))
+
+function server(): McpServerInfo {
+ return {
+ name: 'gh',
+ contextRef: 'ctx',
+ transport: { type: 'streamableHttp', url: 'http://gh/mcp' },
+ auth: { type: 'oauth' },
+ oauth: { grantScope: 'user' },
+ enabled: true,
+ status: { deployed: true, ready: true },
+ }
+}
+
+function httpError(status: number): () => Promise<never> {
+ return () => {
+ const err = new Error(`http ${status}`) as Error & { code: number }
+ err.code = status
+ return Promise.reject(err)
+ }
+}
+
+function trackingProvider(): { provider: McpTokenProvider; refreshCount: () => number } {
+ let refreshes = 0
+ return {
+ provider: {
+ resolve: async () => 'tok',
+ refresh: async () => {
+ refreshes += 1
+ return 'tok-refreshed'
+ },
+ },
+ refreshCount: () => refreshes,
+ }
+}
+
+beforeEach(() => {
+ state.callToolQueue = []
+ state.connectCount = 0
+})
+
+describe('McpClient — 401 tool-call recovery', () => {
+ it('refreshes the token, reconnects, and retries once on 401', async () => {
+ const { provider, refreshCount } = trackingProvider()
+ const client = new McpClient(server(), provider)
+ await client.connect()
+ const connectsAfterInitial = state.connectCount
+
+ state.callToolQueue = [
+ httpError(401),
+ () => Promise.resolve({ content: [{ type: 'text', text: 'ok' }] }),
+ ]
+ const result = await client.callTool('do', {})
+
+ expect(result).toEqual({ content: [{ type: 'text', text: 'ok' }] })
+ expect(refreshCount()).toBe(1)
+ // Reconnected exactly once through the fencing (a new SDK connect happened).
+ expect(state.connectCount).toBe(connectsAfterInitial + 1)
+ })
+
+ it('a second 401 is terminal (McpAuthError), with no refresh loop', async () => {
+ const { provider, refreshCount } = trackingProvider()
+ const client = new McpClient(server(), provider)
+ await client.connect()
+
+ state.callToolQueue = [httpError(401), httpError(401)]
+ await expect(client.callTool('do', {})).rejects.toBeInstanceOf(McpAuthError)
+ // Only one forced refresh — the second 401 does not trigger another.
+ expect(refreshCount()).toBe(1)
+ })
+
+ it('403 is terminal immediately — no refresh, no reconnect', async () => {
+ const { provider, refreshCount } = trackingProvider()
+ const client = new McpClient(server(), provider)
+ await client.connect()
+ const connectsAfterInitial = state.connectCount
+
+ state.callToolQueue = [httpError(403)]
+ await expect(client.callTool('do', {})).rejects.toBeInstanceOf(McpAuthError)
+ expect(refreshCount()).toBe(0)
+ expect(state.connectCount).toBe(connectsAfterInitial)
+ })
+})
diff --git a/mcp-host/src/mcp/__tests__/managerPartition.test.ts b/mcp-host/src/mcp/__tests__/managerPartition.test.ts
new file mode 100644
index 000000000..4b088c4af
--- /dev/null
+++ b/mcp-host/src/mcp/__tests__/managerPartition.test.ts
@@ -0,0 +1,416 @@
+/**
+ * U4 seam — per-user connection partitioning for oauth mcp-servers.
+ *
+ * Invariants pinned here (mini-spec 03, spec §U4):
+ * - SHARED sentinel never collides with a real userId (T2 property-test).
+ * - Catalog dedup by serverName across N per-user partitions.
+ * - Fail-closed: oauth-user + undefined/'anonymous' userId → no token, no forward.
+ * - Identity isolation: user A's partition/Bearer is never used for user B.
+ * - Revocation purge: detachServer removes every ClientKey of that serverName.
+ * - Reconcile no-change branch preserves live per-user partitions.
+ * - Keyspace property-tests on the re-keyed manager (T2).
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import fc from 'fast-check'
+import type { McpServerInfo } from '../../types'
+import type { McpTokenProvider } from '../client'
+import {
+ McpManager,
+ type McpPrincipal,
+ type McpTokenProviderFactory,
+ SHARED_PRINCIPAL,
+ serializeClientKey,
+ serverNameFromClientKey,
+ userPrincipal,
+} from '../manager'
+
+// ─── SDK mocks (constructable; capture per-transport headers) ────────────────
+
+interface MockTransport {
+ requestHeaders: Record<string, string>
+ close: ReturnType<typeof vi.fn>
+}
+
+const sdk: {
+ transports: MockTransport[]
+ callToolImpl: ((headers: Record<string, string>) => Promise<unknown>) | null
+ connectImpl: (() => Promise<void>) | null
+} = { transports: [], callToolImpl: null, connectImpl: null }
+
+vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
+ Client: class MockClient {
+ private transport: MockTransport | null = null
+ connect = vi.fn(async (t: MockTransport) => {
+ this.transport = t
+ if (sdk.connectImpl) await sdk.connectImpl()
+ })
+ 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 ?? {}
+ if (sdk.callToolImpl) return sdk.callToolImpl(headers)
+ 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 ─────────────────────────────────────────────────────────────────
+
+function oauthUserServer(name = 'gh'): McpServerInfo {
+ return {
+ name,
+ contextRef: 'ctx-1',
+ transport: { type: 'streamableHttp', url: `http://${name}/mcp` },
+ auth: { type: 'oauth' },
+ oauth: { grantScope: 'user' },
+ enabled: true,
+ status: { deployed: true, ready: true },
+ }
+}
+
+/** Records (server, principal) each provider was built for and the tokens it hands out. */
+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 }
+ }
+ const uid = principal.userId
+ built.push({ server: server.name, principal: uid })
+ const token = `token-for-${uid}`
+ return { resolve: async () => token, refresh: async () => token }
+ }
+ return { factory, built }
+}
+
+/** A tool call whose entry and completion can be observed/controlled by the test. */
+function gatedCall(): {
+ entered: Promise<void>
+ enter: () => void
+ gate: Promise<void>
+ release: () => void
+} {
+ let enterResolve!: () => void
+ const entered = new Promise<void>(r => (enterResolve = r))
+ let gateResolve!: () => void
+ const gate = new Promise<void>(r => (gateResolve = r))
+ return { entered, enter: () => enterResolve(), gate, release: () => gateResolve() }
+}
+
+beforeEach(() => {
+ sdk.transports = []
+ sdk.callToolImpl = null
+ sdk.connectImpl = null
+})
+
+// ─── T2 · SHARED sentinel property-test ──────────────────────────────────────
+
+describe('ClientKey — SHARED sentinel never collides with a real userId', () => {
+ it('no userId string serializes to the SHARED key (fuzz)', () => {
+ fc.assert(
+ fc.property(fc.string(), fc.string(), (serverName, userId) => {
+ const sharedKey = serializeClientKey(serverName, SHARED_PRINCIPAL)
+ const userKey = serializeClientKey(serverName, userPrincipal(userId))
+ expect(userKey).not.toBe(sharedKey)
+ })
+ )
+ })
+
+ it('serialization is injective over (serverName, principal) and round-trips serverName', () => {
+ fc.assert(
+ fc.property(fc.string(), fc.string(), fc.string(), (serverName, a, b) => {
+ const ka = serializeClientKey(serverName, userPrincipal(a))
+ const kb = serializeClientKey(serverName, userPrincipal(b))
+ // distinct users → distinct keys; same user → same key
+ expect(ka === kb).toBe(a === b)
+ // serverName round-trips out of either flavor of key
+ expect(serverNameFromClientKey(ka)).toBe(serverName)
+ expect(serverNameFromClientKey(serializeClientKey(serverName, SHARED_PRINCIPAL))).toBe(
+ serverName
+ )
+ })
+ )
+ })
+})
+
+// ─── Catalog dedup ───────────────────────────────────────────────────────────
+
+describe('Catalog dedup by serverName across per-user partitions', () => {
+ it('N per-user partitions of one oauth server yield the tool once', async () => {
+ const { factory } = recordingFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+ await manager.addServer(oauthUserServer())
+
+ // Lazily admit two per-user partitions.
+ await manager.callTool('gh__do', {}, { userId: 'alice' })
+ await manager.callTool('gh__do', {}, { userId: 'bob' })
+
+ expect(manager.getAllTools().map(t => t.name)).toEqual(['gh__do'])
+ expect(manager.getConnectedServers()).toEqual(['gh'])
+ expect(manager.hasConnectedServers()).toBe(true)
+ // describeCapabilities counts by serverName, not by live connection.
+ expect(manager.describeCapabilities()).toContain('access to 1 MCP server(s)')
+ })
+})
+
+// ─── Fail-closed ─────────────────────────────────────────────────────────────
+
+describe('Fail-closed: oauth-user with no/anonymous userId', () => {
+ it('undefined userId never resolves a token nor forwards the call', async () => {
+ const { factory, built } = recordingFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+ await manager.addServer(oauthUserServer())
+ const transportsAfterRepresentative = sdk.transports.length
+
+ const res = await manager.callTool('gh__do', {}, {})
+ expect(res.isError).toBe(true)
+ expect(String((res.result as { error: string }).error)).toMatch(/auth/i)
+ // No per-user provider built, no new transport opened (call not forwarded).
+ expect(built.filter(b => b.principal !== 'shared')).toEqual([])
+ expect(sdk.transports.length).toBe(transportsAfterRepresentative)
+ })
+
+ it("'anonymous' userId is rejected the same way", async () => {
+ const { factory, built } = recordingFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+ await manager.addServer(oauthUserServer())
+
+ const res = await manager.callTool('gh__do', {}, { userId: 'anonymous' })
+ expect(res.isError).toBe(true)
+ expect(built.filter(b => b.principal !== 'shared')).toEqual([])
+ })
+})
+
+// ─── Identity isolation ──────────────────────────────────────────────────────
+
+describe('Identity isolation: A partition never serves B', () => {
+ it('each per-user connection carries only its own Bearer token', async () => {
+ const { factory } = recordingFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+ await manager.addServer(oauthUserServer())
+
+ const a = await manager.callTool('gh__do', {}, { userId: 'alice' })
+ const b = await manager.callTool('gh__do', {}, { userId: 'bob' })
+
+ expect((a.result as { authorization?: string }).authorization).toBe('Bearer token-for-alice')
+ expect((b.result as { authorization?: string }).authorization).toBe('Bearer token-for-bob')
+
+ // The representative connection carries NO Authorization (token-less catalog).
+ const authHeaders = sdk.transports.map(t => t.requestHeaders['Authorization'])
+ expect(authHeaders).toContain(undefined)
+ expect(authHeaders).toContain('Bearer token-for-alice')
+ expect(authHeaders).toContain('Bearer token-for-bob')
+ // Alice's token is never present on more than her own connection.
+ expect(authHeaders.filter(h => h === 'Bearer token-for-alice')).toHaveLength(1)
+ })
+
+ it('re-calling as the same user reuses the partition (no second connection)', async () => {
+ const { factory } = recordingFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+ await manager.addServer(oauthUserServer())
+
+ await manager.callTool('gh__do', {}, { userId: 'alice' })
+ const transportsAfterFirst = sdk.transports.length
+ await manager.callTool('gh__do', {}, { userId: 'alice' })
+ expect(sdk.transports.length).toBe(transportsAfterFirst)
+ })
+})
+
+// ─── Revocation purge ────────────────────────────────────────────────────────
+
+describe('Revocation: detachServer purges every ClientKey of the serverName', () => {
+ it('removes representative + all per-user partitions from all maps', async () => {
+ const { factory } = recordingFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+ await manager.addServer(oauthUserServer())
+ await manager.callTool('gh__do', {}, { userId: 'alice' })
+ await manager.callTool('gh__do', {}, { userId: 'bob' })
+ expect(manager.getConnectedServers()).toEqual(['gh'])
+
+ await manager.detachServer('gh')()
+
+ expect(manager.getConnectedServers()).toEqual([])
+ expect(manager.getAllTools()).toEqual([])
+ expect(manager.hasConnectedServers()).toBe(false)
+ expect(manager.status.get('gh')).toBeUndefined()
+ })
+})
+
+// ─── LRU + TTL eviction of per-user partitions ───────────────────────────────
+
+describe('evictIdleUserPartitions — TTL sweep (mini-spec §6)', () => {
+ it('evicts idle per-user partitions but keeps the SHARED representative', async () => {
+ const { factory } = recordingFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+ await manager.addServer(oauthUserServer())
+ await manager.callTool('gh__do', {}, { userId: 'alice' })
+ await manager.callTool('gh__do', {}, { userId: 'bob' })
+
+ // maxIdleMs=0 → every per-user partition is past TTL; SHARED is exempt.
+ const evicted = manager.evictIdleUserPartitions(0)
+ expect(evicted).toBe(2)
+
+ // Representative survives → catalog and connectivity intact.
+ expect(manager.getConnectedServers()).toEqual(['gh'])
+ expect(manager.getAllTools().map(t => t.name)).toEqual(['gh__do'])
+
+ // A later call re-admits the evicted partition lazily.
+ const transportsBefore = sdk.transports.length
+ await manager.callTool('gh__do', {}, { userId: 'alice' })
+ expect(sdk.transports.length).toBe(transportsBefore + 1)
+ })
+
+ it('never evicts a partition with an in-flight tool call (TTL and LRU passes)', async () => {
+ const { factory } = recordingFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+ await manager.addServer(oauthUserServer())
+
+ // Hold a tool call open, and signal when it has actually entered client.callTool.
+ let enteredResolve!: () => void
+ const entered = new Promise<void>(r => (enteredResolve = r))
+ let releaseCall!: () => void
+ const gate = new Promise<void>(r => (releaseCall = r))
+ sdk.callToolImpl = async () => {
+ enteredResolve()
+ await gate
+ return { content: [{ type: 'text', text: 'ok' }] }
+ }
+
+ const inFlight = manager.callTool('gh__do', {}, { userId: 'alice' })
+ await entered // refcount is now > 0
+
+ // Both eviction passes must skip the in-flight partition.
+ expect(manager.evictIdleUserPartitions(0)).toBe(0)
+ expect(manager.evictIdleUserPartitions(0, 0)).toBe(0)
+ expect(manager.getConnectedServers()).toEqual(['gh'])
+
+ releaseCall()
+ await inFlight
+
+ // Once the call completes the partition is eligible again.
+ expect(manager.evictIdleUserPartitions(0)).toBe(1)
+ })
+
+ it('does not evict a re-admitted partition mid-call after a force-eviction (H1 race)', async () => {
+ const { factory } = recordingFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+ await manager.addServer(oauthUserServer())
+
+ const callA = gatedCall()
+ const callB = gatedCall()
+ const queue = [callA, callB]
+ sdk.callToolImpl = async () => {
+ const call = queue.shift()
+ if (!call) throw new Error('unexpected extra callTool')
+ call.enter()
+ await call.gate
+ return { content: [{ type: 'text', text: 'ok' }] }
+ }
+
+ // Call A (alice) in flight.
+ const aPromise = manager.callTool('gh__do', {}, { userId: 'alice' })
+ await callA.entered
+
+ // Force-evict alice's partition (config change → replaceServer → evictPartitionsExcept).
+ await manager.replaceServer(oauthUserServer())
+
+ // Re-admit alice as call B, held open (fresh partition + fresh in-flight token set).
+ const bPromise = manager.callTool('gh__do', {}, { userId: 'alice' })
+ await callB.entered
+
+ // A completes: its finally must remove ONLY A's token, not zero B's set.
+ callA.release()
+ await aPromise
+
+ // B is still in flight → must NOT be evicted by either pass.
+ expect(manager.evictIdleUserPartitions(0)).toBe(0)
+ expect(manager.evictIdleUserPartitions(0, 0)).toBe(0)
+ expect(manager.getConnectedServers()).toEqual(['gh'])
+
+ callB.release()
+ await bPromise
+ // Now B is done → evictable.
+ expect(manager.evictIdleUserPartitions(0)).toBe(1)
+ })
+})
+
+// ─── Representative self-heal (class-a transient failure) ────────────────────
+
+describe('Representative connect failure self-heals on retry (mini-spec §5, class-a)', () => {
+ it('re-admits a ready oauth server after a transient representative failure', async () => {
+ const { factory } = recordingFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+
+ // First representative connect fails transiently; second succeeds.
+ let fail = true
+ sdk.connectImpl = async () => {
+ if (fail) {
+ fail = false
+ throw new Error('transient connect failure')
+ }
+ }
+
+ await expect(manager.addServer(oauthUserServer())).rejects.toThrow(/transient/)
+ // Not connected, but recorded as known inventory (so it is not deleted and
+ // stays retryable — the reconcile "not-connected-but-ready → addServer"
+ // branch fires again on the next poll rather than wedging on serverState).
+ expect(manager.getConnectedServers()).toEqual([])
+ expect(manager.getKnownServers()).toEqual(['gh'])
+ expect(manager.status.get('gh')?.state).toBe('failed')
+
+ // Retry (what the next reconcile poll does) → self-heals.
+ const outcome = await manager.addServer(oauthUserServer())
+ expect(outcome).toBe('applied')
+ expect(manager.getConnectedServers()).toEqual(['gh'])
+ expect(manager.getAllTools().map(t => t.name)).toEqual(['gh__do'])
+ })
+})
+
+// ─── Reconcile no-change branch preserves partitions ─────────────────────────
+
+describe('Reconcile no-change preserves live per-user partitions', () => {
+ it('re-admitting the identical server config keeps existing partitions', async () => {
+ const { factory } = recordingFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+ const server = oauthUserServer()
+ await manager.addServer(server)
+ await manager.callTool('gh__do', {}, { userId: 'alice' })
+ const transportsBefore = sdk.transports.length
+
+ // Identical config → "already connected" no-op branch (mirrors the reconcile
+ // no-change branch that only records serverState).
+ const outcome = await manager.addServer({ ...server })
+ expect(outcome).toBe('applied')
+
+ // Alice's partition survives: another call reuses it (no new connection).
+ await manager.callTool('gh__do', {}, { userId: 'alice' })
+ expect(sdk.transports.length).toBe(transportsBefore)
+ expect(manager.getConnectedServers()).toEqual(['gh'])
+ })
+})
diff --git a/mcp-host/src/mcp/__tests__/proxyMode.test.ts b/mcp-host/src/mcp/__tests__/proxyMode.test.ts
index 79d276fbb..92e1fbf66 100644
--- a/mcp-host/src/mcp/__tests__/proxyMode.test.ts
+++ b/mcp-host/src/mcp/__tests__/proxyMode.test.ts
@@ -1,148 +1,151 @@
/**
* Phase 3 tests: MCP Proxy mode — URL strategy and feature flag behavior.
*/
+import { describe, expect, it, vi } from 'vitest'
+import { McpServerInfo } from '../../types'
+import { McpClient, staticTokenProvider } from '../client'
+import { McpManager } from '../manager'
-import { describe, it, expect, vi } from "vitest";
-import { McpManager } from "../manager";
-import { McpClient } from "../client";
-import { McpServerInfo } from "../../types";
-
-function makeMockServer(name: string, url = "http://mock-server:3000/mcp"): McpServerInfo {
+function makeMockServer(name: string, url = 'http://mock-server:3000/mcp'): McpServerInfo {
return {
name,
description: `Mock ${name}`,
- contextRef: "test-context",
- transport: { type: "streamableHttp", url },
+ contextRef: 'test-context',
+ transport: { type: 'streamableHttp', url },
enabled: true,
status: { deployed: true, ready: true },
- };
+ }
}
-describe("McpClient — proxy URL resolution", () => {
- it("should use direct URL when no proxy configured", () => {
- const server = makeMockServer("mongodb", "http://mongodb.mcp-server:3000/mcp");
- const client = new McpClient(server);
+describe('McpClient — proxy URL resolution', () => {
+ it('should use direct URL when no proxy configured', () => {
+ const server = makeMockServer('mongodb', 'http://mongodb.mcp-server:3000/mcp')
+ const client = new McpClient(server)
// Access private resolveUrl via any cast
- const url = (client as any).resolveUrl();
- expect(url).toBe("http://mongodb.mcp-server:3000/mcp");
- });
-
- it("should use proxy URL when proxy configured", () => {
- const server = makeMockServer("mongodb", "http://mongodb.mcp-server:3000/mcp");
- const client = new McpClient(server, undefined, "http://mcp-proxy.mcp-server:8083");
- const url = (client as any).resolveUrl();
- expect(url).toBe("http://mcp-proxy.mcp-server:8083/servers/mongodb/mcp");
- });
-
- it("should include server name in proxy path", () => {
- const server = makeMockServer("mcp-redis-cache");
- const client = new McpClient(server, undefined, "http://proxy:8083");
- const url = (client as any).resolveUrl();
- expect(url).toBe("http://proxy:8083/servers/mcp-redis-cache/mcp");
- });
-
- it("should use StreamableHTTP transport when proxy is set (even for SSE servers)", () => {
- const server = makeMockServer("legacy-sse");
- server.transport.type = "sse";
- const client = new McpClient(server, undefined, "http://proxy:8083");
- const transport = (client as any).createTransport();
- expect(transport.constructor.name).toBe("StreamableHTTPClientTransport");
- });
-
- it("should use SSE transport for SSE servers without proxy", () => {
- const server = makeMockServer("legacy-sse", "http://sse-server:3000/sse");
- server.transport.type = "sse";
- const client = new McpClient(server);
- const transport = (client as any).createTransport();
- expect(transport.constructor.name).toBe("SSEClientTransport");
- });
-
- it("should preserve auth token through proxy", () => {
- const server = makeMockServer("authed-server");
- const client = new McpClient(server, "secret-token-123", "http://proxy:8083");
+ const url = (client as any).resolveUrl()
+ expect(url).toBe('http://mongodb.mcp-server:3000/mcp')
+ })
+
+ it('should use proxy URL when proxy configured', () => {
+ const server = makeMockServer('mongodb', 'http://mongodb.mcp-server:3000/mcp')
+ const client = new McpClient(server, undefined, 'http://mcp-proxy.mcp-server:8083')
+ const url = (client as any).resolveUrl()
+ expect(url).toBe('http://mcp-proxy.mcp-server:8083/servers/mongodb/mcp')
+ })
+
+ it('should include server name in proxy path', () => {
+ const server = makeMockServer('mcp-redis-cache')
+ const client = new McpClient(server, undefined, 'http://proxy:8083')
+ const url = (client as any).resolveUrl()
+ expect(url).toBe('http://proxy:8083/servers/mcp-redis-cache/mcp')
+ })
+
+ it('should use StreamableHTTP transport when proxy is set (even for SSE servers)', () => {
+ const server = makeMockServer('legacy-sse')
+ server.transport.type = 'sse'
+ const client = new McpClient(server, undefined, 'http://proxy:8083')
+ const transport = (client as any).createTransport()
+ expect(transport.constructor.name).toBe('StreamableHTTPClientTransport')
+ })
+
+ it('should use SSE transport for SSE servers without proxy', () => {
+ const server = makeMockServer('legacy-sse', 'http://sse-server:3000/sse')
+ server.transport.type = 'sse'
+ const client = new McpClient(server)
+ const transport = (client as any).createTransport()
+ expect(transport.constructor.name).toBe('SSEClientTransport')
+ })
+
+ it('should preserve auth token through proxy', () => {
+ const server = makeMockServer('authed-server')
+ const client = new McpClient(
+ server,
+ staticTokenProvider('secret-token-123'),
+ 'http://proxy:8083'
+ )
// Verify the URL is correct (auth is handled at transport level)
- const url = (client as any).resolveUrl();
- expect(url).toBe("http://proxy:8083/servers/authed-server/mcp");
- });
-});
-
-describe("McpManager — proxy mode constructor", () => {
- it("should accept no arguments (backward compatible)", () => {
- const manager = new McpManager();
- expect(manager.getConnectedServers()).toEqual([]);
- });
-
- it("should accept proxy URL", () => {
- const manager = new McpManager("http://proxy:8083");
- expect(manager.getConnectedServers()).toEqual([]);
- });
-
- it("should accept undefined proxy URL (explicit direct mode)", () => {
- const manager = new McpManager(undefined);
- expect(manager.getConnectedServers()).toEqual([]);
- });
-
- it("should pass proxy URL to McpClient on addServer", async () => {
- const manager = new McpManager("http://proxy:8083");
- const server = makeMockServer("test-server");
+ const url = (client as any).resolveUrl()
+ expect(url).toBe('http://proxy:8083/servers/authed-server/mcp')
+ })
+})
+
+describe('McpManager — proxy mode constructor', () => {
+ it('should accept no arguments (backward compatible)', () => {
+ const manager = new McpManager()
+ expect(manager.getConnectedServers()).toEqual([])
+ })
+
+ it('should accept proxy URL', () => {
+ const manager = new McpManager('http://proxy:8083')
+ expect(manager.getConnectedServers()).toEqual([])
+ })
+
+ it('should accept undefined proxy URL (explicit direct mode)', () => {
+ const manager = new McpManager(undefined)
+ expect(manager.getConnectedServers()).toEqual([])
+ })
+
+ it('should pass proxy URL to McpClient on addServer', async () => {
+ const manager = new McpManager('http://proxy:8083')
+ const server = makeMockServer('test-server')
// Mock McpClient.connect to avoid real network calls
- const connectSpy = vi.spyOn(McpClient.prototype, "connect").mockResolvedValue();
- vi.spyOn(McpClient.prototype, "availableTools", "get").mockReturnValue([]);
+ const connectSpy = vi.spyOn(McpClient.prototype, 'connect').mockResolvedValue()
+ vi.spyOn(McpClient.prototype, 'availableTools', 'get').mockReturnValue([])
- await manager.addServer(server);
+ await manager.addServer(server)
- expect(connectSpy).toHaveBeenCalledTimes(1);
- expect(manager.getConnectedServers()).toEqual(["test-server"]);
+ expect(connectSpy).toHaveBeenCalledTimes(1)
+ expect(manager.getConnectedServers()).toEqual(['test-server'])
// Clean up
- vi.restoreAllMocks();
- await manager.disconnectAll();
- });
-});
-
-describe("McpManager — feature flag behavior", () => {
- it("MCP_PROXY_ENABLED=false uses no proxy (direct URLs)", () => {
- const proxyUrl = false ? "http://proxy:8083" : undefined;
- const manager = new McpManager(proxyUrl);
- expect((manager as any).proxyUrl).toBeUndefined();
- });
-
- it("MCP_PROXY_ENABLED=true uses proxy URL", () => {
- const proxyEnabled = true;
- const proxyUrl = proxyEnabled ? "http://proxy:8083" : undefined;
- const manager = new McpManager(proxyUrl);
- expect((manager as any).proxyUrl).toBe("http://proxy:8083");
- });
-});
-
-describe("McpManager — public API unchanged (regression guards)", () => {
- it("should expose getAllTools() method", () => {
- const manager = new McpManager("http://proxy:8083");
- expect(typeof manager.getAllTools).toBe("function");
- expect(manager.getAllTools()).toEqual([]);
- });
-
- it("should expose callTool() method with same signature", async () => {
- const manager = new McpManager("http://proxy:8083");
- const result = await manager.callTool("missing__tool", {});
- expect(result.isError).toBe(true);
- expect(result.result).toEqual({ error: "MCP server not found: missing" });
- });
-
- it("should expose getConnectedServers() method", () => {
- const manager = new McpManager("http://proxy:8083");
- expect(typeof manager.getConnectedServers).toBe("function");
- });
-
- it("should expose hasConnectedServers() method", () => {
- const manager = new McpManager("http://proxy:8083");
- expect(manager.hasConnectedServers()).toBe(false);
- });
-
- it("should expose describeCapabilities() method", () => {
- const manager = new McpManager("http://proxy:8083");
- expect(typeof manager.describeCapabilities).toBe("function");
- expect(manager.describeCapabilities()).toContain("No MCP servers");
- });
-});
+ vi.restoreAllMocks()
+ await manager.disconnectAll()
+ })
+})
+
+describe('McpManager — feature flag behavior', () => {
+ it('MCP_PROXY_ENABLED=false uses no proxy (direct URLs)', () => {
+ const proxyUrl = false ? 'http://proxy:8083' : undefined
+ const manager = new McpManager(proxyUrl)
+ expect((manager as any).proxyUrl).toBeUndefined()
+ })
+
+ it('MCP_PROXY_ENABLED=true uses proxy URL', () => {
+ const proxyEnabled = true
+ const proxyUrl = proxyEnabled ? 'http://proxy:8083' : undefined
+ const manager = new McpManager(proxyUrl)
+ expect((manager as any).proxyUrl).toBe('http://proxy:8083')
+ })
+})
+
+describe('McpManager — public API unchanged (regression guards)', () => {
+ it('should expose getAllTools() method', () => {
+ const manager = new McpManager('http://proxy:8083')
+ expect(typeof manager.getAllTools).toBe('function')
+ expect(manager.getAllTools()).toEqual([])
+ })
+
+ it('should expose callTool() method with same signature', async () => {
+ const manager = new McpManager('http://proxy:8083')
+ const result = await manager.callTool('missing__tool', {})
+ expect(result.isError).toBe(true)
+ expect(result.result).toEqual({ error: 'MCP server not found: missing' })
+ })
+
+ it('should expose getConnectedServers() method', () => {
+ const manager = new McpManager('http://proxy:8083')
+ expect(typeof manager.getConnectedServers).toBe('function')
+ })
+
+ it('should expose hasConnectedServers() method', () => {
+ const manager = new McpManager('http://proxy:8083')
+ expect(manager.hasConnectedServers()).toBe(false)
+ })
+
+ it('should expose describeCapabilities() method', () => {
+ const manager = new McpManager('http://proxy:8083')
+ expect(typeof manager.describeCapabilities).toBe('function')
+ expect(manager.describeCapabilities()).toContain('No MCP servers')
+ })
+})
diff --git a/mcp-host/src/mcp/__tests__/serverStatusAuthError.test.ts b/mcp-host/src/mcp/__tests__/serverStatusAuthError.test.ts
new file mode 100644
index 000000000..072776fbd
--- /dev/null
+++ b/mcp-host/src/mcp/__tests__/serverStatusAuthError.test.ts
@@ -0,0 +1,39 @@
+/**
+ * U4 seam — strict auth-error detection (mini-spec 03 §5).
+ *
+ * isAuthError MUST read only the STRUCTURED HTTP status (401/403). It must NOT
+ * consult the message regex, which would extract '320' from a JSON-RPC -32003
+ * (session-lost) code and misclassify it as an auth error.
+ */
+import { describe, expect, it } from 'vitest'
+import { extractHttpStatus, extractStructuredHttpStatus, isAuthError } from '../serverStatus'
+
+describe('isAuthError — strict structured status only', () => {
+ it('is true for a structured 401 (StreamableHTTP .code) and 403 (.status)', () => {
+ expect(isAuthError({ code: 401, message: 'Unauthorized' })).toBe(true)
+ expect(isAuthError({ status: 401 })).toBe(true)
+ expect(isAuthError({ statusCode: 403 })).toBe(true)
+ expect(isAuthError({ code: 403 })).toBe(true)
+ })
+
+ it('is FALSE for a JSON-RPC -32003 session-lost error (regex would read 320)', () => {
+ // Message deliberately shaped to trigger the lenient regex ("code" + digits).
+ const sessionLost = { code: -32003, message: 'JSON-RPC code -32003 session not found' }
+ expect(isAuthError(sessionLost)).toBe(false)
+ // The lenient extractor IS fooled by the message digits (extracts '320')...
+ expect(extractHttpStatus(sessionLost, sessionLost.message)).toBe(320)
+ // ...but the strict structured extractor (what isAuthError uses) is not.
+ expect(extractStructuredHttpStatus(sessionLost)).toBeNull()
+ })
+
+ it('is false for -32000 and for non-auth HTTP statuses', () => {
+ expect(isAuthError({ code: -32000, message: 'Server not initialized' })).toBe(false)
+ expect(isAuthError({ status: 500 })).toBe(false)
+ expect(isAuthError({ status: 404 })).toBe(false)
+ })
+
+ it('is false when only a message string carries "401" (no structured status)', () => {
+ // No structured field — must not be treated as an auth error.
+ expect(isAuthError(new Error('initialize returned 401'))).toBe(false)
+ })
+})
diff --git a/mcp-host/src/mcp/authoritativeFleet.ts b/mcp-host/src/mcp/authoritativeFleet.ts
index 523fc60d5..5bf195fac 100644
--- a/mcp-host/src/mcp/authoritativeFleet.ts
+++ b/mcp-host/src/mcp/authoritativeFleet.ts
@@ -463,6 +463,15 @@ async function resolveRequiredMcpAuthToken(
server: McpServerInfo,
getAuthToken: (serverName: string) => Promise<string | undefined>
): Promise<string | undefined> {
+ // oauth servers never resolve a token eagerly here: the eager/reconcile path
+ // admits only the token-less representative connection (which populates the
+ // catalog), and per-user/per-context tokens are resolved lazily by the
+ // per-connection tokenProvider at connect time. Returning undefined (never
+ // throwing) keeps the representative admissible without a grant.
+ if (server.auth?.type === 'oauth') {
+ return undefined
+ }
+
if (
!server.enabled ||
!server.status?.ready ||
diff --git a/mcp-host/src/mcp/brokerTokenProvider.ts b/mcp-host/src/mcp/brokerTokenProvider.ts
new file mode 100644
index 000000000..f10211a2f
--- /dev/null
+++ b/mcp-host/src/mcp/brokerTokenProvider.ts
@@ -0,0 +1,124 @@
+/**
+ * Broker-backed per-connection token provider for oauth mcp-servers
+ * (mini-spec 03 §1/§5, spec §U4/§U6).
+ *
+ * Reaches the control-api OAuth broker through the workflow-approval gateway
+ * (decision #6/B — a POST-only L7-allowlisted location, NOT a new direct egress
+ * to control-api). The subject (userId | contextId) is baked into each provider
+ * INSTANCE, and its cache lives in a closure local to that instance: a provider
+ * built for user A can never POST — nor return — user B's token. The factory
+ * builds a fresh provider per ClientKey, so per-user cache isolation is
+ * structural, keyed by principal.
+ *
+ * Fail-closed contract (frozen cross-service, built in U1 — mcp-host is the
+ * consumer):
+ * - 200 {token, expiresAt} → return token; cache honoring expiry.
+ * - 404 {error:'no_grant'} / 403 → resolve() undefined; the call is NOT
+ * forwarded (surfaces as the auth failure
+ * U5 later turns into connect_required).
+ * - missing gateway / control token → undefined (fail closed).
+ * - any other non-200 / malformed 200 body → throw (never forward a stale or
+ * empty token).
+ */
+import type { McpTokenProvider } from './client'
+
+/** House fetch timeout (matches runtimeAuthFactory REISSUE_FETCH_TIMEOUT_MS). */
+export const DEFAULT_BROKER_FETCH_TIMEOUT_MS = 10_000
+/** Reuse a cached token only with this much headroom before its expiry. */
+const CACHE_EXPIRY_HEADROOM_MS = 30_000
+
+export interface BrokerTokenSubject {
+ userId?: string
+ contextId?: string
+}
+
+export interface BrokerTokenProviderDeps {
+ /** Base URL of the workflow-approval gateway (config.mcpHostGatewayUrl). */
+ gatewayUrl: () => string | undefined
+ /** The mcp-host control JWT (scope 'oauth:user-token'). */
+ controlToken: () => string | undefined
+ /** Injectable for tests; defaults to global fetch. */
+ fetchImpl?: typeof fetch
+ /** Bounded per-request timeout; defaults to DEFAULT_BROKER_FETCH_TIMEOUT_MS. */
+ timeoutMs?: number
+ /** Injectable clock for expiry math; defaults to Date.now. */
+ now?: () => number
+}
+
+export function createBrokerTokenProvider(
+ server: { name: string },
+ subject: BrokerTokenSubject,
+ deps: BrokerTokenProviderDeps
+): McpTokenProvider {
+ const fetchImpl = deps.fetchImpl ?? fetch
+ const timeoutMs = deps.timeoutMs ?? DEFAULT_BROKER_FETCH_TIMEOUT_MS
+ const now = deps.now ?? (() => Date.now())
+ let cached: { token: string; expiresAtMs: number | null } | undefined
+
+ const fetchToken = async (): Promise<string | undefined> => {
+ const gatewayUrl = deps.gatewayUrl()?.trim()
+ if (!gatewayUrl) {
+ console.warn('[BrokerTokenProvider] gateway URL not configured; failing closed')
+ return undefined
+ }
+ const controlToken = deps.controlToken()
+ if (!controlToken) {
+ console.warn('[BrokerTokenProvider] control token unavailable; failing closed')
+ return undefined
+ }
+ const body: { mcpServerName: string; userId?: string; contextId?: string } = {
+ mcpServerName: server.name,
+ }
+ if (subject.userId) body.userId = subject.userId
+ if (subject.contextId) body.contextId = subject.contextId
+
+ const res = await fetchImpl(`${gatewayUrl}/api/v1/mcp-oauth/user-token`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${controlToken}`,
+ },
+ body: JSON.stringify(body),
+ // A hung broker must not stall the lazy per-user connect.
+ signal: AbortSignal.timeout(timeoutMs),
+ })
+
+ if (res.status === 200) {
+ const data = (await res.json()) as { token?: unknown; expiresAt?: unknown }
+ if (typeof data.token !== 'string' || data.token.length === 0) {
+ cached = undefined
+ throw new Error(`mcp-oauth broker returned malformed 200 body for ${server.name}`)
+ }
+ const parsed = typeof data.expiresAt === 'string' ? Date.parse(data.expiresAt) : NaN
+ cached = { token: data.token, expiresAtMs: Number.isNaN(parsed) ? null : parsed }
+ return data.token
+ }
+ // no_grant / insufficient_scope → fail closed as "no token".
+ if (res.status === 404 || res.status === 403) {
+ cached = undefined
+ return undefined
+ }
+ // Any other status (400/500/502/503/…) → fail closed with an error.
+ cached = undefined
+ throw new Error(`mcp-oauth broker returned ${res.status} for ${server.name}`)
+ }
+
+ return {
+ resolve: async () => {
+ // Re-validate the grant on every (re)connect; only reuse a cached token
+ // with comfortable headroom before expiry.
+ if (
+ cached &&
+ (cached.expiresAtMs === null || cached.expiresAtMs - now() > CACHE_EXPIRY_HEADROOM_MS)
+ ) {
+ return cached.token
+ }
+ return fetchToken()
+ },
+ refresh: async () => {
+ // Force a fresh exchange (bypass cache) — used after a live 401.
+ cached = undefined
+ return fetchToken()
+ },
+ }
+}
diff --git a/mcp-host/src/mcp/client.ts b/mcp-host/src/mcp/client.ts
index febe8b8e4..80185879f 100644
--- a/mcp-host/src/mcp/client.ts
+++ b/mcp-host/src/mcp/client.ts
@@ -6,6 +6,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 { McpServerInfo, McpTool } from '../types'
+import { extractStructuredHttpStatus, isAuthError } from './serverStatus'
const DEFAULT_MCP_TOOL_TIMEOUT_MS = 3_600_000
const DEFAULT_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS = 3_600_000
@@ -17,6 +18,49 @@ type SupportedMcpTransport = SSEClientTransport | StreamableHTTPClientTransport
export interface McpToolCallOptions {
timeoutMs?: number
signal?: AbortSignal
+ /**
+ * Caller identity used by McpManager to dispatch the per-connection partition
+ * of an oauth grantScope='user' server. Ignored by McpClient itself.
+ */
+ userId?: string
+}
+
+/**
+ * Resolves the Bearer token for a connection just-in-time. `resolve()` is the
+ * normal path (return a cached-then-fetched token, honoring expiry); `refresh()`
+ * FORCES a fresh exchange (used after a live 401). A provider whose `resolve()`
+ * returns undefined yields a token-less connection — the catalog "representative"
+ * connection for an oauth server relies on this (connects without Authorization).
+ */
+export interface McpTokenProvider {
+ resolve(): Promise<string | undefined>
+ refresh(): Promise<string | undefined>
+}
+
+/**
+ * A token provider that always yields the same static token (or none). Preserves
+ * today's behavior for static (secretRef) servers and dev/workflow callers that
+ * pass a plain token string.
+ */
+export function staticTokenProvider(token?: string): McpTokenProvider {
+ return {
+ resolve: async () => token,
+ refresh: async () => token,
+ }
+}
+
+/**
+ * Terminal auth failure surfaced by a live tool call. Thrown when a 403 arrives
+ * (insufficient scope — no retry) or a 401 survives one forced-refresh retry.
+ * The manager evicts the affected per-user partition on this error.
+ */
+export class McpAuthError extends Error {
+ readonly status: number
+ constructor(serverName: string, status: number) {
+ super(`MCP server ${serverName} auth failed (${status})`)
+ this.name = 'McpAuthError'
+ this.status = status
+ }
}
interface McpSdkRequestOptions {
@@ -142,7 +186,9 @@ export class McpClient {
private client: Client | null = null
private transport: SupportedMcpTransport | null = null
private serverConfig: McpServerInfo
- private authToken?: string
+ private tokenProvider?: McpTokenProvider
+ /** Token resolved for the CURRENT connection, re-read on every (re)connect. */
+ private currentAuthToken?: string
private proxyUrl?: string
private tools: McpTool[] = []
private connected: boolean = false
@@ -153,9 +199,9 @@ export class McpClient {
private readonly retirementController = new AbortController()
private readonly transportCleanups = new WeakMap<SupportedMcpTransport, Promise<void>>()
- constructor(serverConfig: McpServerInfo, authToken?: string, proxyUrl?: string) {
+ constructor(serverConfig: McpServerInfo, tokenProvider?: McpTokenProvider, proxyUrl?: string) {
this.serverConfig = serverConfig
- this.authToken = authToken
+ this.tokenProvider = tokenProvider
this.proxyUrl = proxyUrl
}
@@ -252,8 +298,10 @@ export class McpClient {
const { transport } = this.serverConfig
const headers: Record<string, string> = {}
- if (this.authToken) {
- headers['Authorization'] = `Bearer ${this.authToken}`
+ // currentAuthToken is resolved per (re)connect in connect() below; a
+ // representative (token-less) connection leaves it undefined → no header.
+ if (this.currentAuthToken) {
+ headers['Authorization'] = `Bearer ${this.currentAuthToken}`
}
const targetUrl = this.resolveUrl()
@@ -285,6 +333,20 @@ export class McpClient {
console.log(`[MCP:${this.name}] Connecting to ${transport.url} (${transport.type})...`)
this.ensureNotRetired()
+ // Per-connection JIT token resolution (spec §6): the SDK bakes the
+ // Authorization header once at transport-build time, so the token is
+ // re-read here on EVERY (re)connect right before createTransport. A 401
+ // recovery path forces a fresh exchange via tokenProvider.refresh() before
+ // reconnecting, so this resolve() then returns the refreshed token.
+ //
+ // Only await when a provider exists, so the token-less path stays fully
+ // synchronous up to the SDK connect (preserves abort/timeout ordering).
+ if (this.tokenProvider) {
+ this.currentAuthToken = await this.tokenProvider.resolve()
+ ensureNotAborted(options.signal)
+ } else {
+ this.currentAuthToken = undefined
+ }
const connectionEpoch = ++this.connectionEpoch
const nextTransport = this.createTransport()
const nextClient = new Client(
@@ -625,14 +687,69 @@ export class McpClient {
console.log(`[MCP:${this.name}] Tool result:`, JSON.stringify(result).substring(0, 200))
return result
} catch (error) {
- const sessionError = this.isSessionError(error)
+ // Strict auth detection FIRST: only a structured 401/403 counts, never the
+ // message regex (which would read '320' out of a JSON-RPC -32003 code).
+ const authError = isAuthError(error)
+ const sessionError = !authError && this.isSessionError(error)
if (this.retired) {
throw this.lifecycleError('closed')
}
const callCurrent = this.isCallCurrent(callEpoch, callClient)
if (!callCurrent && (!sessionError || !this.canAdoptCallRecovery(callEpoch, callClient))) {
+ // Auth recovery requires the call to still be current — a superseded
+ // call never enters the refresh/retry path (it falls through here).
throw this.lifecycleError('superseded')
}
+ if (authError) {
+ const status = extractStructuredHttpStatus(error)
+ // 403 (insufficient scope) is terminal — never enter the refresh retry.
+ if (status === 403) {
+ console.warn(`[MCP:${this.name}] Tool call rejected (403, insufficient scope) — terminal`)
+ throw new McpAuthError(this.name, 403)
+ }
+ // 401: force a fresh token exchange, reconnect through the SAME fencing
+ // as session recovery, and retry exactly once. A second 401 is terminal.
+ console.warn(
+ `[MCP:${this.name}] Tool call auth failed (401), refreshing token, retrying once...`
+ )
+ try {
+ await this.tokenProvider?.refresh()
+ ensureNotAborted(options.signal)
+ await this.reconnectForCall(callEpoch, callClient, {
+ 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(
+ {
+ name: toolName,
+ arguments: args,
+ },
+ undefined,
+ callRequestOptions()
+ )
+ this.ensureCallCurrent(retryEpoch, retryClient)
+ console.log(
+ `[MCP:${this.name}] Tool result (after auth refresh):`,
+ JSON.stringify(result).substring(0, 200)
+ )
+ return result
+ } catch (retryError) {
+ if (isAuthError(retryError)) {
+ // Second auth failure — terminal (auth_failed), evict upstream. No loop.
+ const retryStatus = extractStructuredHttpStatus(retryError) ?? 401
+ console.error(
+ `[MCP:${this.name}] Tool call auth failed again (${retryStatus}) — terminal`
+ )
+ throw new McpAuthError(this.name, retryStatus)
+ }
+ console.error(`[MCP:${this.name}] Tool call failed after auth refresh:`, retryError)
+ throw retryError
+ }
+ }
if (sessionError) {
console.warn(`[MCP:${this.name}] Session lost, reconnecting and retrying after delay...`)
try {
diff --git a/mcp-host/src/mcp/index.ts b/mcp-host/src/mcp/index.ts
index 1f85617ba..8c1655b5f 100644
--- a/mcp-host/src/mcp/index.ts
+++ b/mcp-host/src/mcp/index.ts
@@ -2,8 +2,16 @@
* MCP (Model Context Protocol) client module.
*/
-export { McpClient } from './client'
-export { McpManager } from './manager'
+export { McpClient, McpAuthError, staticTokenProvider } from './client'
+export type { McpTokenProvider } from './client'
+export {
+ McpManager,
+ SHARED_PRINCIPAL,
+ userPrincipal,
+ serializeClientKey,
+ serverNameFromClientKey,
+} from './manager'
+export type { McpPrincipal, McpTokenProviderFactory } from './manager'
export {
ServerStatusTracker,
classifyConnectError,
diff --git a/mcp-host/src/mcp/manager.ts b/mcp-host/src/mcp/manager.ts
index ab295411d..0c5c3f3c2 100644
--- a/mcp-host/src/mcp/manager.ts
+++ b/mcp-host/src/mcp/manager.ts
@@ -1,8 +1,20 @@
/**
* MCP Manager - manages connections to multiple MCP servers.
+ *
+ * Live connections are keyed by ClientKey = (serverName, principal) where
+ * principal ∈ { SHARED, userId }. Static/oauth-context servers use a single
+ * SHARED partition; oauth-user servers keep one token-less SHARED representative
+ * (populates the catalog) plus N lazily-admitted per-user partitions. Desired
+ * state / catalog / fencing still reason by serverName — see `byServer`.
*/
import { McpServerInfo, McpTool, ToolCallResult } from '../types'
-import { McpClient, type McpToolCallOptions } from './client'
+import {
+ McpAuthError,
+ McpClient,
+ McpTokenProvider,
+ type McpToolCallOptions,
+ staticTokenProvider,
+} from './client'
import { ServerStatusTracker } from './serverStatus'
export type McpAdmissionOutcome = 'applied' | 'stale'
@@ -16,6 +28,7 @@ export type McpDetachedServerCleanup = () => Promise<void>
interface PendingAdmission {
attempt: symbol
client: McpClient
+ serverName: string
}
interface ClientRetirement {
@@ -23,20 +36,77 @@ interface ClientRetirement {
claimed: boolean
}
+// ─── ClientKey / principal ──────────────────────────────────────────────────
+//
+// SHARED is a STRUCTURAL sentinel (a tagged tuple), never a bare literal a real
+// userId could collide with. Serialization tags the shared/user discriminator as
+// the first tuple element, so no userId string can serialize to a SHARED key
+// (property-tested in managerPartition.test.ts, T2).
+
+export type McpPrincipal =
+ | { readonly kind: 'shared' }
+ | { readonly kind: 'user'; readonly userId: string }
+
+export const SHARED_PRINCIPAL: McpPrincipal = { kind: 'shared' }
+
+export function userPrincipal(userId: string): McpPrincipal {
+ return { kind: 'user', userId }
+}
+
+/** Serialize a (serverName, principal) pair into a stable Map key string. */
+export function serializeClientKey(serverName: string, principal: McpPrincipal): string {
+ return principal.kind === 'shared'
+ ? JSON.stringify(['s', serverName])
+ : JSON.stringify(['u', serverName, principal.userId])
+}
+
+/** Recover the serverName from a serialized ClientKey. */
+export function serverNameFromClientKey(key: string): string {
+ return (JSON.parse(key) as [string, string, string?])[1]
+}
+
+/** Factory that builds a per-connection token provider for an oauth server. */
+export type McpTokenProviderFactory = (
+ server: McpServerInfo,
+ principal: McpPrincipal
+) => McpTokenProvider
+
export class McpManager {
+ // Live connections, keyed by serialized ClientKey.
private clients: Map<string, McpClient> = new Map()
+ // Desired-state projection is per-serverName (identical across partitions).
private serverInfos: Map<string, McpServerInfo> = new Map()
private toolToServerMap: Map<string, string> = new Map()
+ // In-flight admissions, keyed by serialized ClientKey.
private pendingAdmissions: Map<string, PendingAdmission> = new Map()
+ // serverName → set of live ClientKeys. Restores serverName-level reasoning
+ // (catalog dedup, connected-servers projection, server-wide purge).
+ private byServer: Map<string, Set<string>> = new Map()
+ // Coalesces concurrent lazy admissions for the same per-user partition.
+ private ensureInFlight: Map<string, Promise<void>> = new Map()
+ // Last-used timestamp for per-user partitions (LRU + TTL eviction).
+ private partitionLastUsed: Map<string, number> = new Map()
+ // In-flight tool-call tokens per per-user partition. A UNIQUE token per call
+ // (not a bare counter): each call removes only its own token, so a completing
+ // call can never zero a *re-admitted* partition's in-flight state after a
+ // force-eviction (the H1 re-admission race). A partition with a live call is
+ // NEVER evicted by the idle sweep (mini-spec §6 — respect in-flight).
+ private partitionInFlight: Map<string, Set<symbol>> = new Map()
private clientRetirements = new WeakMap<McpClient, ClientRetirement>()
private lifecycleEpoch = 0
private closed = false
private proxyUrl?: string
private statusTracker: ServerStatusTracker
+ private tokenProviderFactory?: McpTokenProviderFactory
- constructor(proxyUrl?: string, statusTracker?: ServerStatusTracker) {
+ constructor(
+ proxyUrl?: string,
+ statusTracker?: ServerStatusTracker,
+ tokenProviderFactory?: McpTokenProviderFactory
+ ) {
this.proxyUrl = proxyUrl
this.statusTracker = statusTracker ?? new ServerStatusTracker()
+ this.tokenProviderFactory = tokenProviderFactory
if (proxyUrl) {
console.log(`[McpManager] Proxy mode enabled: ${proxyUrl}`)
}
@@ -50,6 +120,56 @@ export class McpManager {
return this.statusTracker
}
+ private sharedKey(serverName: string): string {
+ return serializeClientKey(serverName, SHARED_PRINCIPAL)
+ }
+
+ private userKey(serverName: string, userId: string): string {
+ return serializeClientKey(serverName, userPrincipal(userId))
+ }
+
+ /**
+ * The representative connection for a serverName: prefer the SHARED partition
+ * (token-less for oauth-user, the sole connection for static/oauth-context),
+ * else any live per-user partition. Powers catalog dedup by serverName.
+ */
+ private representativeClient(serverName: string): McpClient | undefined {
+ const shared = this.clients.get(this.sharedKey(serverName))
+ if (shared) return shared
+ const keys = this.byServer.get(serverName)
+ if (keys) {
+ for (const key of keys) {
+ const client = this.clients.get(key)
+ if (client) return client
+ }
+ }
+ return undefined
+ }
+
+ private buildTokenProvider(
+ serverConfig: McpServerInfo,
+ principal: McpPrincipal,
+ eagerToken: string | undefined
+ ): McpTokenProvider | undefined {
+ if (serverConfig.auth?.type === 'oauth') {
+ // oauth: JIT resolution via the injected factory (broker per-user /
+ // per-context, or token-less representative). No factory (dev/tests) →
+ // token-less, which fails closed on a server that requires auth.
+ //
+ // PRECONDITION (v1 class-a, spec §10.1 VERIFIED / mini-spec 03 §5): catalog
+ // population relies on the SHARED representative connecting WITHOUT auth —
+ // i.e. the server must serve initialize/tools/list unauthenticated and only
+ // 401 on tools/call (own-image, static catalog). A class-b upstream that
+ // auth-gates discovery is OUT of v1 scope and needs the deferred
+ // CRD-declared-schema path (mini-spec 03 §5/§8 "fuente de schema declarado").
+ return this.tokenProviderFactory
+ ? this.tokenProviderFactory(serverConfig, principal)
+ : staticTokenProvider(undefined)
+ }
+ // static/none/bearer/basic/apiKey: preserve today's frozen-token behavior.
+ return staticTokenProvider(eagerToken)
+ }
+
private clearToolMappings(serverName: string): void {
for (const [toolName, server] of this.toolToServerMap.entries()) {
if (server === serverName) {
@@ -58,11 +178,22 @@ export class McpManager {
}
}
- private installConnectedClient(serverConfig: McpServerInfo, client: McpClient): void {
+ private installConnectedClient(
+ key: string,
+ serverConfig: McpServerInfo,
+ client: McpClient
+ ): void {
this.clearToolMappings(serverConfig.name)
- this.clients.set(serverConfig.name, client)
+ this.clients.set(key, client)
this.serverInfos.set(serverConfig.name, serverConfig)
+ let keys = this.byServer.get(serverConfig.name)
+ if (!keys) {
+ keys = new Set()
+ this.byServer.set(serverConfig.name, keys)
+ }
+ keys.add(key)
+
for (const tool of client.availableTools) {
const fullToolName = `${serverConfig.name}__${tool.name}`
this.toolToServerMap.set(fullToolName, serverConfig.name)
@@ -117,7 +248,9 @@ export class McpManager {
}
/**
- * Add and connect to an MCP server.
+ * Add and connect to an MCP server (SHARED partition — the eager coordinator
+ * path). oauth-user servers admit only the token-less representative here;
+ * per-user partitions are lazily admitted on demand via callTool.
*/
async addServer(
serverConfig: McpServerInfo,
@@ -162,8 +295,10 @@ export class McpManager {
return 'applied'
}
- // Check if already connected
- if (this.clients.has(serverConfig.name)) {
+ const key = this.sharedKey(serverConfig.name)
+
+ // Check if already connected (SHARED partition)
+ if (this.clients.has(key)) {
const installed = this.serverInfos.get(serverConfig.name)
if (installed && JSON.stringify(installed) === JSON.stringify(serverConfig)) {
console.log(`[McpManager] Server already connected: ${serverConfig.name}`)
@@ -173,42 +308,67 @@ export class McpManager {
return this.replaceServer(serverConfig, authToken, control)
}
- const client = new McpClient(serverConfig, authToken, this.proxyUrl)
- const attempt = Symbol(serverConfig.name)
- this.pendingAdmissions.set(serverConfig.name, { attempt, client })
- this.statusTracker.markConnecting(serverConfig.name)
+ const tokenProvider = this.buildTokenProvider(serverConfig, SHARED_PRINCIPAL, authToken)
+ return this.connectAndInstall(key, serverConfig, tokenProvider, control, true)
+ }
+
+ /**
+ * Shared connect+install core reused by the eager SHARED path (addServer) and
+ * the lazy per-user path (ensureClient) — one fencing machine (D4), keyed by
+ * ClientKey. `ownsServerStatus` gates the per-serverName status writes so a
+ * per-user admission failure never flips a healthy representative to failed.
+ */
+ private async connectAndInstall(
+ key: string,
+ serverConfig: McpServerInfo,
+ tokenProvider: McpTokenProvider | undefined,
+ control: McpAdmissionControl,
+ ownsServerStatus: boolean
+ ): 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 client = new McpClient(serverConfig, tokenProvider, this.proxyUrl)
+ const attempt = Symbol(key)
+ this.pendingAdmissions.set(key, { attempt, client, serverName: serverConfig.name })
+ if (ownsServerStatus) this.statusTracker.markConnecting(serverConfig.name)
try {
await client.connect()
- if (!isCurrent() || this.pendingAdmissions.get(serverConfig.name)?.attempt !== attempt) {
+ if (!isCurrent() || this.pendingAdmissions.get(key)?.attempt !== attempt) {
await this.scheduleClientCleanup(client, control)
- this.discardPendingAdmission(serverConfig.name, attempt)
+ this.discardPendingAdmission(key, attempt, serverConfig.name)
return 'stale'
}
- this.pendingAdmissions.delete(serverConfig.name)
- this.installConnectedClient(serverConfig, client)
+ this.pendingAdmissions.delete(key)
+ this.installConnectedClient(key, serverConfig, client)
control.onCommit?.()
- console.log(`[McpManager] Added server: ${serverConfig.name}`)
+ console.log(`[McpManager] Installed client: ${key}`)
return 'applied'
} catch (error) {
- if (!isCurrent() || this.pendingAdmissions.get(serverConfig.name)?.attempt !== attempt) {
+ if (!isCurrent() || this.pendingAdmissions.get(key)?.attempt !== attempt) {
await this.scheduleClientCleanup(client, control)
- this.discardPendingAdmission(serverConfig.name, attempt)
+ this.discardPendingAdmission(key, attempt, serverConfig.name)
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.
+ this.pendingAdmissions.delete(key)
+ console.error(`[McpManager] Failed to install client ${key}:`, error)
+ // Only the SHARED/eager path owns the per-serverName status transition. A
+ // per-user admission failure must leave the representative's status intact.
+ if (ownsServerStatus) this.recordAdmissionFailure(serverConfig, error)
throw error
}
}
/**
* 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.
+ * SHARED connection. A candidate failure leaves the previous client, tools,
+ * serverInfo, and connected status untouched. On commit, per-user partitions
+ * of the same server are evicted (the desired config changed for everyone;
+ * they rebuild lazily with the new revision).
*/
async replaceServer(
serverConfig: McpServerInfo,
@@ -221,65 +381,212 @@ export class McpManager {
!this.closed && this.lifecycleEpoch === admissionLifecycleEpoch && externalIsCurrent()
if (!isCurrent()) return 'stale'
- const previousClient = this.clients.get(serverConfig.name)
+ const key = this.sharedKey(serverConfig.name)
+ const previousClient = this.clients.get(key)
if (!previousClient) {
return this.addServer(serverConfig, authToken, control)
}
- const candidate = new McpClient(serverConfig, authToken, this.proxyUrl)
- const attempt = Symbol(serverConfig.name)
- this.pendingAdmissions.set(serverConfig.name, { attempt, client: candidate })
+ const tokenProvider = this.buildTokenProvider(serverConfig, SHARED_PRINCIPAL, authToken)
+ const candidate = new McpClient(serverConfig, tokenProvider, this.proxyUrl)
+ const attempt = Symbol(key)
+ this.pendingAdmissions.set(key, { attempt, client: candidate, serverName: serverConfig.name })
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)
+ if (!isCurrent() || this.pendingAdmissions.get(key)?.attempt !== attempt) {
+ this.discardPendingAdmission(key, attempt, serverConfig.name)
return 'stale'
}
- this.pendingAdmissions.delete(serverConfig.name)
+ this.pendingAdmissions.delete(key)
throw error
}
- if (!isCurrent() || this.pendingAdmissions.get(serverConfig.name)?.attempt !== attempt) {
+ if (!isCurrent() || this.pendingAdmissions.get(key)?.attempt !== attempt) {
await this.scheduleClientCleanup(candidate, control)
- this.discardPendingAdmission(serverConfig.name, attempt)
+ this.discardPendingAdmission(key, attempt, serverConfig.name)
return 'stale'
}
- this.pendingAdmissions.delete(serverConfig.name)
+ this.pendingAdmissions.delete(key)
// Commit is synchronous: readers see either the complete previous
// revision or the complete connected candidate, never a missing server.
- this.installConnectedClient(serverConfig, candidate)
+ this.installConnectedClient(key, serverConfig, candidate)
control.onCommit?.()
+ // The desired config changed for the whole server → per-user partitions are
+ // stale. Evict them (and any in-flight lazy admission) so they rebuild lazily.
+ this.evictPartitionsExcept(serverConfig.name, key, control)
+
await this.scheduleClientCleanup(previousClient, control)
console.log(`[McpManager] Replaced server: ${serverConfig.name}`)
return 'applied'
}
+ /**
+ * Lazily admit a per-user partition for an oauth-user server, reusing the same
+ * connect+install fencing as the eager path. Concurrent callers for the same
+ * partition coalesce onto one admission.
+ */
+ private async ensureClient(serverName: string, userId: string): Promise<void> {
+ const key = this.userKey(serverName, userId)
+ if (this.clients.has(key)) return
+ const existing = this.ensureInFlight.get(key)
+ if (existing) return existing
+
+ const info = this.serverInfos.get(serverName)
+ if (!info) {
+ throw new Error(`MCP server not connected: ${serverName}`)
+ }
+ const tokenProvider = this.buildTokenProvider(info, userPrincipal(userId), undefined)
+ const admission = this.connectAndInstall(key, info, tokenProvider, {}, false).then(
+ () => undefined
+ )
+ const tracked = admission.finally(() => {
+ if (this.ensureInFlight.get(key) === tracked) this.ensureInFlight.delete(key)
+ })
+ this.ensureInFlight.set(key, tracked)
+ return tracked
+ }
+
+ /**
+ * Evict every per-user partition of a server (and any in-flight lazy
+ * admission), except an optional key to keep (the SHARED representative).
+ */
+ private evictPartitionsExcept(
+ serverName: string,
+ keepKey: string,
+ control: McpAdmissionControl
+ ): void {
+ const keys = this.byServer.get(serverName)
+ if (keys) {
+ for (const key of [...keys]) {
+ if (key === keepKey) continue
+ const client = this.clients.get(key)
+ this.clients.delete(key)
+ keys.delete(key)
+ this.partitionLastUsed.delete(key)
+ this.partitionInFlight.delete(key)
+ if (client) void this.scheduleClientCleanup(client, control)
+ }
+ if (keys.size === 0) this.byServer.delete(serverName)
+ }
+ for (const [key, pending] of [...this.pendingAdmissions]) {
+ if (pending.serverName === serverName && key !== keepKey) {
+ this.pendingAdmissions.delete(key)
+ void this.scheduleClientCleanup(pending.client, control)
+ }
+ }
+ for (const key of [...this.ensureInFlight.keys()]) {
+ if (key !== keepKey && serverNameFromClientKey(key) === serverName) {
+ this.ensureInFlight.delete(key)
+ }
+ }
+ }
+
+ /**
+ * Evict a single per-user partition (terminal auth failure). SHARED/static
+ * partitions and per-serverName status/serverInfo are left untouched — a later
+ * call re-admits the partition lazily.
+ */
+ private evictPartition(key: string): void {
+ const client = this.clients.get(key)
+ const serverName = serverNameFromClientKey(key)
+ this.clients.delete(key)
+ this.partitionLastUsed.delete(key)
+ this.partitionInFlight.delete(key)
+ this.ensureInFlight.delete(key)
+ const keys = this.byServer.get(serverName)
+ if (keys) {
+ keys.delete(key)
+ if (keys.size === 0) this.byServer.delete(serverName)
+ }
+ if (client) {
+ const cleanup = this.claimClientCleanup(client)
+ if (cleanup) void cleanup().catch(() => undefined)
+ }
+ }
+
+ /**
+ * Evict idle per-user partitions (LRU + TTL). SHARED/static/representative
+ * partitions are exempt (snapshot-driven, never evicted here). Bounds
+ * revocation latency for oauth-user grants and caps memory. Returns the count
+ * evicted.
+ */
+ evictIdleUserPartitions(maxIdleMs: number, maxUserPartitions?: number): number {
+ const now = Date.now()
+ let evicted = 0
+ const inFlight = (key: string): boolean => (this.partitionInFlight.get(key)?.size ?? 0) > 0
+ // TTL pass — never evict a partition with a live tool call.
+ for (const [key, lastUsed] of [...this.partitionLastUsed]) {
+ if (inFlight(key)) continue
+ if (now - lastUsed >= maxIdleMs) {
+ this.evictPartition(key)
+ evicted += 1
+ }
+ }
+ // LRU-cap pass — same in-flight exemption; only idle partitions are candidates.
+ if (maxUserPartitions !== undefined && this.partitionLastUsed.size > maxUserPartitions) {
+ const ordered = [...this.partitionLastUsed.entries()]
+ .filter(([key]) => !inFlight(key))
+ .sort((a, b) => a[1] - b[1])
+ const overflow = this.partitionLastUsed.size - maxUserPartitions
+ for (let i = 0; i < overflow && i < ordered.length; i++) {
+ this.evictPartition(ordered[i][0])
+ evicted += 1
+ }
+ }
+ return evicted
+ }
+
+ private releaseInFlight(key: string, token: symbol): void {
+ // Remove only THIS call's token. If the partition was force-evicted and
+ // re-admitted under a fresh Set, this no-ops on the new Set instead of
+ // clearing another live call's in-flight state.
+ const set = this.partitionInFlight.get(key)
+ if (!set) return
+ set.delete(token)
+ if (set.size === 0) this.partitionInFlight.delete(key)
+ }
+
/**
* 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.
+ * Purges EVERY ClientKey that shares this serverName (SHARED representative +
+ * all per-user partitions) — a config change / delete affects everyone. This
+ * is the revocation path. Callers can detach every server in an authoritative
+ * revocation snapshot before awaiting any potentially slow disconnect.
*/
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 clients = new Set<McpClient>()
+ const liveKeys = this.byServer.get(serverName)
+ if (liveKeys) {
+ for (const key of liveKeys) {
+ const client = this.clients.get(key)
+ if (client) clients.add(client)
+ this.clients.delete(key)
+ this.partitionLastUsed.delete(key)
+ this.partitionInFlight.delete(key)
+ }
+ }
+ for (const [key, pending] of [...this.pendingAdmissions]) {
+ if (pending.serverName === serverName) {
+ clients.add(pending.client)
+ this.pendingAdmissions.delete(key)
+ }
+ }
+ for (const key of [...this.ensureInFlight.keys()]) {
+ if (serverNameFromClientKey(key) === serverName) this.ensureInFlight.delete(key)
+ }
+
const cleanups = [...clients]
.map(client => this.claimClientCleanup(client))
.filter((cleanup): cleanup is McpDetachedServerCleanup => cleanup !== undefined)
this.clearToolMappings(serverName)
- this.clients.delete(serverName)
+ this.byServer.delete(serverName)
this.serverInfos.delete(serverName)
- this.pendingAdmissions.delete(serverName)
this.statusTracker.remove(serverName)
return async () => {
@@ -322,11 +629,20 @@ export class McpManager {
private detachAllServers(): McpDetachedServerCleanup[] {
this.lifecycleEpoch += 1
- const serverNames = [...new Set([...this.clients.keys(), ...this.pendingAdmissions.keys()])]
+ const serverNames = [
+ ...new Set([
+ ...this.byServer.keys(),
+ ...[...this.pendingAdmissions.values()].map(p => p.serverName),
+ ]),
+ ]
const cleanups = serverNames.map(name => this.detachServer(name))
this.toolToServerMap.clear()
this.serverInfos.clear()
this.pendingAdmissions.clear()
+ this.byServer.clear()
+ this.ensureInFlight.clear()
+ this.partitionLastUsed.clear()
+ this.partitionInFlight.clear()
this.statusTracker.reset()
return cleanups
}
@@ -349,17 +665,22 @@ export class McpManager {
/**
* Get all available tools from all connected servers.
+ *
+ * Deduplicated by serverName via the representative connection: N per-user
+ * partitions of one oauth server contribute the tool exactly once.
* Tool names are prefixed with server name to avoid conflicts.
*/
getAllTools(): McpTool[] {
const allTools: McpTool[] = []
- for (const client of this.clients.values()) {
+ for (const serverName of this.byServer.keys()) {
+ const client = this.representativeClient(serverName)
+ if (!client) continue
for (const tool of client.availableTools) {
// Prefix tool name with server name for uniqueness
allTools.push({
...tool,
- name: `${client.name}__${tool.name}`,
+ name: `${serverName}__${tool.name}`,
})
}
}
@@ -370,15 +691,18 @@ export class McpManager {
/**
* Build a description of all connected MCP servers and their tools.
* Used to give the LLM full context about its available capabilities.
+ * Deduplicated by serverName (representative connection).
*/
describeCapabilities(): string {
- if (this.clients.size === 0) {
+ if (this.byServer.size === 0) {
return 'No MCP servers are currently connected. You cannot use any tools.'
}
const sections: string[] = []
- for (const [serverName, client] of this.clients.entries()) {
+ for (const serverName of this.byServer.keys()) {
+ const client = this.representativeClient(serverName)
+ if (!client) continue
const info = this.serverInfos.get(serverName)
const description = info?.description || 'No description available.'
const tools = client.availableTools
@@ -398,11 +722,16 @@ export class McpManager {
sections.push(section)
}
- return `## Available MCP Servers\n\nYou have access to ${this.clients.size} MCP server(s) with ${this.getAllTools().length} tool(s) total.\nAlways use the full tool name (serverName__toolName) when calling tools.\n\n${sections.join('\n\n')}`
+ return `## Available MCP Servers\n\nYou have access to ${this.byServer.size} MCP server(s) with ${this.getAllTools().length} tool(s) total.\nAlways use the full tool name (serverName__toolName) when calling tools.\n\n${sections.join('\n\n')}`
}
/**
* Call a tool by its full name (serverName__toolName).
+ *
+ * Dispatch by the server's flavor: static & oauth grantScope='context' route
+ * to the SHARED partition; oauth grantScope='user' routes to the caller's
+ * per-user partition (lazily admitted). oauth-user with no/anonymous userId is
+ * rejected fail-closed BEFORE any token is resolved.
*/
async callTool(
fullToolName: string,
@@ -420,8 +749,47 @@ export class McpManager {
}
const [serverName, toolName] = parts
- const client = this.clients.get(serverName)
+ const info = this.serverInfos.get(serverName)
+ const isOauthUser =
+ info?.auth?.type === 'oauth' && (info.oauth?.grantScope ?? 'user') === 'user'
+
+ let key: string
+ if (isOauthUser) {
+ // options.userId originates from the authenticated session (`sender`,
+ // rpc-proxy's auth.sub). It is forwarded verbatim as the broker grant
+ // subject: mcp-host asserts the identity, and control-api is the
+ // authorization authority that resolves the grant against it (spec §U4
+ // must-fix). Fail-closed in practice — a non-sub principal matches no grant
+ // → 404/no_grant → no token. No authz is enforced here by design.
+ const userId = options.userId
+ // Fail-closed: never resolve a token (nor forward the call) without a
+ // concrete user identity on a per-user oauth server.
+ if (!userId || userId === 'anonymous') {
+ return {
+ toolName: fullToolName,
+ result: {
+ error: `Authentication required: ${serverName} needs a per-user connection, but no user identity was provided`,
+ },
+ isError: true,
+ }
+ }
+ key = this.userKey(serverName, userId)
+ try {
+ await this.ensureClient(serverName, userId)
+ } catch (error) {
+ return {
+ toolName: fullToolName,
+ result: {
+ error: `Authentication required for ${serverName}: ${error instanceof Error ? error.message : 'connection failed'}`,
+ },
+ isError: true,
+ }
+ }
+ } else {
+ key = this.sharedKey(serverName)
+ }
+ const client = this.clients.get(key)
if (!client) {
return {
toolName: fullToolName,
@@ -430,19 +798,47 @@ export class McpManager {
}
}
+ // Unique token identifying THIS call's in-flight claim on the partition.
+ const callToken = Symbol('mcp-call')
+ if (isOauthUser) {
+ // Stamp usage only once the partition is confirmed live (a 'stale'
+ // admission installs no client) so no phantom entry counts toward the cap.
+ this.partitionLastUsed.set(key, Date.now())
+ // Pin the partition against idle eviction for the duration of this call.
+ let set = this.partitionInFlight.get(key)
+ if (!set) {
+ set = new Set()
+ this.partitionInFlight.set(key, set)
+ }
+ set.add(callToken)
+ }
+
try {
const result = await client.callTool(toolName, args, options)
+ if (isOauthUser) this.partitionLastUsed.set(key, Date.now())
return {
toolName: fullToolName,
result,
isError: false,
}
} catch (error) {
+ if (error instanceof McpAuthError) {
+ // Terminal auth failure — evict the per-user partition so a later call
+ // (e.g. after the user reconnects) re-admits fresh. Static/shared exempt.
+ if (isOauthUser) this.evictPartition(key)
+ return {
+ toolName: fullToolName,
+ result: { error: error.message },
+ isError: true,
+ }
+ }
return {
toolName: fullToolName,
result: { error: error instanceof Error ? error.message : 'Unknown error' },
isError: true,
}
+ } finally {
+ if (isOauthUser) this.releaseInFlight(key, callToken)
}
}
@@ -450,15 +846,18 @@ export class McpManager {
* Probe every connected server's tool list and update the status tracker.
* Called by the background heartbeat to keep `observedAt` fresh and to
* classify refresh failures (spec §4.5 — stay connected, attach reason).
+ * Probes the representative connection per serverName.
*
* Returns the number of servers probed.
*/
async refreshAllServerStatus(): Promise<number> {
- const entries = [...this.clients.entries()]
+ const entries = [...this.byServer.keys()]
+ .map(name => [name, this.representativeClient(name)] as const)
+ .filter((entry): entry is readonly [string, McpClient] => entry[1] !== undefined)
await Promise.all(
entries.map(async ([name, client]) => {
const result = await client.probeTools()
- if (this.clients.get(name) !== client) return
+ if (this.representativeClient(name) !== client) return
if (!result.ok && result.stale) return
if (result.ok) {
this.statusTracker.updateToolCount(name, result.toolCount)
@@ -471,10 +870,10 @@ export class McpManager {
}
/**
- * Get connected server names.
+ * Get connected server names (projected from the ClientKey index).
*/
getConnectedServers(): string[] {
- return [...this.clients.keys()]
+ return [...this.byServer.keys()]
}
/**
@@ -482,13 +881,19 @@ export class McpManager {
* not-ready, and failed-admission entries that have no connected client.
*/
getKnownServers(): string[] {
- return [...new Set([...this.serverInfos.keys(), ...this.pendingAdmissions.keys()])]
+ return [
+ ...new Set([
+ ...this.serverInfos.keys(),
+ ...[...this.pendingAdmissions.values()].map(p => p.serverName),
+ ]),
+ ]
}
- 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)) {
+ private discardPendingAdmission(key: string, attempt: symbol, serverName: string): void {
+ if (this.pendingAdmissions.get(key)?.attempt !== attempt) return
+ this.pendingAdmissions.delete(key)
+ const hasLiveClient = (this.byServer.get(serverName)?.size ?? 0) > 0
+ if (!hasLiveClient && !this.serverInfos.has(serverName)) {
this.statusTracker.remove(serverName)
}
}
@@ -497,6 +902,6 @@ export class McpManager {
* Check if any servers are connected.
*/
hasConnectedServers(): boolean {
- return this.clients.size > 0
+ return this.byServer.size > 0
}
}
diff --git a/mcp-host/src/mcp/serverStatus.ts b/mcp-host/src/mcp/serverStatus.ts
index dd6d72785..bcacc03d4 100644
--- a/mcp-host/src/mcp/serverStatus.ts
+++ b/mcp-host/src/mcp/serverStatus.ts
@@ -100,7 +100,18 @@ function errorMessage(error: unknown): string {
return String(error)
}
-function extractHttpStatus(error: unknown, msg: string): number | null {
+/**
+ * Extract an HTTP status from the *structured* error shape only — never from
+ * the message string. This is the trustworthy signal: `.status`/`.statusCode`,
+ * or a numeric `.code` that falls in the HTTP range (the MCP SDK puts the HTTP
+ * status in `code` for StreamableHTTP errors).
+ *
+ * Deliberately excludes the message regex: a JSON-RPC error carrying
+ * `code: -32003` would let the regex extract "320" from the digits, which is a
+ * false HTTP status. Auth classification (see `isAuthError`) must use ONLY this
+ * structured signal.
+ */
+export function extractStructuredHttpStatus(error: unknown): number | null {
if (error && typeof error === 'object') {
const status =
(error as Record<string, unknown>).status ?? (error as Record<string, unknown>).statusCode
@@ -109,6 +120,12 @@ function extractHttpStatus(error: unknown, msg: string): number | null {
// MCP SDK sometimes puts an HTTP status in `code` for StreamableHTTP errors.
if (typeof code === 'number' && code >= 100 && code < 600) return code
}
+ return null
+}
+
+export function extractHttpStatus(error: unknown, msg: string): number | null {
+ const structured = extractStructuredHttpStatus(error)
+ if (structured !== null) return structured
// Fallback: "HTTP 401", "status 500", "returned 404"
const m = msg.match(/(?:HTTP|status|returned|code)[^\d]{0,6}(\d{3})/i)
if (m) {
@@ -118,6 +135,18 @@ function extractHttpStatus(error: unknown, msg: string): number | null {
return null
}
+/**
+ * Strict auth-failure detection for a *live* tool call.
+ *
+ * True iff the STRUCTURED HTTP status is exactly 401 or 403. Never consults the
+ * message regex, so a JSON-RPC `-32003` (session-lost) error is NOT an auth
+ * error — that class must keep flowing through the session-recovery path.
+ */
+export function isAuthError(error: unknown): boolean {
+ const status = extractStructuredHttpStatus(error)
+ return status === 401 || status === 403
+}
+
function extractErrorCode(error: unknown): string | null {
if (error && typeof error === 'object') {
const code = (error as Record<string, unknown>).code
diff --git a/mcp-host/src/types.ts b/mcp-host/src/types.ts
index b4642196e..f812880ec 100644
--- a/mcp-host/src/types.ts
+++ b/mcp-host/src/types.ts
@@ -137,11 +137,27 @@ export interface McpServerTransport {
* McpServer authentication configuration.
*/
export interface McpServerAuth {
- type: 'none' | 'bearer' | 'basic' | 'apiKey'
+ type: 'none' | 'bearer' | 'basic' | 'apiKey' | 'oauth'
secretRef?: string
secretKey?: string
}
+/**
+ * OAuth broker configuration for an mcp-server (auth.type === 'oauth').
+ *
+ * Mirrors the separate `spec.oauth` block on the CRD (projected by HCC). Only
+ * `grantScope` is strictly required for the mcp-host connection seam (dispatch
+ * of the per-connection partition); the rest is carried for the token-provider
+ * factory / diagnostics. `grantScope` defaults to 'user' when absent.
+ */
+export interface McpServerOAuth {
+ id?: string
+ provider?: string
+ grantScope?: 'user' | 'context'
+ scopes?: string[]
+ backgroundAccess?: boolean
+}
+
/**
* Deployment status of an MCP server (reported by the skill-mapper operator).
*/
@@ -170,6 +186,11 @@ export interface McpServerInfo {
contextRef: string
transport: McpServerTransport
auth?: McpServerAuth
+ /**
+ * OAuth broker config; present iff auth.type === 'oauth'. Carries `grantScope`
+ * so the manager can dispatch the per-connection partition (user vs shared).
+ */
+ oauth?: McpServerOAuth
enabled: boolean
status: McpServerStatus
}
diff --git a/mcp-host/src/workflow/runtimeAuthFactory.ts b/mcp-host/src/workflow/runtimeAuthFactory.ts
index 9355543b0..7528e7bc4 100644
--- a/mcp-host/src/workflow/runtimeAuthFactory.ts
+++ b/mcp-host/src/workflow/runtimeAuthFactory.ts
@@ -132,7 +132,7 @@ export function createMcpHostRuntimeAuthFromValues(params: {
return auth
}
-function workflowControlTokenFromConfig(): string | undefined {
+export function workflowControlTokenFromConfig(): string | undefined {
const inlineToken = config.mcpHostWorkflowControlToken?.trim()
if (inlineToken) return inlineToken