Skip to content

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

TypeScript

feat(mcp-host): gate the SHARED oauth-context connection on a confirmed grant (spec 13 phase 3)

Diego Zacarias98bf5385bfb6
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index f376de756..c768862a2 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.374",
+ "version": "0.1.375",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.374",
+ "version": "0.1.375",
"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 01ea2fa1e..9021b03f0 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.374",
+ "version": "0.1.375",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/mcp/__tests__/grantRevocationSweep.test.ts b/mcp-host/src/mcp/__tests__/grantRevocationSweep.test.ts
index 26ab3bdea..11e9c006f 100644
--- a/mcp-host/src/mcp/__tests__/grantRevocationSweep.test.ts
+++ b/mcp-host/src/mcp/__tests__/grantRevocationSweep.test.ts
@@ -20,75 +20,38 @@
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { McpServerInfo } from '../../types'
-import type { BrokerTokenProviderDeps } from '../brokerTokenProvider'
-import { createBrokerTokenProvider } from '../brokerTokenProvider'
-import type { McpTokenProvider } from '../client'
import {
type GrantExistsResult,
- buildGrantExistenceQueries,
checkGrantExistence,
selectRevokedPartitionKeys,
} from '../grantExistenceClient'
-import {
- type LiveOAuthPartition,
- McpManager,
- type McpPrincipal,
- type McpTokenProviderFactory,
- serializeClientKey,
- userPrincipal,
-} from '../manager'
+import { type LiveOAuthPartition, McpManager, serializeClientKey, userPrincipal } from '../manager'
+import { type RemoteUpstreamState, brokerWiring, sweepOnce } from './helpers/brokerWiring'
// ─── transport-aware SDK mock (Bearer presence drives the 401) ────────────────
-
-interface MockTransport {
- requestHeaders: Record<string, string>
- close: ReturnType<typeof vi.fn>
-}
-const sdk: {
- transports: MockTransport[]
- callToolImpl: ((auth: string) => Promise<unknown>) | null
-} = { transports: [], callToolImpl: 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
- })
- close = vi.fn().mockResolvedValue(undefined)
- listTools = vi.fn(async () => ({
- tools: [{ name: 'do', description: 'demo tool', inputSchema: { type: 'object' } }],
- }))
- callTool = vi.fn(async () => {
- const auth = this.transport?.requestHeaders?.['Authorization']
- // No Bearer models "no grant → no token"; the server rejects with 401.
- if (!auth) {
- const err = new Error('http 401') as Error & { code: number }
- err.code = 401
- throw err
- }
- if (sdk.callToolImpl) return sdk.callToolImpl(auth)
- return { content: [{ type: 'text', text: 'ok' }], authorization: auth }
- })
- },
-}))
-
-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)
- },
+// The lenient upstream (accepts initialize token-less, 401s at tools/call) and
+// the broker+exists wiring both come from the shared helper (T1: one source of
+// truth). The state is a plain literal in a synchronous vi.hoisted; each vi.mock
+// factory dynamically imports the builder — a factory runs before the file's
+// static imports resolve, so it cannot reference them directly.
+const sdk = vi.hoisted<RemoteUpstreamState>(() => ({
+ transports: [],
+ probeAuth: [],
+ callToolImpl: null,
+ toolCall401Count: 0,
}))
+vi.mock('@modelcontextprotocol/sdk/client/index.js', async () => {
+ const { remoteUpstream } = await import('./helpers/brokerWiring')
+ return remoteUpstream({ strict: false }, sdk).clientModule
+})
+vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', async () => {
+ const { remoteUpstream } = await import('./helpers/brokerWiring')
+ return remoteUpstream({ strict: false }, sdk).transportModule
+})
+vi.mock('@modelcontextprotocol/sdk/client/sse.js', async () => {
+ const { remoteUpstream } = await import('./helpers/brokerWiring')
+ return remoteUpstream({ strict: false }, sdk).sseModule
+})
// ─── fixtures ─────────────────────────────────────────────────────────────────
@@ -121,78 +84,6 @@ function staticServer(name = 'airtable'): McpServerInfo {
}
}
-/**
- * A single fake `fetch` for both broker endpoints, reading a shared grant store.
- * `/user-token` mints while the grant exists (404 otherwise); `/grants/exists`
- * echoes the query coordinates and reports existence from the SAME store — the
- * control-api response shape reproduced faithfully.
- */
-function brokerWiring(grantStore: Set<string>): {
- deps: BrokerTokenProviderDeps
- factory: McpTokenProviderFactory
- existsCalls: Array<Array<{ mcpServerName: string; userId?: string }>>
- failExistsWith?: (status: number) => void
-} {
- const existsCalls: Array<Array<{ mcpServerName: string; userId?: string }>> = []
- let existsStatus = 200
- const fetchImpl = vi.fn(async (url: string, init: RequestInit) => {
- const body = JSON.parse(init.body as string)
- if (url.endsWith('/api/v1/mcp-oauth/user-token')) {
- const has = grantStore.has(`${body.mcpServerName}:${body.userId ?? ''}`)
- return (has
- ? {
- status: 200,
- json: async () => ({ token: `tok-${body.userId ?? 'ctx'}`, expiresAt: null }),
- }
- : { status: 404, json: async () => ({ error: 'no_grant' }) }) as unknown as Response
- }
- if (url.endsWith('/api/v1/mcp-oauth/grants/exists')) {
- existsCalls.push(body.queries)
- if (existsStatus !== 200) {
- return {
- status: existsStatus,
- json: async () => ({ error: 'boom' }),
- } as unknown as Response
- }
- const results: GrantExistsResult[] = body.queries.map(
- (q: { mcpServerName: string; userId?: string }) => ({
- mcpServerName: q.mcpServerName,
- ...(q.userId !== undefined ? { userId: q.userId } : {}),
- exists: grantStore.has(`${q.mcpServerName}:${q.userId ?? ''}`),
- })
- )
- return { status: 200, json: async () => ({ results }) } as unknown as Response
- }
- throw new Error(`unexpected url ${url}`)
- })
- const deps: BrokerTokenProviderDeps = {
- gatewayUrl: () => 'http://gw:8092',
- controlToken: () => 'ctl',
- fetchImpl: fetchImpl as unknown as typeof fetch,
- }
- const factory: McpTokenProviderFactory = (
- server: McpServerInfo,
- principal: McpPrincipal
- ): McpTokenProvider => {
- if (server.authKind === 'oauth-context') {
- return createBrokerTokenProvider(server, {}, deps)
- }
- if (server.authKind === 'oauth-user' && principal.kind === 'user') {
- return createBrokerTokenProvider(server, { userId: principal.userId }, deps)
- }
- return { resolve: async () => undefined, refresh: async () => undefined }
- }
- return { deps, factory, existsCalls, failExistsWith: (s: number) => (existsStatus = s) }
-}
-
-/** The sweep exactly as main.ts wires it (no duplicated decision logic). */
-async function sweepOnce(manager: McpManager, deps: BrokerTokenProviderDeps): Promise<number> {
- const partitions = manager.listLiveOAuthPartitions()
- if (partitions.length === 0) return 0
- const results = await checkGrantExistence(deps, buildGrantExistenceQueries(partitions))
- return manager.evictRevokedPartitions(selectRevokedPartitionKeys(partitions, results))
-}
-
beforeEach(() => {
sdk.transports = []
sdk.callToolImpl = null
diff --git a/mcp-host/src/mcp/__tests__/helpers/brokerWiring.ts b/mcp-host/src/mcp/__tests__/helpers/brokerWiring.ts
new file mode 100644
index 000000000..c03c294ef
--- /dev/null
+++ b/mcp-host/src/mcp/__tests__/helpers/brokerWiring.ts
@@ -0,0 +1,232 @@
+/**
+ * Shared broker + upstream test wiring for the remote-oauth partition tests.
+ *
+ * ONE source of truth per test: `brokerWiring(grantStore)` serves BOTH the
+ * broker `/user-token` mint AND the `/grants/exists` probe from the SAME
+ * `grantStore`, and its factory reproduces `createMcpTokenProviderFactory`
+ * (main.ts). So "the grant exists" means the identical thing to the probe (which
+ * decides whether the SHARED opens) and to the token mint (which authenticates
+ * the connection) — no test ever hand-sets a `GrantExistsResult` boolean (T1).
+ * The `/grants/exists` response shape is control-api's echo-the-coordinates
+ * contract, reproduced faithfully.
+ *
+ * `remoteUpstream({ strict })` builds the two SDK Client mocks the rails need:
+ * - strict: a spec-compliant remote that 401s already at `initialize` when no
+ * Authorization reaches an https target (Slack/Notion).
+ * - lenient: a Google-like remote that ACCEPTS `initialize` token-less and only
+ * 401s on `tools/call` — the upstream that makes an ungated eager SHARED
+ * cache a token-less catalog. Its `state.toolCall401Count` counts those 401s.
+ * The mocks are returned as plain module objects so a test wires them through its
+ * own `vi.mock(...)` calls; the returned `state` is what assertions read.
+ */
+import { vi } from 'vitest'
+import type { McpServerInfo } from '../../../types'
+import type { BrokerTokenProviderDeps } from '../../brokerTokenProvider'
+import { createBrokerTokenProvider } from '../../brokerTokenProvider'
+import type { McpTokenProvider } from '../../client'
+import {
+ type GrantExistsResult,
+ buildGrantExistenceQueries,
+ checkGrantExistence,
+ selectRevokedPartitionKeys,
+} from '../../grantExistenceClient'
+import { McpManager, type McpPrincipal, type McpTokenProviderFactory } from '../../manager'
+
+export interface BrokerWiring {
+ deps: BrokerTokenProviderDeps
+ factory: McpTokenProviderFactory
+ /** Every `/grants/exists` batch POSTed, in order (assert probe count/coordinates). */
+ existsCalls: Array<Array<{ mcpServerName: string; userId?: string }>>
+ /** Force the next `/grants/exists` responses to a non-200 (throws at the client). */
+ failExistsWith: (status: number) => void
+}
+
+/**
+ * A single fake `fetch` for both broker endpoints, reading a shared grant store.
+ * `/user-token` mints while the grant exists (404 otherwise); `/grants/exists`
+ * echoes the query coordinates and reports existence from the SAME store — the
+ * control-api response shape reproduced faithfully.
+ */
+export function brokerWiring(grantStore: Set<string>): BrokerWiring {
+ const existsCalls: Array<Array<{ mcpServerName: string; userId?: string }>> = []
+ let existsStatus = 200
+ const fetchImpl = vi.fn(async (url: string, init: RequestInit) => {
+ const body = JSON.parse(init.body as string)
+ if (url.endsWith('/api/v1/mcp-oauth/user-token')) {
+ const has = grantStore.has(`${body.mcpServerName}:${body.userId ?? ''}`)
+ return (has
+ ? {
+ status: 200,
+ json: async () => ({ token: `tok-${body.userId ?? 'ctx'}`, expiresAt: null }),
+ }
+ : { status: 404, json: async () => ({ error: 'no_grant' }) }) as unknown as Response
+ }
+ if (url.endsWith('/api/v1/mcp-oauth/grants/exists')) {
+ existsCalls.push(body.queries)
+ if (existsStatus !== 200) {
+ return {
+ status: existsStatus,
+ json: async () => ({ error: 'boom' }),
+ } as unknown as Response
+ }
+ const results: GrantExistsResult[] = body.queries.map(
+ (q: { mcpServerName: string; userId?: string }) => ({
+ mcpServerName: q.mcpServerName,
+ ...(q.userId !== undefined ? { userId: q.userId } : {}),
+ exists: grantStore.has(`${q.mcpServerName}:${q.userId ?? ''}`),
+ })
+ )
+ return { status: 200, json: async () => ({ results }) } as unknown as Response
+ }
+ throw new Error(`unexpected url ${url}`)
+ })
+ const deps: BrokerTokenProviderDeps = {
+ gatewayUrl: () => 'http://gw:8092',
+ controlToken: () => 'ctl',
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ }
+ const factory: McpTokenProviderFactory = (
+ server: McpServerInfo,
+ principal: McpPrincipal
+ ): McpTokenProvider => {
+ if (server.authKind === 'oauth-context') {
+ return createBrokerTokenProvider(server, {}, deps)
+ }
+ if (server.authKind === 'oauth-user' && principal.kind === 'user') {
+ return createBrokerTokenProvider(server, { userId: principal.userId }, deps)
+ }
+ return { resolve: async () => undefined, refresh: async () => undefined }
+ }
+ return { deps, factory, existsCalls, failExistsWith: (s: number) => (existsStatus = s) }
+}
+
+/** The revocation sweep exactly as main.ts wires it (no duplicated decision logic). */
+export async function sweepOnce(
+ manager: McpManager,
+ deps: BrokerTokenProviderDeps
+): Promise<number> {
+ const partitions = manager.listLiveOAuthPartitions()
+ if (partitions.length === 0) return 0
+ const results = await checkGrantExistence(deps, buildGrantExistenceQueries(partitions))
+ return manager.evictRevokedPartitions(selectRevokedPartitionKeys(partitions, results))
+}
+
+// ─── SDK upstream mocks ───────────────────────────────────────────────────────
+
+export interface MockTransport {
+ url: string
+ requestHeaders: Record<string, string>
+ close: ReturnType<typeof vi.fn>
+}
+
+/** Mutable state the upstream mock records into; assertions read it. */
+export interface RemoteUpstreamState {
+ /** Every transport constructed (one per connect attempt) — its headers/url. */
+ transports: MockTransport[]
+ /** Authorization header of every heartbeat probe (`request`), in order. */
+ probeAuth: Array<string | undefined>
+ /** Overrides the lenient upstream's `callTool` return once authenticated. */
+ callToolImpl: ((auth: string) => Promise<unknown>) | null
+ /** Count of 401s the lenient upstream raised at `tools/call` (missing Bearer). */
+ toolCall401Count: number
+}
+
+export interface RemoteUpstreamMocks {
+ state: RemoteUpstreamState
+ clientModule: { Client: new () => unknown }
+ transportModule: { StreamableHTTPClientTransport: new (url: URL, opts?: unknown) => unknown }
+ sseModule: { SSEClientTransport: new () => unknown }
+}
+
+const TOOLS_RESULT = {
+ tools: [{ name: 'do', description: 'demo tool', inputSchema: { type: 'object' } }],
+}
+
+/** A fresh mutable upstream state. Share ONE across a file's SDK mock factories. */
+export function createUpstreamState(): RemoteUpstreamState {
+ return { transports: [], probeAuth: [], callToolImpl: null, toolCall401Count: 0 }
+}
+
+/** A 401 raised at `initialize` by a spec-compliant remote (strict variant). */
+export class RemoteAuthRequired extends Error {
+ readonly code = 401
+ constructor() {
+ super('initialize returned 401')
+ this.name = 'RemoteAuthRequired'
+ }
+}
+
+/**
+ * Build the SDK Client/transport mocks for a remote upstream. `strict` picks the
+ * upstream flavor (see the module header). A file mocks THREE modules from ONE
+ * shared `state`, so a caller passes the same `state` (from `createUpstreamState`,
+ * held in an async `vi.hoisted`) to every `remoteUpstream(...)` call; omit it and
+ * a fresh state is created. `state` is what assertions read (connect/probe/401
+ * activity). A vi.mock factory runs before the file's static imports resolve, so
+ * these builders must be reached through an async `vi.hoisted` dynamic import.
+ */
+export function remoteUpstream(
+ opts: { strict: boolean },
+ state: RemoteUpstreamState = createUpstreamState()
+): RemoteUpstreamMocks {
+ const strict = opts.strict
+
+ class MockClient {
+ private transport: MockTransport | null = null
+ connect = vi.fn(async (t: MockTransport) => {
+ // Strict remote: a token-less request to an https target 401s at
+ // `initialize`. Lenient remote accepts initialize regardless of the token.
+ if (strict && t.url.startsWith('https:') && !t.requestHeaders['Authorization']) {
+ throw new RemoteAuthRequired()
+ }
+ this.transport = t
+ })
+ close = vi.fn().mockResolvedValue(undefined)
+ listTools = vi.fn(async () => TOOLS_RESULT)
+ request = vi.fn(async () => {
+ const headers = this.transport?.requestHeaders ?? {}
+ state.probeAuth.push(headers['Authorization'])
+ return TOOLS_RESULT
+ })
+ callTool = vi.fn(async () => {
+ const auth = this.transport?.requestHeaders?.['Authorization']
+ // Lenient remote enforces auth only at tools/call: no Bearer → 401. Strict
+ // remote never reaches here token-less (it 401s at initialize).
+ if (!auth) {
+ state.toolCall401Count += 1
+ const err = new Error('http 401') as Error & { code: number }
+ err.code = 401
+ throw err
+ }
+ if (state.callToolImpl) return state.callToolImpl(auth)
+ return { content: [{ type: 'text', text: 'ok' }], authorization: auth }
+ })
+ }
+
+ class MockStreamable {
+ url: string
+ requestHeaders: Record<string, string>
+ close = vi.fn().mockResolvedValue(undefined)
+ constructor(url: URL, opts?: { requestInit?: { headers?: Record<string, string> } }) {
+ this.url = url.toString()
+ this.requestHeaders = opts?.requestInit?.headers ?? {}
+ state.transports.push(this as unknown as MockTransport)
+ }
+ }
+
+ class MockSSE {
+ close = vi.fn().mockResolvedValue(undefined)
+ }
+
+ return {
+ state,
+ clientModule: { Client: MockClient as unknown as new () => unknown },
+ transportModule: {
+ StreamableHTTPClientTransport: MockStreamable as unknown as new (
+ url: URL,
+ opts?: unknown
+ ) => unknown,
+ },
+ sseModule: { SSEClientTransport: MockSSE as unknown as new () => unknown },
+ }
+}
diff --git a/mcp-host/src/mcp/__tests__/managerSharedGrantGate.test.ts b/mcp-host/src/mcp/__tests__/managerSharedGrantGate.test.ts
new file mode 100644
index 000000000..6c26fe97a
--- /dev/null
+++ b/mcp-host/src/mcp/__tests__/managerSharedGrantGate.test.ts
@@ -0,0 +1,226 @@
+/**
+ * SHARED oauth-context grant gate (spec §6.2, invariants 3/4/17). A remote
+ * oauth-context server's SHARED representative opens ONLY once its context grant
+ * is confirmed — never token-less before it. The dangerous upstream is the
+ * lenient one (Google-like: accepts `initialize` token-less, 401s at tools/call),
+ * because an ungated eager admission would cache a token-less catalog against it.
+ *
+ * Fixtures come from the shared helper (T1): `brokerWiring` serves BOTH the probe
+ * (`/grants/exists`) and the token mint (`/user-token`) from ONE grant store, so
+ * "grant exists" means the identical thing to the gate's decision and to the
+ * connection's Authorization; `remoteUpstream({strict:false})` is the real
+ * McpClient over a mocked SDK. Assertions are observable (T4): the catalog
+ * (`getAllTools`), the transport the SHARED opened (its Authorization header or
+ * its absence), the number of `/grants/exists` POSTs, and the 401 counter.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { logger } from '../../logger'
+import type { McpServerInfo } from '../../types'
+import { checkGrantExistence } from '../grantExistenceClient'
+import type { GrantExistenceChecker, McpCatalogBootstrapConfig } from '../grantProbe'
+import { McpManager } from '../manager'
+import { type RemoteUpstreamState, brokerWiring } from './helpers/brokerWiring'
+
+// Lenient (Google-like) upstream + shared state. The state is a plain literal in
+// a synchronous vi.hoisted (no imports — those aren't resolved that early); each
+// vi.mock factory dynamically imports the builder (a factory runs before the
+// file's static imports resolve, so it cannot reference them directly).
+const sdk = vi.hoisted<RemoteUpstreamState>(() => ({
+ transports: [],
+ probeAuth: [],
+ callToolImpl: null,
+ toolCall401Count: 0,
+}))
+vi.mock('@modelcontextprotocol/sdk/client/index.js', async () => {
+ const { remoteUpstream } = await import('./helpers/brokerWiring')
+ return remoteUpstream({ strict: false }, sdk).clientModule
+})
+vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', async () => {
+ const { remoteUpstream } = await import('./helpers/brokerWiring')
+ return remoteUpstream({ strict: false }, sdk).transportModule
+})
+vi.mock('@modelcontextprotocol/sdk/client/sse.js', async () => {
+ const { remoteUpstream } = await import('./helpers/brokerWiring')
+ return remoteUpstream({ strict: false }, sdk).sseModule
+})
+
+// The real SSRF guard is exercised in clientRemoteTarget.test.ts; here it must
+// never touch DNS (the SDK is mocked, so its returned fetch is never invoked).
+vi.mock('../../core/net/ssrf', () => ({
+ SsrfBlockedError: class SsrfBlockedError extends Error {},
+ resolvePinnedPublicIp: vi.fn(async () => '203.0.113.10'),
+ pinnedFetch: vi.fn(() => vi.fn(async () => new Response('{}'))),
+}))
+
+function remoteOauthContextServer(name = 'remote-ctx'): McpServerInfo {
+ return {
+ name,
+ contextRef: 'ctx-1',
+ transport: { type: 'streamableHttp', url: `https://${name}.example.com/mcp` },
+ authKind: 'oauth-context',
+ remote: true,
+ enabled: true,
+ status: { deployed: true, ready: true },
+ }
+}
+
+function bootstrapConfig(over: Partial<McpCatalogBootstrapConfig> = {}): McpCatalogBootstrapConfig {
+ return {
+ enabled: true,
+ waitBudgetMs: 4000,
+ probeTimeoutMs: 2000,
+ connectTimeoutMs: 8000,
+ negativeTtlMs: 15000,
+ failureTtlMs: 60000,
+ probesPerMin: 20,
+ backoffMs: 30000,
+ ...over,
+ }
+}
+
+/** A manager wired with BOTH grant deps — the note the gate requires to engage. */
+function gatedManager(
+ grantStore: Set<string>,
+ cfgOver: Partial<McpCatalogBootstrapConfig> = {},
+ now?: () => number
+): {
+ manager: McpManager
+ existsCalls: ReturnType<typeof brokerWiring>['existsCalls']
+ failExistsWith: ReturnType<typeof brokerWiring>['failExistsWith']
+} {
+ const { deps, factory, existsCalls, failExistsWith } = brokerWiring(grantStore)
+ const grantExistence: GrantExistenceChecker = (queries, { timeoutMs }) =>
+ checkGrantExistence({ ...deps, timeoutMs }, queries)
+ const manager = new McpManager(undefined, undefined, factory, {
+ grantExistence,
+ catalogBootstrap: bootstrapConfig(cfgOver),
+ now,
+ })
+ return { manager, existsCalls, failExistsWith }
+}
+
+beforeEach(() => {
+ sdk.transports = []
+ sdk.callToolImpl = null
+ sdk.toolCall401Count = 0
+})
+
+describe('SHARED oauth-context grant gate (spec §6.2)', () => {
+ // ── invariant 3 (T3) ──
+ it('without a grant, never opens or caches a token-less SHARED', async () => {
+ const grantStore = new Set<string>() // no grant
+ const { manager, existsCalls } = gatedManager(grantStore)
+
+ await expect(manager.addServer(remoteOauthContextServer())).resolves.toBe('applied')
+
+ // No SHARED connection: empty catalog, no connected server, ZERO upstream
+ // transports (nothing token-less was ever constructed).
+ expect(manager.getAllTools()).toEqual([])
+ expect(manager.getConnectedServers()).toEqual([])
+ expect(sdk.transports).toEqual([])
+ // The server is registered connected-with-0-tools (same shape as an
+ // oauth-user server with no live partition), not failed.
+ expect(manager.status.get('remote-ctx')?.state).toBe('connected')
+ expect(manager.status.get('remote-ctx')?.toolCount).toBe(0)
+ // The gate DID probe control-api for the context grant (single source of truth).
+ expect(existsCalls).toEqual([[{ mcpServerName: 'remote-ctx' }]])
+ })
+
+ // ── invariant 3, second half ──
+ it('with a grant, opens an authenticated SHARED whose first tools/call sees no 401', async () => {
+ const grantStore = new Set(['remote-ctx:']) // context grant present (no userId coordinate)
+ const { manager } = gatedManager(grantStore)
+
+ await expect(manager.addServer(remoteOauthContextServer())).resolves.toBe('applied')
+
+ // The authenticated SHARED populated the catalog.
+ expect(manager.getAllTools().map(t => t.name)).toEqual(['remote-ctx__do'])
+ expect(sdk.transports).toHaveLength(1)
+ expect(sdk.transports[0]!.requestHeaders['Authorization']).toBe('Bearer tok-ctx')
+
+ // A first tool call over the SHARED carries the baked Bearer → no 401.
+ const res = await manager.callTool('remote-ctx__do', {}, { userId: 'alice' })
+ expect(res.isError).toBe(false)
+ expect(sdk.toolCall401Count).toBe(0)
+ })
+
+ // ── invariant 4 ──
+ it('a grant landing between polls makes the next addServer connect authenticated', async () => {
+ let clock = 1_000
+ const grantStore = new Set<string>()
+ const { manager } = gatedManager(grantStore, {}, () => clock)
+
+ // First poll: no grant → nothing opened, caches the absence for negativeTtlMs.
+ await manager.addServer(remoteOauthContextServer())
+ expect(manager.getAllTools()).toEqual([])
+ expect(sdk.transports).toEqual([])
+
+ // Grant lands; advance past the negative-cache TTL so discovery re-probes.
+ grantStore.add('remote-ctx:')
+ clock += 16_000
+
+ await expect(manager.addServer(remoteOauthContextServer())).resolves.toBe('applied')
+ expect(manager.getAllTools().map(t => t.name)).toEqual(['remote-ctx__do'])
+ expect(sdk.transports).toHaveLength(1)
+ expect(sdk.transports[0]!.requestHeaders['Authorization']).toBe('Bearer tok-ctx')
+ })
+
+ // ── invariant 17 (SHARED) ──
+ it('kill-switch: without a grant, behaves exactly as today (token-less SHARED)', async () => {
+ const grantStore = new Set<string>() // no grant
+ const { manager, existsCalls } = gatedManager(grantStore, { enabled: false })
+
+ await expect(manager.addServer(remoteOauthContextServer())).resolves.toBe('applied')
+
+ // Legacy eager path: the lenient upstream accepts a token-less `initialize`,
+ // so the SHARED is installed token-less and populates the catalog — the exact
+ // pre-gate behavior the kill-switch must restore.
+ expect(manager.getAllTools().map(t => t.name)).toEqual(['remote-ctx__do'])
+ expect(sdk.transports).toHaveLength(1)
+ expect(sdk.transports[0]!.requestHeaders['Authorization']).toBeUndefined()
+ // The gate never engaged → no grant probe.
+ expect(existsCalls).toEqual([])
+ })
+
+ // ── M10 fail-open: an indeterminate probe must NOT empty the catalog ──
+ it('probe unknown (control-api 5xx) fails open: the SHARED connects as today', async () => {
+ // Grant IS present at the mint; only the /grants/exists probe is broken.
+ const grantStore = new Set(['remote-ctx:'])
+ const { manager, existsCalls, failExistsWith } = gatedManager(grantStore)
+ failExistsWith(500) // /grants/exists 5xx → probeOne resolves 'unknown'
+
+ await expect(manager.addServer(remoteOauthContextServer())).resolves.toBe('applied')
+
+ // Fail-open (invariant of availability): a down control-api must not empty
+ // the catalog, so the SHARED opens exactly like today's eager path. Because
+ // the grant is present at the mint, that connection authenticates.
+ expect(manager.getAllTools().map(t => t.name)).toEqual(['remote-ctx__do'])
+ expect(sdk.transports).toHaveLength(1)
+ expect(sdk.transports[0]!.requestHeaders['Authorization']).toBe('Bearer tok-ctx')
+ // The gate DID probe — it just could not get a definitive answer.
+ expect(existsCalls).toEqual([[{ mcpServerName: 'remote-ctx' }]])
+ })
+
+ // ── Fix 1: detach must clear the awaiting-grant set (no leak / no log suppression) ──
+ it('detach clears awaiting-grant so a later re-add re-logs the entered transition', async () => {
+ const grantStore = new Set<string>() // no grant → the server stays awaiting
+ const { manager } = gatedManager(grantStore)
+ const infoSpy = vi.spyOn(logger, 'info')
+
+ // First registration enters the awaiting-grant state (logs 'entered').
+ await manager.addServer(remoteOauthContextServer())
+ // Detach must remove the server from the awaiting-grant set.
+ await manager.removeServer('remote-ctx')
+ // A fresh registration of the same server, still without a grant, must be a
+ // genuine transition again — the 'entered' log fires a SECOND time. With the
+ // leak it stayed in the set and the second log was suppressed.
+ await manager.addServer(remoteOauthContextServer())
+
+ const enteredLogs = infoSpy.mock.calls.filter(
+ ([fields]) => fields.event === 'mcp_oauth_shared_awaiting_grant' && fields.state === 'entered'
+ )
+ expect(enteredLogs).toHaveLength(2)
+
+ infoSpy.mockRestore()
+ })
+})
diff --git a/mcp-host/src/mcp/manager.ts b/mcp-host/src/mcp/manager.ts
index 5ab3045d8..1fdb8a235 100644
--- a/mcp-host/src/mcp/manager.ts
+++ b/mcp-host/src/mcp/manager.ts
@@ -162,6 +162,15 @@ export class McpManager {
// One probe instance per manager (bootstrap + SHARED gate share it). Undefined
// when no grant checker (or its config) is injected → lazy admission as today.
private readonly grantProbe?: GrantProbe
+ // Kill-switch: the probe is built whenever a checker + config are present, but
+ // the SHARED gate (and bootstrap) only engage while enabled. `enabled=false`
+ // ⇒ every rail falls back to today's eager/lazy admission.
+ private readonly catalogBootstrapEnabled: boolean
+ // Remote oauth-context servers currently registered WITHOUT an authenticated
+ // SHARED connection (no grant yet). Membership drives the once-per-transition
+ // `mcp_oauth_shared_awaiting_grant` log — discovery re-probes every poll, so
+ // logging per poll would be noise; we log only on entering/leaving the set.
+ private readonly sharedAwaitingGrant: Set<string> = new Set()
constructor(
proxyUrl?: string,
@@ -182,6 +191,7 @@ export class McpManager {
options.now ?? Date.now
)
: undefined
+ this.catalogBootstrapEnabled = options?.catalogBootstrap?.enabled ?? false
if (proxyUrl) {
logger.info({ component: 'McpManager' }, 'Proxy mode enabled')
}
@@ -423,19 +433,23 @@ export class McpManager {
// A LOCAL oauth server serves initialize/tools/list unauthenticated, so the
// eager SHARED representative can populate the catalog token-less. A REMOTE
// spec-compliant server 401s already at `initialize`, so that representative
- // CANNOT be token-less. Handle the eager SHARED admission by flavor; the sole
- // case that keeps the eager path is an oauth-context server WITH a factory,
- // whose SHARED representative connects AUTHENTICATED on its context grant and
- // IS the catalog. Everything else must NOT open a token-less SHARED
- // connection:
+ // CANNOT be token-less. Handle the eager SHARED admission by flavor:
// - oauth-user: no shared grant exists → the catalog is authenticated
// PER-USER (each user's partition does the authenticated initialize/
// tools/list, admitted lazily on first tool call, surfaced through the
// per-user representative fallback in representativeClient/getAllTools).
// - no factory (dev/tests): nothing can authenticate the representative →
// fail closed rather than degrade to a masking token-less catalog.
- // In both, register the server (so per-user admission and status derive from
- // it) but open no SHARED connection.
+ // Both register the server (so per-user admission and status derive from it)
+ // but open no SHARED connection.
+ // - oauth-context WITH a factory is the one flavor whose SHARED
+ // representative CAN authenticate (on its context grant) and IS the
+ // catalog — but only once that grant exists. Opening it before the grant
+ // lands connects token-less against a lenient upstream and caches a
+ // token-less catalog. So when the grant gate is engaged we probe first:
+ // the SHARED opens ONLY on a confirmed grant; without one the server is
+ // registered connected-with-0-tools and discovery re-probes each poll,
+ // admitting the SHARED within one poll of the grant landing.
if (serverConfig.remote && this.isOauthServer(serverConfig)) {
const sharedAuthenticates =
serverConfig.authKind === 'oauth-context' && this.tokenProviderFactory !== undefined
@@ -450,6 +464,9 @@ export class McpManager {
// analogue of replaceServer's per-user eviction. There is no SHARED
// representative to keep, so keepKey matches nothing.
this.evictPartitionsExcept(serverConfig.name, this.sharedKey(serverConfig.name), control)
+ // A server that WAS a gated oauth-context (and may be awaiting a grant) is
+ // no longer one here — it must leave the awaiting-grant set.
+ this.leaveSharedAwaitingGrant(serverConfig.name)
this.serverInfos.set(serverConfig.name, serverConfig)
// Reflect whatever the (per-user) representative catalog already holds —
// 0 right after an eviction / until a user with a live grant connects. The
@@ -462,8 +479,20 @@ export class McpManager {
control.onCommit?.()
return 'applied'
}
+ // oauth-context + factory: gate the SHARED admission on a confirmed grant
+ // when the probe is engaged. No probe / kill-switch off ⇒ fall through to
+ // the eager path below (today's behavior, M10 by absence).
+ if (this.grantProbe && this.catalogBootstrapEnabled) {
+ return this.addGatedSharedOauthContext(serverConfig, authToken, control)
+ }
}
+ // Reaching the general SHARED path means this is NOT a gated oauth-context
+ // this poll (a re-purpose to static/none/local-oauth, or the gate off). A
+ // gated oauth-context still awaiting its grant returns above, so this never
+ // clears a legitimately-awaiting server — only re-purposed ones.
+ this.leaveSharedAwaitingGrant(serverConfig.name)
+
const key = this.sharedKey(serverConfig.name)
// Check if already connected (SHARED partition)
@@ -484,6 +513,144 @@ export class McpManager {
return this.connectAndInstall(key, serverConfig, tokenProvider, control, true)
}
+ /**
+ * SHARED oauth-context admission gated on a confirmed grant (§6.2). A live
+ * client or an in-flight admission short-circuits (M13, idempotent + coalesced);
+ * otherwise a single-coordinate probe decides: a confirmed grant (or an
+ * indeterminate probe, fail-open like today) opens the authenticated SHARED;
+ * a definitive absence registers the server connected-with-0-tools and opens
+ * NOTHING, so no token-less catalog is cached and discovery re-probes each poll.
+ */
+ private async addGatedSharedOauthContext(
+ serverConfig: McpServerInfo,
+ authToken: string | undefined,
+ control: McpAdmissionControl
+ ): Promise<McpAdmissionOutcome> {
+ const key = this.sharedKey(serverConfig.name)
+
+ // A live SHARED representative is today's path: same config → no-op,
+ // changed → replace (never re-probes a connection that already exists).
+ if (this.clients.has(key)) {
+ const installed = this.serverInfos.get(serverConfig.name)
+ if (installed && JSON.stringify(installed) === JSON.stringify(serverConfig)) {
+ control.onCommit?.()
+ return 'applied'
+ }
+ return this.replaceServer(serverConfig, authToken, control)
+ }
+
+ // A SHARED admission already in flight (a concurrent discovery poll or the
+ // turn bootstrap): coalesce onto it instead of probing/opening a second
+ // connection (M13). If it landed a client we are done; otherwise it failed or
+ // was absent, so fall through to a fresh probe.
+ const inFlight = this.ensureInFlight.get(key)
+ if (inFlight) {
+ await inFlight
+ if (this.clients.has(key)) {
+ control.onCommit?.()
+ return 'applied'
+ }
+ }
+
+ const verdict = await this.grantProbe!.probeOne({ mcpServerName: serverConfig.name })
+ if (verdict === 'absent') {
+ return this.registerSharedAwaitingGrant(serverConfig, control)
+ }
+ // 'present' (grant confirmed) or 'unknown' (probe indeterminate → fail-open,
+ // connect as today: a down control-api must not empty the catalog).
+ return this.admitSharedOauthContext(serverConfig, control)
+ }
+
+ /**
+ * Open the authenticated SHARED oauth-context representative and register the
+ * admission under the SHARED key so a concurrent discovery poll or the turn
+ * bootstrap coalesces onto this single connection. `evictPartitionsExcept`
+ * preserves this key (keepKey = sharedKey), so a config-change eviction never
+ * orphans the in-flight admission.
+ */
+ private admitSharedOauthContext(
+ serverConfig: McpServerInfo,
+ control: McpAdmissionControl
+ ): Promise<McpAdmissionOutcome> {
+ this.exitSharedAwaitingGrant(serverConfig.name)
+ const key = this.sharedKey(serverConfig.name)
+ const tokenProvider = this.buildTokenProvider(serverConfig, SHARED_PRINCIPAL, undefined)
+ const admission = this.connectAndInstall(key, serverConfig, tokenProvider, control, true)
+ const tracked = admission.then(
+ () => undefined,
+ () => undefined
+ )
+ const cleared = tracked.finally(() => {
+ if (this.ensureInFlight.get(key) === cleared) this.ensureInFlight.delete(key)
+ })
+ this.ensureInFlight.set(key, cleared)
+ return admission
+ }
+
+ /**
+ * No confirmed grant (M9): register the server connected-with-0-tools without
+ * opening any SHARED connection — the exact shape an oauth-user server shows
+ * with no live per-user partition. On a config change, evict stale partitions
+ * (mirror of the fail-closed remote-oauth branch) and refresh serverInfos/status;
+ * on an unchanged re-poll, just commit. The catalog stays empty until the grant
+ * lands and discovery/bootstrap re-probes.
+ */
+ private registerSharedAwaitingGrant(
+ serverConfig: McpServerInfo,
+ control: McpAdmissionControl
+ ): McpAdmissionOutcome {
+ const installed = this.serverInfos.get(serverConfig.name)
+ if (!(installed && JSON.stringify(installed) === JSON.stringify(serverConfig))) {
+ this.evictPartitionsExcept(serverConfig.name, this.sharedKey(serverConfig.name), control)
+ this.serverInfos.set(serverConfig.name, serverConfig)
+ this.statusTracker.markConnected(serverConfig.name, 0)
+ }
+ this.enterSharedAwaitingGrant(serverConfig.name)
+ control.onCommit?.()
+ return 'applied'
+ }
+
+ /** Log (once) that a SHARED oauth-context is now awaiting its grant. */
+ private enterSharedAwaitingGrant(serverName: string): void {
+ if (this.sharedAwaitingGrant.has(serverName)) return
+ this.sharedAwaitingGrant.add(serverName)
+ logger.info(
+ {
+ component: 'McpManager',
+ event: 'mcp_oauth_shared_awaiting_grant',
+ serverName,
+ state: 'entered',
+ },
+ 'SHARED oauth-context awaiting grant; no token-less connection opened'
+ )
+ }
+
+ /** Log (once) that a SHARED oauth-context left the awaiting-grant state. */
+ private exitSharedAwaitingGrant(serverName: string): void {
+ if (!this.sharedAwaitingGrant.delete(serverName)) return
+ logger.info(
+ {
+ component: 'McpManager',
+ event: 'mcp_oauth_shared_awaiting_grant',
+ serverName,
+ state: 'resolved',
+ },
+ 'SHARED oauth-context grant confirmed; opening authenticated connection'
+ )
+ }
+
+ /**
+ * Silently drop a server from the awaiting-grant set when it is removed or
+ * re-purposed (config no longer a gated oauth-context). Distinct from
+ * exitSharedAwaitingGrant, whose 'resolved' log asserts a grant was confirmed —
+ * which did NOT happen here — so this transition is not logged. Leaving the
+ * membership behind would both retain a stale entry and suppress the next
+ * genuine 'entered' log after a re-registration.
+ */
+ private leaveSharedAwaitingGrant(serverName: string): void {
+ this.sharedAwaitingGrant.delete(serverName)
+ }
+
/**
* Shared connect+install core reused by the eager SHARED path (addServer) and
* the lazy per-user path (ensureClient) — one fencing machine (D4), keyed by
@@ -843,6 +1010,7 @@ export class McpManager {
this.byServer.delete(serverName)
this.serverInfos.delete(serverName)
this.statusTracker.remove(serverName)
+ this.leaveSharedAwaitingGrant(serverName)
return async () => {
await this.runDetachedCleanups(cleanups)
@@ -897,6 +1065,7 @@ export class McpManager {
this.ensureInFlight.clear()
this.partitionLastUsed.clear()
this.partitionInFlight.clear()
+ this.sharedAwaitingGrant.clear()
this.grantProbe?.reset()
this.statusTracker.reset()
return cleanups