Skip to content

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

TypeScript

feat(mcp-host): thread grant-probe wiring and connectRequired into manager (spec 13 phase 2)

Diego Zacarias63e3136857ba
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 38ed97aaf..f376de756 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.373",
+ "version": "0.1.374",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.373",
+ "version": "0.1.374",
"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 4f4971423..01ea2fa1e 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.373",
+ "version": "0.1.374",
"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__/managerConnectRequired.test.ts b/mcp-host/src/mcp/__tests__/managerConnectRequired.test.ts
index fc582e5ee..7f3aabe2e 100644
--- a/mcp-host/src/mcp/__tests__/managerConnectRequired.test.ts
+++ b/mcp-host/src/mcp/__tests__/managerConnectRequired.test.ts
@@ -25,9 +25,34 @@ import { McpManager } from '../manager'
const state: { callToolQueue: Array<() => Promise<unknown>> } = { callToolQueue: [] }
+interface MockTransport {
+ url: string
+ requestHeaders: Record<string, string>
+}
+
+/** Structured 401 at `initialize`, mirroring managerRemoteOauthCatalog's mock:
+ * the MCP SDK puts the HTTP status in `.code` for StreamableHTTP errors, so
+ * `extractStructuredHttpStatus` reads 401 and `isAuthError` classifies it. */
+class RemoteAuthRequired extends Error {
+ readonly code = 401
+ constructor() {
+ super('initialize returned 401')
+ this.name = 'RemoteAuthRequired'
+ }
+}
+
vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
Client: class MockClient {
- connect = vi.fn().mockResolvedValue(undefined)
+ private transport: MockTransport | null = null
+ connect = vi.fn(async (t: MockTransport) => {
+ // Spec-compliant remote: a token-less request to an https target 401s at
+ // `initialize`. Local (http) targets serve initialize unauthenticated, so
+ // the pre-existing http fixtures below still connect.
+ if (t.url?.startsWith('https:') && !t.requestHeaders?.['Authorization']) {
+ throw new RemoteAuthRequired()
+ }
+ this.transport = t
+ })
close = vi.fn().mockResolvedValue(undefined)
listTools = vi.fn().mockResolvedValue({
tools: [{ name: 'do', description: 'demo', inputSchema: { type: 'object' } }],
@@ -42,8 +67,13 @@ vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({
StreamableHTTPClientTransport: class {
+ url: string
+ requestHeaders: Record<string, string>
close = vi.fn().mockResolvedValue(undefined)
- constructor(_url: URL, _opts?: unknown) {}
+ constructor(url: URL, opts?: { requestInit?: { headers?: Record<string, string> } }) {
+ this.url = url.toString()
+ this.requestHeaders = opts?.requestInit?.headers ?? {}
+ }
},
}))
@@ -53,6 +83,14 @@ vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({
},
}))
+// Remote (https) admissions pin a public IP via the SSRF guard; neutralize it so
+// these tests never touch DNS (its real behavior lives in clientRemoteTarget.test.ts).
+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 httpError(status: number): () => Promise<never> {
return () => {
const err = new Error(`http ${status}`) as Error & { code: number }
@@ -99,6 +137,25 @@ function tokenFactory(): McpTokenProviderFactory {
})
}
+/** A remote oauth-user server whose per-user `initialize` 401s when the user has
+ * no grant (the token provider resolves undefined → no Authorization header). */
+function remoteOauthUserServer(name = 'remote-bob'): McpServerInfo {
+ return {
+ name,
+ transport: { type: 'streamableHttp', url: `https://${name}.example.com/mcp` },
+ authKind: 'oauth-user',
+ remote: true,
+ enabled: true,
+ status: { deployed: true, ready: true },
+ }
+}
+
+/** Simulates "no grant": the broker 404s → the provider resolves no token, so the
+ * per-user connection reaches the upstream token-less and 401s at `initialize`. */
+function noGrantFactory(): McpTokenProviderFactory {
+ return () => ({ resolve: async () => undefined, refresh: async () => undefined })
+}
+
beforeEach(() => {
state.callToolQueue = []
})
@@ -140,4 +197,22 @@ describe('manager.callTool — U5 reactive consent classification', () => {
expect(result.isError).toBe(true)
expect(result.connectRequired).toBeUndefined()
})
+
+ // Inv. 16 (§9): with another user's partition alive, a second user without a
+ // grant sees the tool, the LLM calls it, and the per-user admission 401s at
+ // `initialize` (a RAW 401, not the McpAuthError of a live tools/call). The
+ // callTool catch must still surface `connectRequired` so the desktop offers the
+ // consent flow. This is the second user's NORMAL path once eager bootstrap makes
+ // the tool visible for everyone via the representative catalog.
+ it('401 at the per-user admission initialize → connect_required marker', async () => {
+ const manager = new McpManager(undefined, undefined, noGrantFactory())
+ // Remote oauth-user: addServer registers it (markConnected, 0 tools) without
+ // connecting — the per-user admission happens lazily in callTool below.
+ await manager.addServer(remoteOauthUserServer('remote-bob'))
+
+ const result = await manager.callTool('remote-bob__do', {}, { userId: 'bob' })
+
+ expect(result.isError).toBe(true)
+ expect(result.connectRequired).toEqual({ mcpServerName: 'remote-bob' })
+ })
})
diff --git a/mcp-host/src/mcp/manager.ts b/mcp-host/src/mcp/manager.ts
index 37e3af557..5ab3045d8 100644
--- a/mcp-host/src/mcp/manager.ts
+++ b/mcp-host/src/mcp/manager.ts
@@ -16,7 +16,13 @@ import {
type McpToolCallOptions,
staticTokenProvider,
} from './client'
-import { ServerStatusTracker } from './serverStatus'
+import {
+ type GrantExistenceChecker,
+ type GrantProbe,
+ type McpCatalogBootstrapConfig,
+ createGrantProbe,
+} from './grantProbe'
+import { ServerStatusTracker, extractStructuredHttpStatus, isAuthError } from './serverStatus'
export interface McpStatusRefreshSummary {
serverCount: number
@@ -35,6 +41,23 @@ export interface McpAdmissionControl {
}
export type McpDetachedServerCleanup = () => Promise<void>
+/**
+ * Optional dependencies for eager catalog bootstrap and the SHARED oauth-context
+ * grant gate. Omitting `grantExistence` (or its policy config) keeps the manager
+ * on today's lazy admission — no bootstrap, no gate — so every existing 3-arg
+ * `new McpManager(...)` construction behaves identically.
+ */
+export interface McpManagerOptions {
+ /** Batch grant-existence checker (control-api `grants/exists`); no checker → no probe. */
+ grantExistence?: GrantExistenceChecker
+ /** LRU cap on live per-user partitions (main.ts OAUTH_USER_PARTITION_MAX). */
+ userPartitionMax?: number
+ /** Probe-policy knobs, injected so grantProbe never imports config.ts. */
+ catalogBootstrap?: McpCatalogBootstrapConfig
+ /** Injectable clock for tests. */
+ now?: () => number
+}
+
interface PendingAdmission {
attempt: symbol
client: McpClient
@@ -136,15 +159,29 @@ export class McpManager {
private proxyUrl?: string
private statusTracker: ServerStatusTracker
private tokenProviderFactory?: McpTokenProviderFactory
+ // 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
constructor(
proxyUrl?: string,
statusTracker?: ServerStatusTracker,
- tokenProviderFactory?: McpTokenProviderFactory
+ tokenProviderFactory?: McpTokenProviderFactory,
+ options?: McpManagerOptions
) {
this.proxyUrl = proxyUrl
this.statusTracker = statusTracker ?? new ServerStatusTracker()
this.tokenProviderFactory = tokenProviderFactory
+ // A probe is inert without both a checker and its policy config; either
+ // absent → stay on today's lazy admission (bootstrap and SHARED gate off).
+ this.grantProbe =
+ options?.grantExistence && options?.catalogBootstrap
+ ? createGrantProbe(
+ options.grantExistence,
+ options.catalogBootstrap,
+ options.now ?? Date.now
+ )
+ : undefined
if (proxyUrl) {
logger.info({ component: 'McpManager' }, 'Proxy mode enabled')
}
@@ -458,7 +495,8 @@ export class McpManager {
serverConfig: McpServerInfo,
tokenProvider: McpTokenProvider | undefined,
control: McpAdmissionControl,
- ownsServerStatus: boolean
+ ownsServerStatus: boolean,
+ options?: McpToolCallOptions
): Promise<McpAdmissionOutcome> {
const admissionLifecycleEpoch = this.lifecycleEpoch
const externalIsCurrent = control.isCurrent ?? (() => true)
@@ -472,7 +510,7 @@ export class McpManager {
if (ownsServerStatus) this.statusTracker.markConnecting(serverConfig.name)
try {
- await client.connect()
+ await client.connect(options ?? {})
if (!isCurrent() || this.pendingAdmissions.get(key)?.attempt !== attempt) {
await this.scheduleClientCleanup(client, control)
this.discardPendingAdmission(key, attempt, serverConfig.name)
@@ -580,7 +618,11 @@ export class McpManager {
* 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> {
+ private async ensureClient(
+ serverName: string,
+ userId: string,
+ options?: McpToolCallOptions
+ ): Promise<void> {
const key = this.userKey(serverName, userId)
if (this.clients.has(key)) return
const existing = this.ensureInFlight.get(key)
@@ -591,7 +633,7 @@ export class McpManager {
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(
+ const admission = this.connectAndInstall(key, info, tokenProvider, {}, false, options).then(
() => undefined
)
const tracked = admission.finally(() => {
@@ -855,6 +897,7 @@ export class McpManager {
this.ensureInFlight.clear()
this.partitionLastUsed.clear()
this.partitionInFlight.clear()
+ this.grantProbe?.reset()
this.statusTracker.reset()
return cleanups
}
@@ -945,6 +988,30 @@ export class McpManager {
* per-user partition (lazily admitted). oauth-user with no/anonymous userId is
* rejected fail-closed BEFORE any token is resolved.
*/
+ /**
+ * Fail-closed admission gates (enabled → authoritative → ready) shared by the
+ * lazy per-user callTool path and the eager catalog bootstrap. serverInfos
+ * retains disabled / not-ready / non-authoritative servers (each eager skip
+ * branch does serverInfos.set before returning), so without this gate a lazy
+ * per-user admission would connect and execute against a server the operator
+ * disabled or that is not ready. A non-admissible server is operator intent
+ * (disabled) or transient/unauthoritative infra (not_ready) — NOT an auth
+ * failure, so the messages stay distinct from the "Authentication required"
+ * cases. Mirrors the eager admission gates in addServer.
+ */
+ private admissionGate(
+ info: McpServerInfo | undefined
+ ): { ok: true } | { ok: false; error: string } {
+ if (!info?.enabled) {
+ return { ok: false, error: `MCP server disabled: ${info?.name}` }
+ }
+ if (info.status?.authoritative === false || !info.status?.ready) {
+ const detail = info.status?.message ? ` (${info.status.message})` : ''
+ return { ok: false, error: `MCP server not ready: ${info.name}${detail}` }
+ }
+ return { ok: true }
+ }
+
async callTool(
fullToolName: string,
args: Record<string, unknown>,
@@ -1001,40 +1068,30 @@ export class McpManager {
}
key = this.userKey(serverName, userId)
// Fail-closed: replicate the eager addServer admission gates
- // (enabled → authoritative → ready, manager.ts:276-305) before opening a
- // per-user connection with the caller's OAuth token. serverInfos retains
- // disabled/not-ready/non-authoritative servers (each skip branch there
- // does serverInfos.set before returning), so without this gate a lazy
- // per-user admission would connect and execute against a server the
- // operator disabled or that is not ready. A non-admissible server is
- // operator intent (disabled) or transient/unauthoritative infra
- // (not_ready) — NOT an auth failure, so surface it distinctly from the
- // "Authentication required" cases above.
- if (!info?.enabled) {
- return {
- toolName: fullToolName,
- result: { error: `MCP server disabled: ${serverName}` },
- isError: true,
- }
- }
- if (info.status?.authoritative === false || !info.status?.ready) {
- const detail = info.status?.message ? ` (${info.status.message})` : ''
- return {
- toolName: fullToolName,
- result: { error: `MCP server not ready: ${serverName}${detail}` },
- isError: true,
- }
+ // (enabled → authoritative → ready) before opening a per-user connection
+ // with the caller's OAuth token — see admissionGate for why.
+ const gate = this.admissionGate(info)
+ if (!gate.ok) {
+ return { toolName: fullToolName, result: { error: gate.error }, isError: true }
}
try {
await this.ensureClient(serverName, userId)
} catch (error) {
- return {
+ const result: ToolCallResult = {
toolName: fullToolName,
result: {
error: `Authentication required for ${serverName}: ${error instanceof Error ? error.message : 'connection failed'}`,
},
isError: true,
}
+ // A 401 during the per-user admission's `initialize` is the same
+ // re-consent signal as a 401 on `tools/call`; without the marker the
+ // desktop cannot offer the reconnect flow. A 403 (insufficient scope)
+ // stays unmarked (terminal), mirroring the McpAuthError path below.
+ if (isAuthError(error) && extractStructuredHttpStatus(error) === 401) {
+ result.connectRequired = { mcpServerName: serverName }
+ }
+ return result
}
} else {
key = this.sharedKey(serverName)