Skip to content

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

TypeScript

Merge feat/mcp-server-oauth into host; reconcile U4 seam onto HCC v2

Diego Zacarias917a8615e5d8
diff --cc host-context-controller/src/hostReconciler.ts
index 203831263,ec5ecab59..b3f9e6fcb
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@@ -1607,7 -1514,8 +1641,8 @@@ export class HostReconciler
const tokens = await issueMcpHostRuntimeTokens(
host.name,
+ host.uid ?? '',
- this.resolveWorkflowControlScopesForHost(host, hasChannelIngress)
+ this.resolveWorkflowControlScopesForHost(host, hasChannelIngress, frontsOAuthServer)
)
const gfs = await mintHostGfsToken({ name: host.name, namespace: host.namespace })
const body = buildMcpHostRuntimeTokenSecret(
diff --cc host-context-controller/src/k8sClient.ts
index 085d4bd89,e32fb5b70..dd8bb1f0f
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@@ -4474,3 -4631,186 +4653,188 @@@ export function createMcpServerProvider
return new McpServerWatcher()
}
}
+
+ function authorizationMetadata(metadata: {
+ uid?: string
+ resourceVersion?: string
+ deletionTimestamp?: string | Date
+ }): { uid: string; resourceVersion: string; deletionTimestamp?: string } {
+ return {
+ uid: metadata.uid ?? '',
+ resourceVersion: metadata.resourceVersion ?? '',
+ ...(metadata.deletionTimestamp
+ ? { deletionTimestamp: new Date(metadata.deletionTimestamp).toISOString() }
+ : {}),
+ }
+ }
+
+ export function isMcpAuthorizationNotFound(error: unknown): boolean {
+ return getErrorCode(error) === 404
+ }
+
+ /**
+ * Live Kubernetes authority used only by the protected v2 Host MCP routes.
+ * Reads are deliberately not served from watch caches: every successful
+ * credential operation is fenced against current object UIDs/resourceVersions.
+ */
+ export function createMcpAuthorizationStore(provider: McpServerProvider): McpAuthorizationStore {
+ if (config.devMode || !customObjectsApi || !hostCustomObjectsApi || !coreApi) {
+ return {
+ async readHost() {
+ return null
+ },
+ async readContext() {
+ return null
+ },
+ async readMcpServer() {
+ return null
+ },
+ async readSecretMetadata() {
+ return null
+ },
+ async readSecret() {
+ return null
+ },
+ }
+ }
+
+ return {
+ async readHost(name: string): Promise<AuthorityHost | null> {
+ try {
+ const object = (await hostCustomObjectsApi!.getNamespacedCustomObject({
+ group: GROUP,
+ version: VERSION,
+ namespace: config.hostNamespace,
+ plural: PLURAL_HOSTS,
+ name,
+ })) as {
+ metadata: {
+ name: string
+ namespace?: string
+ uid?: string
+ resourceVersion?: string
+ deletionTimestamp?: string
+ }
+ spec: HostSpec
+ }
+ return {
+ name: object.metadata.name,
+ namespace: object.metadata.namespace ?? config.hostNamespace,
+ metadata: authorizationMetadata(object.metadata),
+ contextRef: object.spec.contextRef,
+ }
+ } catch (error) {
+ if (isMcpAuthorizationNotFound(error)) return null
+ throw error
+ }
+ },
+
+ async readContext(name: string): Promise<AuthorityContext | null> {
+ try {
+ const object = (await customObjectsApi!.getNamespacedCustomObject({
+ group: GROUP,
+ version: VERSION,
+ namespace: config.namespace,
+ plural: PLURAL_CONTEXTS,
+ name,
+ })) as {
+ metadata: {
+ name: string
+ namespace?: string
+ uid?: string
+ resourceVersion?: string
+ deletionTimestamp?: string
+ }
+ spec: ContextSpec
+ }
+ return {
+ name: object.metadata.name,
+ namespace: object.metadata.namespace ?? config.namespace,
+ metadata: authorizationMetadata(object.metadata),
+ mcpServers: [...object.spec.mcpServers],
+ }
+ } catch (error) {
+ if (isMcpAuthorizationNotFound(error)) return null
+ throw error
+ }
+ },
+
+ async readMcpServer(name: string): Promise<AuthorityMcpServer | null> {
+ try {
+ const object = (await customObjectsApi!.getNamespacedCustomObject({
+ group: GROUP,
+ version: VERSION,
+ namespace: config.namespace,
+ plural: PLURAL_MCPSERVERS,
+ name,
+ })) as McpServerWatchObject & {
+ metadata: McpServerWatchObject['metadata'] & {
+ resourceVersion?: string
+ deletionTimestamp?: string
+ }
+ }
+ const status = provider.getAllServerInfos().find(server => server.name === name)
+ ?.status ?? {
+ deployed: false,
+ ready: false,
+ }
+ return {
+ name: object.metadata.name,
+ namespace: object.metadata.namespace ?? config.namespace,
+ metadata: authorizationMetadata(object.metadata),
+ description: object.spec.description,
+ transport: { ...object.spec.transport },
+ auth: object.spec.auth ? { ...object.spec.auth } : undefined,
++ // grantScope drives the inventory authKind derivation (mini-spec 10 §3.1).
++ oauth: object.spec.oauth ? { ...object.spec.oauth } : undefined,
+ enabled: object.spec.enabled !== false,
+ status,
+ }
+ } catch (error) {
+ if (isMcpAuthorizationNotFound(error)) return null
+ throw error
+ }
+ },
+
+ async readSecretMetadata(name: string): Promise<AuthoritySecretMetadata | null> {
+ try {
+ // CoreV1Api returns a Secret object, but this boundary intentionally
+ // drops `data` immediately. Inventory authorization can therefore use
+ // UID/resourceVersion without making credential bytes available to the
+ // service layer or its DTO/logging path.
+ const object = await coreApi!.readNamespacedSecret({ name, namespace: config.namespace })
+ return {
+ name: object.metadata?.name ?? name,
+ namespace: object.metadata?.namespace ?? config.namespace,
+ metadata: authorizationMetadata({
+ uid: object.metadata?.uid,
+ resourceVersion: object.metadata?.resourceVersion,
+ deletionTimestamp: object.metadata?.deletionTimestamp,
+ }),
+ }
+ } catch (error) {
+ if (isMcpAuthorizationNotFound(error)) return null
+ throw error
+ }
+ },
+
+ async readSecret(name: string): Promise<AuthoritySecret | null> {
+ try {
+ const object = await coreApi!.readNamespacedSecret({ name, namespace: config.namespace })
+ return {
+ name: object.metadata?.name ?? name,
+ namespace: object.metadata?.namespace ?? config.namespace,
+ metadata: authorizationMetadata({
+ uid: object.metadata?.uid,
+ resourceVersion: object.metadata?.resourceVersion,
+ deletionTimestamp: object.metadata?.deletionTimestamp,
+ }),
+ data: { ...(object.data ?? {}) },
+ }
+ } catch (error) {
+ if (isMcpAuthorizationNotFound(error)) return null
+ throw error
+ }
+ },
+ }
+ }
diff --cc host-context-controller/src/mcpAuthorization.test.ts
index 000000000,7cb1605cb..2af2cc9c1
mode 000000,100644..100644
--- a/host-context-controller/src/mcpAuthorization.test.ts
+++ b/host-context-controller/src/mcpAuthorization.test.ts
@@@ -1,0 -1,558 +1,632 @@@
+ import { describe, expect, it, vi } from 'vitest'
+ import type { VerifiedMcpHostPrincipal } from './mcpApiAuthentication'
+ import {
+ type AuthorityContext,
+ type AuthorityHost,
+ type AuthorityMcpServer,
+ type AuthoritySecret,
+ type AuthoritySecretMetadata,
++ deriveAuthKind,
+ McpAuthorizationService,
+ type McpAuthorizationStore,
+ toPublicMcpTransport,
+ } from './mcpAuthorization'
++import type { McpServerOAuth } from './types'
++
++// A complete McpServerOAuth block, shaped like the CRD `spec.oauth` the real
++// producer (k8sClient.readMcpServer) projects — never a hand-built partial.
++const fullOAuth = (grantScope: 'user' | 'context'): McpServerOAuth => ({
++ id: 'oauth-adapter',
++ provider: 'google',
++ clientIdRef: { name: 'oauth-secret', key: 'client-id' },
++ clientSecretRef: { name: 'oauth-secret', key: 'client-secret' },
++ grantScope,
++})
+
+ const meta = (uid: string, resourceVersion: string) => ({ uid, resourceVersion })
+ const principal: VerifiedMcpHostPrincipal = {
+ subject: 'mcp-host/standalone',
+ hostName: 'host-a',
+ hostUid: 'host-uid-a',
+ namespace: 'mcp-host',
+ jti: 'jti-a',
+ issuedAt: 1,
+ expiresAt: 4_000_000_000,
+ audiences: ['host-context-controller'],
+ }
+ const principalB: VerifiedMcpHostPrincipal = {
+ ...principal,
+ hostName: 'host-b',
+ hostUid: 'host-uid-b',
+ jti: 'jti-b',
+ }
+ const host: AuthorityHost = {
+ name: 'host-a',
+ namespace: 'mcp-host',
+ metadata: meta('host-uid-a', '10'),
+ contextRef: 'context-a',
+ }
+ const context: AuthorityContext = {
+ name: 'context-a',
+ namespace: 'mcp-server',
+ metadata: meta('context-uid-a', '20'),
+ mcpServers: ['server-a'],
+ }
+ const contextB: AuthorityContext = {
+ name: 'context-b',
+ namespace: 'mcp-server',
+ metadata: meta('context-uid-b', '21'),
+ mcpServers: ['server-b'],
+ }
+ const server: AuthorityMcpServer = {
+ name: 'server-a',
+ namespace: 'mcp-server',
+ metadata: meta('server-uid-a', '30'),
+ transport: { type: 'streamableHttp', url: 'http://server-a/mcp' },
+ auth: { type: 'bearer', secretRef: 'server-a-auth', secretKey: 'token' },
+ enabled: true,
+ status: { deployed: true, ready: true, authoritative: false },
+ }
+ const serverB: AuthorityMcpServer = {
+ ...server,
+ name: 'server-b',
+ metadata: meta('server-uid-b', '31'),
+ transport: { type: 'streamableHttp', url: 'http://server-b/mcp' },
+ auth: { type: 'bearer', secretRef: 'server-b-auth', secretKey: 'token' },
+ }
+ const secret: AuthoritySecret = {
+ name: 'server-a-auth',
+ namespace: 'mcp-server',
+ metadata: meta('secret-uid-a', '40'),
+ data: { token: Buffer.from('credential-value').toString('base64') },
+ }
+
+ class FakeStore implements McpAuthorizationStore {
+ secretMetadataReads = 0
+ secretValueReads = 0
+ secretMetadataSequence: Array<AuthoritySecretMetadata | null> = [secret]
+ secretSequence: Array<AuthoritySecret | null> = [secret]
+ hostSequence: Array<AuthorityHost | null> | null = null
+ contextSequence: Array<AuthorityContext | null> | null = null
+ serverSequence: Array<AuthorityMcpServer | null> | null = null
+ hostObjects: Map<string, AuthorityHost | null> | null = null
+ contextObjects: Map<string, AuthorityContext | null> | null = null
+ serverObjects: Map<string, AuthorityMcpServer | null> | null = null
+ secretMetadataObjects: Map<string, AuthoritySecretMetadata | null> | null = null
+ secretObjects: Map<string, AuthoritySecret | null> | null = null
+ hostReads = 0
+ contextReads = 0
+ serverReads = 0
+ hostObject: AuthorityHost | null = host
+ contextObject: AuthorityContext | null = context
+ serverObject: AuthorityMcpServer | null = server
+
+ async readHost(name: string) {
+ this.hostReads += 1
+ if (this.hostObjects) return this.hostObjects.get(name) ?? null
+ return this.hostSequence
+ ? this.hostSequence[Math.min(this.hostReads - 1, this.hostSequence.length - 1)]
+ : this.hostObject
+ }
+ async readContext(name: string) {
+ this.contextReads += 1
+ if (this.contextObjects) return this.contextObjects.get(name) ?? null
+ return this.contextSequence
+ ? this.contextSequence[Math.min(this.contextReads - 1, this.contextSequence.length - 1)]
+ : this.contextObject
+ }
+ async readMcpServer(name: string) {
+ this.serverReads += 1
+ if (this.serverObjects) return this.serverObjects.get(name) ?? null
+ return this.serverSequence
+ ? this.serverSequence[Math.min(this.serverReads - 1, this.serverSequence.length - 1)]
+ : this.serverObject
+ }
+ async readSecretMetadata(name: string) {
+ this.secretMetadataReads += 1
+ if (this.secretMetadataObjects) return this.secretMetadataObjects.get(name) ?? null
+ const value =
+ this.secretMetadataSequence[
+ Math.min(this.secretMetadataReads - 1, this.secretMetadataSequence.length - 1)
+ ]
+ return value ? { name: value.name, namespace: value.namespace, metadata: value.metadata } : null
+ }
+ async readSecret(name: string) {
+ this.secretValueReads += 1
+ if (this.secretObjects) return this.secretObjects.get(name) ?? null
+ return this.secretSequence[Math.min(this.secretValueReads - 1, this.secretSequence.length - 1)]
+ }
+ }
+
+ async function expectCredentialFailure(
+ service: McpAuthorizationService,
+ code: string
+ ): Promise<void> {
+ const error = await service.getCredential(principal, 'server-a').then(
+ () => null,
+ reason => reason
+ )
+ expect(error).toMatchObject({ code })
+ expect(error).not.toHaveProperty('token')
+ expect(JSON.stringify(error)).not.toContain(
+ Buffer.from(secret.data.token, 'base64').toString('utf8')
+ )
+ }
+
+ describe('McpAuthorizationService', () => {
+ it('keeps two Host/Context grant sets disjoint in both directions', async () => {
+ const hostB: AuthorityHost = {
+ name: 'host-b',
+ namespace: 'mcp-host',
+ metadata: meta('host-uid-b', '11'),
+ contextRef: 'context-b',
+ }
+ const secretB: AuthoritySecret = {
+ name: 'server-b-auth',
+ namespace: 'mcp-server',
+ metadata: meta('secret-uid-b', '41'),
+ data: { token: Buffer.from('credential-b').toString('base64') },
+ }
+ const store = new FakeStore()
+ store.hostObjects = new Map([
+ [host.name, host],
+ [hostB.name, hostB],
+ ])
+ store.contextObjects = new Map([
+ [context.name, context],
+ [contextB.name, contextB],
+ ])
+ store.serverObjects = new Map([
+ [server.name, server],
+ [serverB.name, serverB],
+ ])
+ store.secretMetadataObjects = new Map([
+ [secret.name, secret],
+ [secretB.name, secretB],
+ ])
+ store.secretObjects = new Map([
+ [secret.name, secret],
+ [secretB.name, secretB],
+ ])
+
+ const service = new McpAuthorizationService(store)
+ await expect(service.listServers(principal)).resolves.toEqual([
+ expect.objectContaining({ name: 'server-a' }),
+ ])
+ await expect(service.listServers(principalB)).resolves.toEqual([
+ expect.objectContaining({ name: 'server-b' }),
+ ])
+ const readsBeforeForeignRequests = {
+ secretMetadata: store.secretMetadataReads,
+ secretValue: store.secretValueReads,
+ }
+ await expect(service.getCredential(principal, 'server-b')).rejects.toMatchObject({
+ code: 'not_found',
+ })
+ await expect(service.getCredential(principalB, 'server-a')).rejects.toMatchObject({
+ code: 'not_found',
+ })
+ expect(store.secretMetadataReads).toBe(readsBeforeForeignRequests.secretMetadata)
+ expect(store.secretValueReads).toBe(readsBeforeForeignRequests.secretValue)
+ await expect(service.getCredential(principalB, 'server-b')).resolves.toMatchObject({
+ token: 'credential-b',
+ })
+ })
+
+ it('projects only valid TCP ports into the public transport contract', () => {
+ expect(toPublicMcpTransport({ type: 'streamableHttp', port: 65_535 })).toEqual({
+ type: 'streamableHttp',
+ port: 65_535,
+ })
+ for (const port of [0, -1, 65_536, 1.5]) {
+ expect(toPublicMcpTransport({ type: 'streamableHttp', port })).toEqual({
+ type: 'streamableHttp',
+ })
+ }
+ })
+
+ it('returns only the current Context inventory and an opaque Secret-aware revision', async () => {
+ const store = new FakeStore()
+ const service = new McpAuthorizationService(store)
+ const inventory = await service.listServers(principal)
+ expect(inventory).toEqual([
+ expect.objectContaining({
+ name: 'server-a',
+ authRequired: true,
+ credentialRevision: expect.any(String),
+ status: { deployed: true, ready: true, authoritative: false },
+ }),
+ ])
+ expect(inventory[0]).not.toHaveProperty('contextRef')
+ expect(inventory[0]).not.toHaveProperty('auth')
+ expect(JSON.stringify(inventory)).not.toContain('credential-value')
+ expect(store.secretMetadataReads).toBe(1)
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it('authorizes before Secret read and returns the same revision for a stable credential', async () => {
+ const store = new FakeStore()
+ const service = new McpAuthorizationService(store)
+ const inventory = await service.listServers(principal)
+ const credential = await service.getCredential(principal, 'server-a')
+ expect(credential).toEqual({
+ token: 'credential-value',
+ credentialRevision: inventory[0].credentialRevision,
+ })
+ })
+
+ it('performs zero Secret reads for a cross-Context or unknown target', async () => {
+ const store = new FakeStore()
+ const service = new McpAuthorizationService(store)
+ await expect(service.getCredential(principal, 'server-b')).rejects.toMatchObject({
+ code: 'not_found',
+ })
+ expect(store.secretMetadataReads).toBe(0)
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it.each(['host', 'context', 'server', 'secret-metadata', 'secret-value'] as const)(
+ 'fails closed without disclosing a credential when the %s store read errors',
+ async read => {
+ const store = new FakeStore()
+ if (read === 'host')
+ vi.spyOn(store, 'readHost').mockRejectedValueOnce(new Error('read failed'))
+ if (read === 'context') {
+ vi.spyOn(store, 'readContext').mockRejectedValueOnce(new Error('read failed'))
+ }
+ if (read === 'server') {
+ vi.spyOn(store, 'readMcpServer').mockRejectedValueOnce(new Error('read failed'))
+ }
+ if (read === 'secret-metadata') {
+ vi.spyOn(store, 'readSecretMetadata').mockRejectedValueOnce(new Error('read failed'))
+ }
+ if (read === 'secret-value') {
+ vi.spyOn(store, 'readSecret').mockRejectedValueOnce(new Error('read failed'))
+ }
+ const service = new McpAuthorizationService(store)
+
+ await expectCredentialFailure(service, 'authorization_unavailable')
+ if (read !== 'secret-value') expect(store.secretValueReads).toBe(0)
+ if (read === 'host' || read === 'context' || read === 'server') {
+ expect(store.secretMetadataReads).toBe(0)
+ }
+ }
+ )
+
+ it.each([
+ ['missing secretRef', { auth: { type: 'bearer' as const } }, secret],
+ ['missing Secret metadata', {}, null],
+ ])('rejects %s before any Secret value read', async (_label, serverOverride, metadataValue) => {
+ const store = new FakeStore()
+ store.serverObject = { ...server, ...(serverOverride as Partial<AuthorityMcpServer>) }
+ store.secretMetadataSequence = metadataValue
+ ? [metadataValue as AuthoritySecretMetadata]
+ : [null]
+ const service = new McpAuthorizationService(store)
+
+ await expectCredentialFailure(service, 'credential_unavailable')
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it.each([
+ ['missing configured key', { other: Buffer.from('other').toString('base64') }],
+ ['empty base64', { token: '' }],
+ ['malformed base64', { token: 'invalid-test-token' }],
+ ['non-UTF8 base64', { token: Buffer.from([0xff]).toString('base64') }],
+ ])('rejects %s without returning Secret data', async (_label, data) => {
+ const store = new FakeStore()
+ store.secretSequence = [{ ...secret, data }]
+ const service = new McpAuthorizationService(store)
+
+ await expectCredentialFailure(service, 'credential_unavailable')
+ expect(store.secretValueReads).toBe(1)
+ })
+
+ it('uses the same opaque denial for a cross-Context and an unknown target', async () => {
+ const store = new FakeStore()
+ const service = new McpAuthorizationService(store)
+ const denied = await Promise.allSettled([
+ service.getCredential(principal, 'server-b'),
+ service.getCredential(principal, 'unknown-server'),
+ ])
+ expect(
+ denied.map(result => (result.status === 'rejected' ? result.reason.code : null))
+ ).toEqual(['not_found', 'not_found'])
+ expect(store.secretMetadataReads).toBe(0)
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it('does not read Secret metadata or values for a disabled or deleting server', async () => {
+ const store = new FakeStore()
+ store.serverObject = { ...server, enabled: false }
+ const service = new McpAuthorizationService(store)
+ await expect(service.listServers(principal)).resolves.toEqual([])
+ await expect(service.getCredential(principal, 'server-a')).rejects.toMatchObject({
+ code: 'not_found',
+ })
+ expect(store.secretMetadataReads).toBe(0)
+ expect(store.secretValueReads).toBe(0)
+
+ store.serverObject = { ...server, metadata: { ...server.metadata, deletionTimestamp: 'now' } }
+ await expect(service.getCredential(principal, 'server-a')).rejects.toMatchObject({
+ code: 'not_found',
+ })
+ expect(store.secretMetadataReads).toBe(0)
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it('returns a null token without reading a Secret when the server has no auth', async () => {
+ const store = new FakeStore()
+ store.serverObject = { ...server, auth: { type: 'none' } }
+ const service = new McpAuthorizationService(store)
+ await expect(service.getCredential(principal, 'server-a')).resolves.toEqual({
+ token: null,
+ credentialRevision: expect.any(String),
+ })
+ expect(store.secretMetadataReads).toBe(0)
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it('changes the credential revision when the McpServer secretKey changes', async () => {
+ const store = new FakeStore()
+ store.serverObject = { ...server, auth: { ...server.auth!, secretKey: 'rotated' } }
+ store.secretSequence = [
+ {
+ ...secret,
+ data: {
+ token: Buffer.from('old').toString('base64'),
+ rotated: Buffer.from('new').toString('base64'),
+ },
+ },
+ ]
+ store.secretMetadataSequence = [store.secretSequence[0]]
+ const service = new McpAuthorizationService(store)
+ const first = await service.getCredential(principal, 'server-a')
+ store.serverObject = { ...server, auth: { ...server.auth!, secretKey: 'token' } }
+ store.secretMetadataReads = 0
+ store.secretValueReads = 0
+ const second = await service.getCredential(principal, 'server-a')
+ expect(first.credentialRevision).not.toBe(second.credentialRevision)
+ expect(first.token).toBe('new')
+ expect(second.token).toBe('old')
+ })
+
+ it('enumerates no foreign server and performs zero Secret reads outside the Context grant', async () => {
+ const store = new FakeStore()
+ store.contextObject = { ...context, mcpServers: [] }
+ const service = new McpAuthorizationService(store)
+
+ await expect(service.listServers(principal)).resolves.toEqual([])
+ expect(store.secretMetadataReads).toBe(0)
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it('performs zero Secret reads when an old JWT is rebound to a recreated Host name', async () => {
+ const store = new FakeStore()
+ store.hostObject = { ...host, metadata: meta('replacement-uid', '11') }
+ const service = new McpAuthorizationService(store)
+ await expect(service.getCredential(principal, 'server-a')).rejects.toMatchObject({
+ code: 'unauthorized',
+ })
+ expect(store.secretMetadataReads).toBe(0)
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it.each([
+ ['missing', null],
+ ['deleting', { ...host, metadata: { ...host.metadata, deletionTimestamp: 'now' } }],
+ ])('performs zero Secret reads when the authenticated Host is %s', async (_state, value) => {
+ const store = new FakeStore()
+ store.hostObject = value
+ const service = new McpAuthorizationService(store)
+
+ await expect(service.getCredential(principal, 'server-a')).rejects.toMatchObject({
+ code: 'unauthorized',
+ })
+ expect(store.secretMetadataReads).toBe(0)
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it.each([
+ ['missing', null],
+ ['deleting', { ...context, metadata: { ...context.metadata, deletionTimestamp: 'now' } }],
+ ])('performs zero Secret reads when the live Context is %s', async (_state, value) => {
+ const store = new FakeStore()
+ store.contextObject = value
+ const service = new McpAuthorizationService(store)
+
+ await expect(service.getCredential(principal, 'server-a')).rejects.toMatchObject({
+ code: 'not_found',
+ })
+ expect(store.secretMetadataReads).toBe(0)
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it('discards inventory when the Host binding changes before the response', async () => {
+ const store = new FakeStore()
+ store.hostSequence = [host, { ...host, metadata: meta('host-uid-a', '11') }]
+ const service = new McpAuthorizationService(store)
+
+ await expect(service.listServers(principal)).rejects.toMatchObject({
+ code: 'authorization_unavailable',
+ })
+ expect(store.secretMetadataReads).toBe(1)
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it('discards inventory when the Context allowlist changes before the response', async () => {
+ const store = new FakeStore()
+ store.contextSequence = [
+ context,
+ { ...context, metadata: meta('context-uid-a', '21'), mcpServers: [] },
+ ]
+ const service = new McpAuthorizationService(store)
+
+ await expect(service.listServers(principal)).rejects.toMatchObject({
+ code: 'authorization_unavailable',
+ })
+ expect(store.secretMetadataReads).toBe(1)
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it('discards a credential when the Secret changes during the post-read fence', async () => {
+ const store = new FakeStore()
+ store.secretMetadataSequence = [secret, { ...secret, metadata: meta('secret-uid-a', '41') }]
+ const service = new McpAuthorizationService(store)
+ await expect(service.getCredential(principal, 'server-a')).rejects.toMatchObject({
+ code: 'authorization_unavailable',
+ })
+ expect(store.secretMetadataReads).toBe(2)
+ expect(store.secretValueReads).toBe(1)
+ })
+
+ it('rejects a credential when the Host is rebound during the post-read fence', async () => {
+ const store = new FakeStore()
+ store.hostSequence = [host, { ...host, metadata: meta('replacement-host-uid', '1') }]
+ const service = new McpAuthorizationService(store)
+
+ await expectCredentialFailure(service, 'unauthorized')
+ expect(store.secretMetadataReads).toBe(1)
+ expect(store.secretValueReads).toBe(1)
+ })
+
+ it('rejects a credential when the Context allowlist changes during the post-read fence', async () => {
+ const store = new FakeStore()
+ store.contextSequence = [context, { ...context, mcpServers: [] }]
+ const service = new McpAuthorizationService(store)
+
+ await expectCredentialFailure(service, 'not_found')
+ expect(store.secretMetadataReads).toBe(1)
+ expect(store.secretValueReads).toBe(1)
+ })
+
+ it('discards a credential when the McpServer changes during the post-read fence', async () => {
+ const store = new FakeStore()
+ store.serverSequence = [server, { ...server, metadata: meta('server-uid-a', '31') }]
+ const service = new McpAuthorizationService(store)
+ await expect(service.getCredential(principal, 'server-a')).rejects.toMatchObject({
+ code: 'authorization_unavailable',
+ })
+ expect(store.secretMetadataReads).toBe(2)
+ expect(store.secretValueReads).toBe(1)
+ })
+
+ it('fails closed when the McpServer disappears during the post-read fence', async () => {
+ const store = new FakeStore()
+ store.serverSequence = [server, null]
+ const service = new McpAuthorizationService(store)
+
+ await expect(service.getCredential(principal, 'server-a')).rejects.toMatchObject({
+ code: 'not_found',
+ })
+ expect(store.secretMetadataReads).toBe(1)
+ expect(store.secretValueReads).toBe(1)
+ })
+
+ it('discards a credential when the McpServer is recreated under the same name', async () => {
+ const store = new FakeStore()
+ store.serverSequence = [server, { ...server, metadata: meta('replacement-server-uid', '1') }]
+ const service = new McpAuthorizationService(store)
+
+ await expect(service.getCredential(principal, 'server-a')).rejects.toMatchObject({
+ code: 'authorization_unavailable',
+ })
+ expect(store.secretMetadataReads).toBe(2)
+ expect(store.secretValueReads).toBe(1)
+ })
+
+ it('fails closed when the Secret disappears during the post-read fence', async () => {
+ const store = new FakeStore()
+ store.secretMetadataSequence = [secret, null]
+ const service = new McpAuthorizationService(store)
+
+ await expect(service.getCredential(principal, 'server-a')).rejects.toMatchObject({
+ code: 'authorization_unavailable',
+ })
+ expect(store.secretMetadataReads).toBe(2)
+ expect(store.secretValueReads).toBe(1)
+ })
+
+ it('fails closed when the Context disappears during the post-read fence', async () => {
+ const store = new FakeStore()
+ store.contextSequence = [context, null]
+ const service = new McpAuthorizationService(store)
+ await expect(service.getCredential(principal, 'server-a')).rejects.toMatchObject({
+ code: 'not_found',
+ })
+ expect(store.secretMetadataReads).toBe(1)
+ expect(store.secretValueReads).toBe(1)
+ })
+
+ it('rejects an expired principal before any Kubernetes authority read', async () => {
+ const store = new FakeStore()
+ const service = new McpAuthorizationService(store, () => principal.expiresAt)
+ await expect(service.getCredential(principal, 'server-a')).rejects.toMatchObject({
+ code: 'unauthorized',
+ })
+ expect(store.secretMetadataReads).toBe(0)
+ expect(store.secretValueReads).toBe(0)
+ })
+ })
++
++describe('deriveAuthKind (mini-spec 10 §3.1)', () => {
++ it.each([
++ ['oauth + grantScope=user → oauth-user', { type: 'oauth' as const }, { grantScope: 'user' as const }, true, 'oauth-user'],
++ ['oauth + grantScope=context → oauth-context', { type: 'oauth' as const }, { grantScope: 'context' as const }, true, 'oauth-context'],
++ ['oauth + grantScope absent → oauth-user (CEL default)', { type: 'oauth' as const }, undefined, true, 'oauth-user'],
++ ['bearer (authRequired) → static', { type: 'bearer' as const }, undefined, true, 'static'],
++ ['apiKey (authRequired) → static', { type: 'apiKey' as const }, undefined, true, 'static'],
++ ['none → undefined (omitted)', { type: 'none' as const }, undefined, false, undefined],
++ ['absent auth → undefined', undefined, undefined, false, undefined],
++ ])('%s', (_label, auth, oauth, authRequired, expected) => {
++ expect(deriveAuthKind(auth as never, oauth as never, authRequired)).toBe(expected)
++ })
++
++ it('never collapses an oauth server to static across every grantScope', () => {
++ for (const grantScope of ['user', 'context', undefined] as const) {
++ const kind = deriveAuthKind(
++ { type: 'oauth' },
++ grantScope ? { grantScope } : undefined,
++ true
++ )
++ expect(kind).not.toBe('static')
++ expect(kind?.startsWith('oauth-')).toBe(true)
++ }
++ })
++
++ it('is idempotent: same inputs yield the same authKind', () => {
++ const a = deriveAuthKind({ type: 'oauth' }, { grantScope: 'context' }, true)
++ const b = deriveAuthKind({ type: 'oauth' }, { grantScope: 'context' }, true)
++ expect(a).toBe(b)
++ })
++})
++
++describe('listServers authKind emission (mini-spec 10 §3.2, T1)', () => {
++ it.each([
++ ['oauth-user', { type: 'oauth' as const }, fullOAuth('user'), 'oauth-user'],
++ ['oauth-context', { type: 'oauth' as const }, fullOAuth('context'), 'oauth-context'],
++ ['static (bearer)', { type: 'bearer' as const, secretRef: 'server-a-auth', secretKey: 'token' }, undefined, 'static'],
++ ])('emits authKind=%s derived from the real producer', async (_label, auth, oauth, expected) => {
++ const store = new FakeStore()
++ store.serverObject = {
++ ...server,
++ auth,
++ ...(oauth ? { oauth } : {}),
++ }
++ const service = new McpAuthorizationService(store)
++ const inventory = await service.listServers(principal)
++ expect(inventory[0].authKind).toBe(expected)
++ // I1: the wire projection never leaks context/auth identity.
++ expect(inventory[0]).not.toHaveProperty('contextRef')
++ expect(inventory[0]).not.toHaveProperty('auth')
++ expect(inventory[0]).not.toHaveProperty('oauth')
++ })
++
++ it('omits authKind entirely for a no-auth server', async () => {
++ const store = new FakeStore()
++ store.serverObject = { ...server, auth: { type: 'none' } }
++ const service = new McpAuthorizationService(store)
++ const inventory = await service.listServers(principal)
++ expect(inventory[0]).not.toHaveProperty('authKind')
++ })
++})
diff --cc host-context-controller/src/mcpAuthorization.ts
index 000000000,1d19d53d6..79378bacb
mode 000000,100644..100644
--- a/host-context-controller/src/mcpAuthorization.ts
+++ b/host-context-controller/src/mcpAuthorization.ts
@@@ -1,0 -1,371 +1,409 @@@
+ import { createHash } from 'node:crypto'
+ import type { VerifiedMcpHostPrincipal } from './mcpApiAuthentication'
-import type { McpServerAuth, McpServerStatus, McpServerTransport } from './types'
++import type {
++ McpServerAuth,
++ McpServerOAuth,
++ McpServerStatus,
++ McpServerTransport,
++} from './types'
+
+ export interface AuthorityMetadata {
+ uid: string
+ resourceVersion: string
+ deletionTimestamp?: string
+ }
+
+ export interface AuthorityHost {
+ name: string
+ namespace: string
+ metadata: AuthorityMetadata
+ contextRef: string
+ }
+
+ export interface AuthorityContext {
+ name: string
+ namespace: string
+ metadata: AuthorityMetadata
+ mcpServers: readonly string[]
+ }
+
+ export interface AuthorityMcpServer {
+ name: string
+ namespace: string
+ metadata: AuthorityMetadata
+ description?: string
+ transport: McpServerTransport
+ auth?: McpServerAuth
++ // OAuth broker config (grantScope) from the CRD. Non-secret; used only to
++ // derive the inventory `authKind`. HCC never forwards it to mcp-host raw.
++ oauth?: McpServerOAuth
+ enabled: boolean
+ status: McpServerStatus
+ }
+
+ export interface AuthoritySecretMetadata {
+ name: string
+ namespace: string
+ metadata: AuthorityMetadata
+ }
+
+ export interface AuthoritySecret extends AuthoritySecretMetadata {
+ data: Readonly<Record<string, string>>
+ }
+
+ export interface McpAuthorizationStore {
+ readHost(name: string): Promise<AuthorityHost | null>
+ readContext(name: string): Promise<AuthorityContext | null>
+ readMcpServer(name: string): Promise<AuthorityMcpServer | null>
+ readSecretMetadata(name: string): Promise<AuthoritySecretMetadata | null>
+ readSecret(name: string): Promise<AuthoritySecret | null>
+ }
+
+ export interface AuthorizedMcpServerInfo {
+ name: string
+ description?: string
+ transport: McpServerTransport
+ enabled: boolean
+ status: Pick<McpServerStatus, 'deployed' | 'ready'> &
+ Partial<Pick<McpServerStatus, 'authoritative'>>
+ authRequired: boolean
+ credentialRevision?: string
++ /**
++ * Non-secret credential-mode policy the mcp-host seam dispatches on
++ * (mini-spec 10 §3.2). Derived from the CRD auth selector; carries NO
++ * authority (no contextRef/secretRef/token). `none` is represented as an
++ * omitted field. Absent → mcp-host degrades to `static` (fail-closed).
++ */
++ authKind?: AuthorizedMcpAuthKind
++}
++
++export type AuthorizedMcpAuthKind = 'static' | 'oauth-user' | 'oauth-context'
++
++/**
++ * Derive the non-secret `authKind` policy for the inventory (mini-spec 10 §3.1).
++ * Pure: same inputs → same output; an oauth server never collapses to `static`.
++ * Returns undefined for the implicit `none` (no auth required) so the caller
++ * omits the field.
++ */
++export function deriveAuthKind(
++ auth: McpServerAuth | undefined,
++ // Only grantScope is read here; accepting the narrow shape documents the
++ // contract and lets callers pass a full McpServerOAuth (structurally wider).
++ oauth: Pick<McpServerOAuth, 'grantScope'> | undefined,
++ authRequired: boolean
++): AuthorizedMcpAuthKind | undefined {
++ if (auth?.type === 'oauth') {
++ return oauth?.grantScope === 'context' ? 'oauth-context' : 'oauth-user'
++ }
++ return authRequired ? 'static' : undefined
+ }
+
+ export interface AuthorizedCredential {
+ token: string | null
+ credentialRevision: string
+ }
+
+ /** Project only the transport keys that are part of the mcp-host wire contract. */
+ export function toPublicMcpTransport(transport: McpServerTransport): McpServerTransport {
+ return {
+ type: transport.type,
+ ...(typeof transport.url === 'string' ? { url: transport.url } : {}),
+ ...(Number.isSafeInteger(transport.port) &&
+ (transport.port ?? 0) > 0 &&
+ (transport.port ?? 0) <= 65_535
+ ? { port: transport.port }
+ : {}),
+ }
+ }
+
+ export type McpAuthorizationFailureCode =
+ | 'unauthorized'
+ | 'not_found'
+ | 'authorization_unavailable'
+ | 'credential_unavailable'
+
+ export class McpAuthorizationError extends Error {
+ constructor(readonly code: McpAuthorizationFailureCode) {
+ super(code)
+ this.name = 'McpAuthorizationError'
+ }
+ }
+
+ type AuthorizedHostContext = {
+ principal: VerifiedMcpHostPrincipal
+ host: AuthorityHost
+ context: AuthorityContext
+ }
+
+ type AuthorizedMcpServerGrant = AuthorizedHostContext & {
+ server: AuthorityMcpServer
+ secretMetadata: AuthoritySecretMetadata | null
+ credentialRevision: string
+ }
+
+ const FALLBACK_SECRET_KEYS = ['token', 'api-key', 'apiKey', 'password'] as const
+
+ function isLive(metadata: AuthorityMetadata): boolean {
+ return Boolean(metadata.uid && metadata.resourceVersion && !metadata.deletionTimestamp)
+ }
+
+ function selectSecretKey(secret: AuthoritySecret | null, configured?: string): string | null {
+ if (!secret) return null
+ const keys = configured ? [configured] : FALLBACK_SECRET_KEYS
+ return (
+ keys.find(key => Object.hasOwn(secret.data, key) && typeof secret.data[key] === 'string') ??
+ null
+ )
+ }
+
+ function decodeBase64Credential(value: unknown): string | null {
+ if (
+ typeof value !== 'string' ||
+ value.length === 0 ||
+ value.length % 4 !== 0 ||
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)
+ ) {
+ return null
+ }
+ const decoded = Buffer.from(value, 'base64')
+ if (decoded.length === 0 || decoded.toString('base64') !== value) return null
+ const token = decoded.toString('utf8')
+ return Buffer.from(token, 'utf8').equals(decoded) && token.length > 0 ? token : null
+ }
+
+ function revisionFor(server: AuthorityMcpServer, secret: AuthoritySecretMetadata | null): string {
+ const material = JSON.stringify({
+ serverUid: server.metadata.uid,
+ serverResourceVersion: server.metadata.resourceVersion,
+ serverDeleting: server.metadata.deletionTimestamp ?? null,
+ authType: server.auth?.type ?? 'none',
+ authSecretRef: server.auth?.secretRef ?? null,
+ authSecretKey: server.auth?.secretKey ?? null,
+ secretUid: secret?.metadata.uid ?? null,
+ secretResourceVersion: secret?.metadata.resourceVersion ?? null,
+ secretDeleting: secret?.metadata.deletionTimestamp ?? null,
+ })
+ return createHash('sha256').update(material).digest('base64url')
+ }
+
+ function sameHostContext(left: AuthorizedHostContext, right: AuthorizedHostContext): boolean {
+ return (
+ left.principal.subject === right.principal.subject &&
+ left.principal.hostName === right.principal.hostName &&
+ left.principal.hostUid === right.principal.hostUid &&
+ left.principal.jti === right.principal.jti &&
+ left.principal.issuedAt === right.principal.issuedAt &&
+ left.principal.expiresAt === right.principal.expiresAt &&
+ left.host.name === right.host.name &&
+ left.host.namespace === right.host.namespace &&
+ left.host.metadata.uid === right.host.metadata.uid &&
+ left.host.metadata.resourceVersion === right.host.metadata.resourceVersion &&
+ left.host.contextRef === right.host.contextRef &&
+ left.context.name === right.context.name &&
+ left.context.namespace === right.context.namespace &&
+ left.context.metadata.uid === right.context.metadata.uid &&
+ left.context.metadata.resourceVersion === right.context.metadata.resourceVersion &&
+ left.context.mcpServers.join('\u0000') === right.context.mcpServers.join('\u0000')
+ )
+ }
+
+ function sameGrant(left: AuthorizedMcpServerGrant, right: AuthorizedMcpServerGrant): boolean {
+ return (
+ sameHostContext(left, right) &&
+ left.server.metadata.uid === right.server.metadata.uid &&
+ left.server.metadata.resourceVersion === right.server.metadata.resourceVersion &&
+ left.credentialRevision === right.credentialRevision
+ )
+ }
+
+ export class McpAuthorizationService {
+ constructor(
+ private readonly store: McpAuthorizationStore,
+ private readonly nowEpochSeconds: () => number = () => Math.floor(Date.now() / 1000)
+ ) {}
+
+ private assertPrincipalLive(principal: VerifiedMcpHostPrincipal): void {
+ if (principal.expiresAt <= this.nowEpochSeconds()) {
+ throw new McpAuthorizationError('unauthorized')
+ }
+ }
+
+ private async resolveHostContext(
+ principal: VerifiedMcpHostPrincipal
+ ): Promise<AuthorizedHostContext> {
+ this.assertPrincipalLive(principal)
+ let host: AuthorityHost | null
+ let context: AuthorityContext | null
+ try {
+ host = await this.store.readHost(principal.hostName)
+ if (
+ !host ||
+ host.name !== principal.hostName ||
+ host.namespace !== principal.namespace ||
+ !isLive(host.metadata) ||
+ host.metadata.uid !== principal.hostUid ||
+ !host.contextRef
+ ) {
+ // A missing/recreated/deleting Host invalidates the authenticated
+ // principal itself. Surface 401 so mcp-host revokes the whole retained
+ // authority set instead of treating this as one missing MCP target.
+ throw new McpAuthorizationError('unauthorized')
+ }
+ context = await this.store.readContext(host.contextRef)
+ } catch (error) {
+ if (error instanceof McpAuthorizationError) throw error
+ throw new McpAuthorizationError('authorization_unavailable')
+ }
+ if (
+ !context ||
+ context.name !== host.contextRef ||
+ !context.namespace ||
+ !isLive(context.metadata)
+ ) {
+ throw new McpAuthorizationError('not_found')
+ }
+ return { principal, host, context }
+ }
+
+ private async resolveServerGrant(
+ binding: AuthorizedHostContext,
+ serverName: string
+ ): Promise<AuthorizedMcpServerGrant> {
+ if (!binding.context.mcpServers.includes(serverName)) {
+ throw new McpAuthorizationError('not_found')
+ }
+
+ let server: AuthorityMcpServer | null
+ try {
+ server = await this.store.readMcpServer(serverName)
+ } catch {
+ throw new McpAuthorizationError('authorization_unavailable')
+ }
+ if (
+ !server ||
+ server.name !== serverName ||
+ server.namespace !== binding.context.namespace ||
+ !server.enabled ||
+ !isLive(server.metadata)
+ ) {
+ throw new McpAuthorizationError('not_found')
+ }
+
+ const authRequired = Boolean(server.auth && server.auth.type !== 'none')
+ let secretMetadata: AuthoritySecretMetadata | null = null
+ if (authRequired && server.auth?.secretRef) {
+ try {
+ secretMetadata = await this.store.readSecretMetadata(server.auth.secretRef)
+ } catch {
+ throw new McpAuthorizationError('authorization_unavailable')
+ }
+ }
+ if (
+ secretMetadata &&
+ (secretMetadata.name !== server.auth?.secretRef ||
+ secretMetadata.namespace !== server.namespace ||
+ !isLive(secretMetadata.metadata))
+ ) {
+ secretMetadata = null
+ }
+ return {
+ ...binding,
+ server,
+ secretMetadata,
+ credentialRevision: revisionFor(server, secretMetadata),
+ }
+ }
+
+ async listServers(principal: VerifiedMcpHostPrincipal): Promise<AuthorizedMcpServerInfo[]> {
+ const binding = await this.resolveHostContext(principal)
+ const names = [...new Set(binding.context.mcpServers)]
+ const servers: AuthorizedMcpServerInfo[] = []
+ for (const name of names) {
+ let grant: AuthorizedMcpServerGrant
+ try {
+ grant = await this.resolveServerGrant(binding, name)
+ } catch (error) {
+ if (error instanceof McpAuthorizationError && error.code === 'not_found') continue
+ throw error
+ }
+ const authRequired = Boolean(grant.server.auth && grant.server.auth.type !== 'none')
++ const authKind = deriveAuthKind(grant.server.auth, grant.server.oauth, authRequired)
+ servers.push({
+ name: grant.server.name,
+ ...(grant.server.description ? { description: grant.server.description } : {}),
+ transport: toPublicMcpTransport(grant.server.transport),
+ enabled: grant.server.enabled,
+ status: {
+ deployed: grant.server.status.deployed,
+ ready: grant.server.status.ready,
+ ...(typeof grant.server.status.authoritative === 'boolean'
+ ? { authoritative: grant.server.status.authoritative }
+ : {}),
+ },
+ authRequired,
+ ...(authRequired ? { credentialRevision: grant.credentialRevision } : {}),
++ ...(authKind ? { authKind } : {}),
+ })
+ }
+ const revalidated = await this.resolveHostContext(principal)
+ if (!sameHostContext(binding, revalidated)) {
+ throw new McpAuthorizationError('authorization_unavailable')
+ }
+ return servers
+ }
+
+ async getCredential(
+ principal: VerifiedMcpHostPrincipal,
+ serverName: string
+ ): Promise<AuthorizedCredential> {
+ const binding = await this.resolveHostContext(principal)
+ const grant = await this.resolveServerGrant(binding, serverName)
+ const authRequired = Boolean(grant.server.auth && grant.server.auth.type !== 'none')
+ if (!authRequired) {
+ const revalidated = await this.resolveServerGrant(
+ await this.resolveHostContext(principal),
+ serverName
+ )
+ if (!sameGrant(grant, revalidated)) {
+ throw new McpAuthorizationError('authorization_unavailable')
+ }
+ this.assertPrincipalLive(principal)
+ return { token: null, credentialRevision: grant.credentialRevision }
+ }
+
+ if (!grant.server.auth?.secretRef || !grant.secretMetadata) {
+ throw new McpAuthorizationError('credential_unavailable')
+ }
+ let secret: AuthoritySecret | null
+ try {
+ secret = await this.store.readSecret(grant.server.auth.secretRef)
+ } catch {
+ throw new McpAuthorizationError('authorization_unavailable')
+ }
+ if (
+ !secret ||
+ secret.name !== grant.secretMetadata.name ||
+ secret.namespace !== grant.secretMetadata.namespace ||
+ !isLive(secret.metadata) ||
+ secret.metadata.uid !== grant.secretMetadata.metadata.uid ||
+ secret.metadata.resourceVersion !== grant.secretMetadata.metadata.resourceVersion ||
+ secret.metadata.deletionTimestamp !== grant.secretMetadata.metadata.deletionTimestamp
+ ) {
+ throw new McpAuthorizationError('authorization_unavailable')
+ }
+ const selectedSecretKey = selectSecretKey(secret, grant.server.auth.secretKey)
+ if (!selectedSecretKey) throw new McpAuthorizationError('credential_unavailable')
+ const token = decodeBase64Credential(secret.data[selectedSecretKey])
+ if (!token) throw new McpAuthorizationError('credential_unavailable')
+
+ const revalidated = await this.resolveServerGrant(
+ await this.resolveHostContext(principal),
+ serverName
+ )
+ if (!sameGrant(grant, revalidated)) {
+ throw new McpAuthorizationError('authorization_unavailable')
+ }
+ this.assertPrincipalLive(principal)
+ return { token, credentialRevision: grant.credentialRevision }
+ }
+ }
diff --cc host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts
index a12dda49e,9037ec36d..43a4a7299
--- a/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts
+++ b/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts
@@@ -5,7 -5,8 +5,8 @@@
*/
import { config } from './config'
import { hccLogger } from './logger'
+ import { McpApiAuthenticator } from './mcpApiAuthentication'
-import type { HostWorkflowControlScope } from './types'
+import type { HostRuntimeControlScope } from './types'
import { signInternalControlJwt } from './utils/internalControlSigner'
export interface McpHostRuntimeTokenResponse {
@@@ -40,8 -56,31 +56,31 @@@ function positiveInteger(value: unknown
*/
export async function issueMcpHostRuntimeTokens(
hostName: string,
+ hostUid: string,
- workflowControlScopes: HostWorkflowControlScope[] = []
+ workflowControlScopes: HostRuntimeControlScope[] = []
): Promise<McpHostRuntimeTokenResponse> {
+ if (
+ typeof hostName !== 'string' ||
+ !hostName ||
+ hostName.length > 63 ||
+ !HOST_NAME_RE.test(hostName)
+ ) {
+ throw new Error('mcpHost runtime token issuance requires a canonical Host name')
+ }
+ if (
+ typeof hostUid !== 'string' ||
+ !hostUid.trim() ||
+ hostUid.trim() !== hostUid ||
+ hostUid.length > 128 ||
+ /[^A-Za-z0-9._:-]/.test(hostUid)
+ ) {
+ throw new Error('mcpHost runtime token issuance requires a live Host UID')
+ }
+ if (config.hccTargetNamespace !== config.hostNamespace) {
+ throw new Error(
+ 'HCC_TARGET_NAMESPACE must equal CONTEXT_MAPPER_HOST_NAMESPACE for caller-bound Host credentials'
+ )
+ }
const recipeNamespace = config.hccTargetNamespace
const url = `${config.controlApiBaseUrl}/api/v1/auth/mcp-host/${encodeURIComponent(recipeNamespace)}/${encodeURIComponent(SENTINEL_RECIPE_NAME)}/tokens`
diff --cc host-context-controller/src/types.ts
index 834fde631,54914e551..1cc3e2065
--- a/host-context-controller/src/types.ts
+++ b/host-context-controller/src/types.ts
@@@ -428,21 -428,45 +428,60 @@@ export interface HostWorkflowControlSpe
scopes?: HostWorkflowControlScope[]
}
+/**
+ * Runtime control scopes minted into an mcp-host's control JWT. This is the
+ * DERIVED superset of the user-declarable {@link HostWorkflowControlScope}:
+ * HCC appends `oauth:user-token` for a Host runtime that fronts an enabled
+ * `auth.type: oauth` mcp-server, so the mcp-host can call control-api's OAuth
+ * user-token broker on that connection's behalf.
+ *
+ * `oauth:user-token` is HCC-derived and MUST NEVER be user-declarable: it is
+ * deliberately absent from {@link HostWorkflowControlScope} and from the Host
+ * CRD `spec.workflowControl.scopes` enum. HCC computes it per reconcile from
+ * the referenced Context's McpServer allow-list; nothing writes it back to the
+ * Host CR.
+ */
+export type HostRuntimeControlScope = HostWorkflowControlScope | 'oauth:user-token'
+
+ /**
+ * A single installed-hook reference inside Host.spec.guardrails.hooks[phase].
+ * `id` is the LlmHook CR name (llm-hooks namespace); `digest` is the expected
+ * image digest mcp-host binds against status.observedDigest (§8.2).
+ */
+ export interface HostGuardrailHookRef {
+ id: string
+ digest?: string
+ }
+
+ /**
+ * Host.spec.guardrails.hooks — installed LlmHook references grouped by
+ * lifecycle phase. Only the hook `id`s matter to HCC: they form the
+ * Host→LlmHook reverse index that drives the shared hook pod's NetworkPolicy
+ * ingress set (guardrails phase-4 design §5).
+ */
+ export interface HostGuardrailHooks {
+ preToolUse?: HostGuardrailHookRef[]
+ postToolUse?: HostGuardrailHookRef[]
+ preCall?: HostGuardrailHookRef[]
+ moderate?: HostGuardrailHookRef[]
+ postCallSuccess?: HostGuardrailHookRef[]
+ onError?: HostGuardrailHookRef[]
+ }
+
+ /**
+ * Host.spec.guardrails — additive, opt-in guardrail policy (guardrails spec
+ * §5). HCC only reads `hooks` (for the reverse index); the loosely-typed
+ * `rules`/`builtins`/ceiling fields are owned by mcp-host/control-api.
+ */
+ export interface HostGuardrailsSpec {
+ hooks?: HostGuardrailHooks
+ rules?: unknown[]
+ builtins?: unknown[]
+ minInstalledHookTrustLevel?: 'low' | 'mid' | 'high'
+ approvalPolicies?: string[]
+ capabilityCeiling?: string[]
+ }
+
export interface HostSpec {
host: string
contextRef: string
diff --cc host-context-controller/test/hostReconciler.test.ts
index cf71f679d,b8347b82e..59a918bdf
--- a/host-context-controller/test/hostReconciler.test.ts
+++ b/host-context-controller/test/hostReconciler.test.ts
@@@ -1941,106 -1942,3 +1944,106 @@@ describe('reconcileChannelReaderDeploym
expect(replaceBody.spec?.replicas).toBe(1)
})
})
+
+describe('HostReconciler oauth:user-token runtime scope provisioning', () => {
+ // Extract the runtime-token scope arg from the LAST issuer call, sorted for
+ // stable comparison. This is the REAL derive → issuance payload: the mock
+ // captures whatever `resolveWorkflowControlScopesForHost` (the production
+ // derive) actually produced — no hand-minted JWT.
+ function lastIssuedScopes(): string[] {
+ const calls = vi.mocked(issueMcpHostRuntimeTokens).mock.calls
+ const last = calls[calls.length - 1]
- return [...(last?.[1] ?? [])].sort()
++ return [...(last?.[2] ?? [])].sort()
+ }
+
+ // Access the private static scope-hash used for drift detection.
+ const scopeHashOf = (
+ HostReconciler as unknown as {
+ runtimeTokenScopeHash(
+ host: HostCRD,
+ hasChannelIngress?: boolean,
+ frontsOAuthServer?: boolean
+ ): string
+ }
+ ).runtimeTokenScopeHash
+
+ it('requests oauth:user-token through the real issuance payload when the Host fronts an enabled oauth mcp-server', async () => {
+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()
+ const { reconciler } = createReconciler()
+ // Host CRD carries NO oauth scope — the value is derive-only. HCC learns
+ // the Host fronts an oauth server exclusively from this injected probe.
+ reconciler.setHostFrontsOAuthServer(async () => true)
+
+ await reconciler.reconcile(makeHost())
+
+ // Goes through the REAL derive (resolveWorkflowControlScopesForHost →
+ // resolveRuntimeControlScopes). Without the derive change this scope is
+ // absent and the assertion fails.
+ expect(lastIssuedScopes()).toEqual(
+ [...DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES, OAUTH_USER_TOKEN_SCOPE].sort()
+ )
+ expect(lastIssuedScopes()).toContain('oauth:user-token')
+ })
+
+ it('does NOT request oauth:user-token when the Host fronts no oauth mcp-server', async () => {
+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()
+ const { reconciler } = createReconciler()
+ reconciler.setHostFrontsOAuthServer(async () => false)
+
+ await reconciler.reconcile(makeHost())
+
+ expect(lastIssuedScopes()).toEqual([...DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES].sort())
+ expect(lastIssuedScopes()).not.toContain('oauth:user-token')
+ })
+
+ it('defaults to NO oauth:user-token when the probe is unwired', async () => {
+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()
+ const { reconciler } = createReconciler()
+ // No setHostFrontsOAuthServer — production default is fail-closed false.
+
+ await reconciler.reconcile(makeHost())
+
+ expect(lastIssuedScopes()).not.toContain('oauth:user-token')
+ })
+
+ it('fails closed (no oauth:user-token) when the oauth-server probe throws', async () => {
+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()
+ const { reconciler } = createReconciler()
+ reconciler.setHostFrontsOAuthServer(async () => {
+ throw new Error('context read failed')
+ })
+
+ await reconciler.reconcile(makeHost())
+
+ expect(lastIssuedScopes()).toEqual([...DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES].sort())
+ expect(lastIssuedScopes()).not.toContain('oauth:user-token')
+ })
+
+ it('toggling oauth-server presence changes the runtime-token scope hash (drift re-issues)', () => {
+ const host = makeHost()
+ const withoutOAuth = scopeHashOf(host, true, false)
+ const withOAuth = scopeHashOf(host, true, true)
+ expect(withOAuth).not.toBe(withoutOAuth)
+ })
+
+ it('mint scope set matches the scope-hash input (no mint/hash divergence)', async () => {
+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()
+ const { reconciler } = createReconciler()
+ reconciler.setHostFrontsOAuthServer(async () => true)
+ const host = makeHost()
+
+ await reconciler.reconcile(host)
+
+ // The scopes minted into the token (issuer payload) must equal the exact
+ // set the drift hash is computed over — both flow through
+ // resolveRuntimeControlScopes, so a hash miss would re-issue forever.
+ const hashInput = [
+ ...resolveRuntimeControlScopes(host.spec.workflowControl, {
+ hasChannelIngress: true,
+ frontsOAuthServer: true,
+ }),
+ ].sort()
+ expect(lastIssuedScopes()).toEqual(hashInput)
+ expect(hashInput).toContain('oauth:user-token')
+ })
+})
diff --cc host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts
index 28b4e3acb,afc11f380..ba498c7e0
--- a/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts
+++ b/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts
@@@ -116,39 -166,17 +166,35 @@@ describe('mcpHostRuntimeTokenIssuerClie
expect(claims.jti).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)
})
+ it('serializes the derive-only oauth:user-token scope into the request body', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => canonicalIssueResponse(),
+ } as Response)
+ globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch
+
+ const issueMcpHostRuntimeTokens = await loadIssuer()
- await issueMcpHostRuntimeTokens('chatllm', ['workflow:read', 'oauth:user-token'])
++ await issueMcpHostRuntimeTokens('chatllm', 'host-uid', ['workflow:read', 'oauth:user-token'])
+
+ const [, init] = fetchMock.mock.calls[0]
+ // The scope must survive verbatim into the wire body control-api reads —
+ // proving the broker actually receives `oauth:user-token`.
+ expect((init as RequestInit).body).toBe(
- '{"includeMcpHostControlToken":true,"host":"chatllm","workflowControlScopes":["workflow:read","oauth:user-token"]}'
++ '{"includeMcpHostControlToken":true,"host":"chatllm","hostUid":"host-uid","workflowControlScopes":["workflow:read","oauth:user-token"]}'
+ )
+ })
+
- it('uses HCC_TARGET_NAMESPACE when building the issuance URL', async () => {
+ it('rejects a target namespace that differs from the live Host namespace', async () => {
vi.resetModules()
process.env.HCC_TARGET_NAMESPACE = 'first-party-hosts'
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: async () => canonicalIssueResponse(),
- } as Response) as unknown as typeof globalThis.fetch
+ const fetchMock = vi.fn()
+ globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch
const issueMcpHostRuntimeTokens = await loadIssuer()
- await issueMcpHostRuntimeTokens('chatllm')
-
- const [url] = (globalThis.fetch as unknown as ReturnType<typeof vi.fn>).mock.calls[0]
- expect(url).toBe(
- 'http://control-api.test:8090/api/v1/auth/mcp-host/first-party-hosts/standalone/tokens'
+ await expect(issueMcpHostRuntimeTokens('chatllm', 'host-uid')).rejects.toThrow(
+ /must equal CONTEXT_MAPPER_HOST_NAMESPACE/
)
+ expect(fetchMock).not.toHaveBeenCalled()
})
it('surfaces non-2xx responses with status code in the error message', async () => {
diff --cc mcp-host/src/__tests__/mcp/mcpManager.status.test.ts
index 000000000,592ed3ab4..e014a7e32
mode 000000,100644..100644
--- a/mcp-host/src/__tests__/mcp/mcpManager.status.test.ts
+++ b/mcp-host/src/__tests__/mcp/mcpManager.status.test.ts
@@@ -1,0 -1,89 +1,96 @@@
+ import { describe, expect, it, vi } from 'vitest'
-import { McpManager } from '../../mcp/manager'
++import { McpManager, SHARED_PRINCIPAL, serializeClientKey } from '../../mcp/manager'
+ import { ServerStatusTracker, classifyConnectError } from '../../mcp/serverStatus'
+
+ type ProbeClient = {
+ probeTools: ReturnType<typeof vi.fn>
+ }
+
+ function connectedManager(clients: Record<string, ProbeClient>): {
+ manager: McpManager
+ tracker: ServerStatusTracker
+ } {
+ const tracker = new ServerStatusTracker(() => new Date('2026-07-23T10:00:00.000Z'))
+ const manager = new McpManager(undefined, tracker)
+ const internalClients = (manager as unknown as { clients: Map<string, ProbeClient> }).clients
++ const byServer = (manager as unknown as { byServer: Map<string, Set<string>> }).byServer
+ for (const [name, client] of Object.entries(clients)) {
- internalClients.set(name, client)
++ // Register the SHARED representative exactly as a real connection does: the
++ // client is keyed by its serialized ClientKey and indexed under byServer, so
++ // refreshAllServerStatus finds it via representativeClient(name) (one probe
++ // per server, never once per per-user partition).
++ const key = serializeClientKey(name, SHARED_PRINCIPAL)
++ internalClients.set(key, client)
++ byServer.set(name, new Set([key]))
+ tracker.markConnecting(name)
+ tracker.markConnected(name, 1)
+ }
+ return { manager, tracker }
+ }
+
+ describe('McpManager status refresh', () => {
+ it('aggregates raw-probe metadata and forwards the round signal to every probe', async () => {
+ const first = {
+ probeTools: vi.fn().mockResolvedValue({ ok: true, toolCount: 2, outputSchemaCount: 1 }),
+ }
+ const second = {
+ probeTools: vi
+ .fn()
+ .mockResolvedValue({ ok: false, error: new Error('upstream unavailable') }),
+ }
+ const { manager, tracker } = connectedManager({ first, second })
+ const controller = new AbortController()
+
+ await expect(
+ manager.refreshAllServerStatus({ timeoutMs: 1234, signal: controller.signal })
+ ).resolves.toEqual({
+ serverCount: 2,
+ succeeded: 1,
+ failed: 1,
+ toolCount: 2,
+ outputSchemaCount: 1,
+ aborted: false,
+ })
+
+ const firstSignal = first.probeTools.mock.calls[0]?.[0].signal as AbortSignal
+ const secondSignal = second.probeTools.mock.calls[0]?.[0].signal as AbortSignal
+ expect(firstSignal).toBe(controller.signal)
+ expect(secondSignal).toBe(controller.signal)
+ expect(tracker.get('first')?.toolCount).toBe(2)
+ expect(tracker.get('second')?.reason).toBe('unknown')
+ })
+
+ it('does not invoke probes or mutate status for an already aborted round', async () => {
+ const client = { probeTools: vi.fn() }
+ const { manager, tracker } = connectedManager({ one: client })
+ const before = tracker.get('one')
+ const controller = new AbortController()
+ controller.abort('shutdown')
+
+ await expect(
+ manager.refreshAllServerStatus({ signal: controller.signal })
+ ).resolves.toMatchObject({
+ serverCount: 1,
+ aborted: true,
+ })
+ expect(client.probeTools).not.toHaveBeenCalled()
+ expect(tracker.get('one')).toEqual(before)
+ })
+ })
+
+ describe('MCP status error classification', () => {
+ it('classifies JSON-RPC timeout and Zod response-shape failures deterministically', () => {
+ expect(
+ classifyConnectError({ code: -32001, message: 'request exceeded deadline' })
+ ).toMatchObject({
+ reason: 'timeout',
+ })
+ expect(
+ classifyConnectError({
+ name: '$ZodError',
+ issues: [{ path: ['tools', 0], message: 'invalid' }],
+ message: 'response parse error',
+ })
+ ).toEqual({ reason: 'handshake', message: 'invalid MCP response schema' })
+ })
+ })
diff --cc mcp-host/src/contextMapperClient.test.ts
index 61c78e97c,5f1077044..6a8da3626
--- a/mcp-host/src/contextMapperClient.test.ts
+++ b/mcp-host/src/contextMapperClient.test.ts
@@@ -61,69 -264,28 +264,88 @@@ describe('ContextMapperClient Host-scop
)
)
)
- const client = new ContextMapperClient('http://context-mapper.test')
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: authentication(),
+ })
- await expect(client.listServersByContext('production')).resolves.toEqual([])
+ await expect(client.pollServers()).rejects.toThrow(
+ 'HCC inventory response contains forbidden authority metadata'
+ )
})
- it('does not convert a failed all-server request into an authoritative empty fleet', async () => {
- const networkError = new Error('connection reset')
- vi.stubGlobal('fetch', vi.fn().mockRejectedValue(networkError))
- const client = new ContextMapperClient('http://context-mapper.test')
++ it('preserves a valid authKind from the v2 inventory (mini-spec 10 §3.3)', async () => {
++ vi.stubGlobal(
++ 'fetch',
++ vi.fn().mockResolvedValue(
++ new Response(
++ JSON.stringify(inventory([authorizedServer({ authKind: 'oauth-user' })])),
++ { status: 200 }
++ )
++ )
++ )
++ const client = new ContextMapperClient('http://context-mapper.test', {
++ authentication: authentication(),
++ })
+
- await expect(client.listAllServers()).rejects.toBe(networkError)
++ const result = await client.pollServers()
++ expect(result.servers[0].authKind).toBe('oauth-user')
+ })
+
- it('does not convert an unavailable controller into an authoritative empty fleet', async () => {
- // The rejection case above never reaches the `!response.ok` branch, so a
- // 503 from an unready controller was uncovered: swapping that throw for
- // `return []` left the whole suite green while turning "I cannot tell you"
- // into an authoritative "there are none".
++ it('rejects an authKind value outside the enum', async () => {
+ vi.stubGlobal(
+ 'fetch',
- vi
- .fn()
- .mockResolvedValue(new Response('', { status: 503, statusText: 'Service Unavailable' }))
++ vi.fn().mockResolvedValue(
++ new Response(
++ JSON.stringify(inventory([authorizedServer({ authKind: 'oauth-admin' })])),
++ { status: 200 }
++ )
++ )
+ )
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.listAllServers()).rejects.toThrow(/503/)
- })
- })
++ const client = new ContextMapperClient('http://context-mapper.test', {
++ authentication: authentication(),
++ })
+
- describe('ContextMapperClient.pollServers', () => {
- afterEach(() => {
- vi.restoreAllMocks()
- vi.unstubAllGlobals()
++ await expect(client.pollServers()).rejects.toThrow(
++ 'HCC inventory response contains an invalid authKind'
++ )
+ })
+
- it('rejects an HTTP 503 instead of fabricating an authoritative empty fleet', async () => {
++ it('still rejects forbidden metadata even when a valid authKind is present (guard intact, I1)', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ new Response(
- JSON.stringify({
- error: 'Service Unavailable',
- message: 'Context mapper provider inventory is not authoritative',
- }),
- { status: 503, statusText: 'Service Unavailable' }
++ JSON.stringify(
++ inventory([
++ authorizedServer({ authKind: 'oauth-context', contextRef: 'foreign-context' }),
++ ])
++ ),
++ { status: 200 }
+ )
+ )
+ )
- const client = new ContextMapperClient('http://context-mapper.test')
++ const client = new ContextMapperClient('http://context-mapper.test', {
++ authentication: authentication(),
++ })
+
- await expect(client.pollServers('production')).rejects.toThrow('HTTP 503: Service Unavailable')
++ await expect(client.pollServers()).rejects.toThrow(
++ 'HCC inventory response contains forbidden authority metadata'
++ )
+ })
+
- it('rejects a network failure instead of fabricating an authoritative empty fleet', async () => {
- const networkError = new Error('connection reset')
- vi.stubGlobal('fetch', vi.fn().mockRejectedValue(networkError))
- const client = new ContextMapperClient('http://context-mapper.test')
+ it('accepts an authenticated HTTP 200 empty inventory as authoritative', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(new Response(JSON.stringify(inventory([])), { status: 200 }))
+ )
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: authentication(),
+ })
- await expect(client.pollServers('production')).rejects.toBe(networkError)
+ await expect(client.pollServers()).resolves.toEqual(inventory([]))
})
- it('bounds a silent HCC request so authoritative polling cannot stall indefinitely', async () => {
+ it('bounds a silent authenticated HCC request', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockImplementation((_url: string, init?: RequestInit) => {
diff --cc mcp-host/src/contextMapperClient.ts
index 6aeefb5d0,6374e33ca..f8280ed36
--- a/mcp-host/src/contextMapperClient.ts
+++ b/mcp-host/src/contextMapperClient.ts
@@@ -19,6 -18,155 +18,168 @@@ export interface AuthTokenResponse
}
const DEFAULT_CONTEXT_MAPPER_REQUEST_TIMEOUT_MS = 10_000
+ const MCP_SERVER_NAME_PATTERN = /^[a-z0-9](?:[-a-z0-9.]*[a-z0-9])?$/
+
+ export type ContextMapperRequestKind = 'inventory' | 'credential'
+
+ export class ContextMapperRequestError extends Error {
+ constructor(
+ readonly status: number,
+ readonly kind: ContextMapperRequestKind,
+ readonly authorizationFailure: boolean
+ ) {
+ super(
+ authorizationFailure
+ ? 'HCC caller authority was rejected'
+ : `HCC ${kind} request failed with status ${status}`
+ )
+ this.name = 'ContextMapperRequestError'
+ }
+ }
+
+ export class ContextMapperCredentialRevisionError extends Error {
+ constructor() {
+ super('HCC credential authority changed during retrieval')
+ this.name = 'ContextMapperCredentialRevisionError'
+ }
+ }
+
+ export function isContextMapperAuthorityRevocation(error: unknown): boolean {
+ return (
+ error instanceof ContextMapperCredentialRevisionError ||
+ (error instanceof ContextMapperRequestError &&
+ (error.authorizationFailure || (error.kind === 'credential' && error.status === 404)))
+ )
+ }
+
+ /**
+ * An inventory 404 means HCC could not resolve the authenticated Host's live
+ * Context authority. Unlike a credential 404 (which retires one target), this
+ * invalidates the complete locally-published MCP fleet.
+ */
+ export function isContextMapperInventoryAuthorityRevocation(error: unknown): boolean {
+ return (
+ error instanceof ContextMapperRequestError && error.kind === 'inventory' && error.status === 404
+ )
+ }
+
+ export interface ContextMapperAuthentication {
+ getAccessToken(): string
+ refreshOnUnauthorized(): Promise<void>
+ /** Required so every authenticated client has a synchronous revocation hook. */
+ onCallerAuthorizationFailure(status: 401 | 403): void
+ }
+
+ export interface ContextMapperClientOptions {
+ requestTimeoutMs?: number
+ authentication?: ContextMapperAuthentication
+ }
+
+ function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ }
+
+ function decodeMcpServer(value: unknown): McpServerInfo {
+ if (!isRecord(value)) throw new Error('HCC inventory response is malformed')
+ if ('contextRef' in value || 'auth' in value || 'secretRef' in value || 'secretKey' in value) {
+ throw new Error('HCC inventory response contains forbidden authority metadata')
+ }
+ if (typeof value.name !== 'string' || !MCP_SERVER_NAME_PATTERN.test(value.name)) {
+ throw new Error('HCC inventory response contains an invalid server selector')
+ }
+ if (!isRecord(value.transport)) throw new Error('HCC inventory response is malformed')
+ const transportType = value.transport.type
+ if (!['sse', 'streamableHttp', 'stdio'].includes(String(transportType))) {
+ throw new Error('HCC inventory response contains an invalid transport')
+ }
+ const transportUrl = value.transport.url
+ if (transportUrl !== undefined && typeof transportUrl !== 'string') {
+ throw new Error('HCC inventory response contains an invalid transport')
+ }
+ const transportPort = value.transport.port
+ if (
+ transportPort !== undefined &&
+ (!Number.isSafeInteger(transportPort) ||
+ (transportPort as number) < 1 ||
+ (transportPort as number) > 65_535)
+ ) {
+ throw new Error('HCC inventory response contains an invalid transport port')
+ }
+ if (typeof value.enabled !== 'boolean' || typeof value.authRequired !== 'boolean') {
+ throw new Error('HCC inventory response is malformed')
+ }
+ if (!isRecord(value.status)) throw new Error('HCC inventory response is malformed')
+ if (typeof value.status.deployed !== 'boolean' || typeof value.status.ready !== 'boolean') {
+ throw new Error('HCC inventory response is malformed')
+ }
+ if (
+ value.credentialRevision !== undefined &&
+ (typeof value.credentialRevision !== 'string' || !value.credentialRevision)
+ ) {
+ throw new Error('HCC inventory response contains an invalid credential revision')
+ }
+ if (value.authRequired && typeof value.credentialRevision !== 'string') {
+ throw new Error('HCC authenticated server is missing its credential revision')
+ }
++ // authKind is non-secret policy (mini-spec §3.3): an absent value degrades to
++ // `static` at dispatch (fail-closed); a present-but-unknown value is rejected,
++ // consistent with the strictness of the rest of the decoder. authKind is NOT
++ // on the forbidden-metadata denylist, so accepting it leaves that guard intact.
++ if (
++ value.authKind !== undefined &&
++ !['static', 'oauth-user', 'oauth-context'].includes(String(value.authKind))
++ ) {
++ throw new Error('HCC inventory response contains an invalid authKind')
++ }
+
+ return {
+ name: value.name,
+ ...(typeof value.description === 'string' ? { description: value.description } : {}),
+ transport: {
+ type: transportType as McpServerInfo['transport']['type'],
+ ...(typeof transportUrl === 'string' ? { url: transportUrl } : {}),
+ ...(typeof transportPort === 'number' ? { port: transportPort } : {}),
+ },
+ enabled: value.enabled,
+ authRequired: value.authRequired,
+ ...(typeof value.credentialRevision === 'string'
+ ? { credentialRevision: value.credentialRevision }
+ : {}),
++ ...(typeof value.authKind === 'string'
++ ? { authKind: value.authKind as McpServerInfo['authKind'] }
++ : {}),
+ status: {
+ deployed: value.status.deployed,
+ ready: value.status.ready,
+ ...(typeof value.status.authoritative === 'boolean'
+ ? { authoritative: value.status.authoritative }
+ : {}),
+ },
+ }
+ }
+
+ function decodeInventoryResponse(value: unknown): McpServersResponse {
+ if (!isRecord(value) || !Array.isArray(value.servers) || typeof value.timestamp !== 'string') {
+ throw new Error('HCC inventory response is malformed')
+ }
+ return { servers: value.servers.map(decodeMcpServer), timestamp: value.timestamp }
+ }
+
+ function decodeCredentialResponse(value: unknown): AuthTokenResponse {
+ if (!isRecord(value)) throw new Error('HCC credential response is malformed')
+ const keys = Object.keys(value).sort()
+ if (
+ keys.length !== 2 ||
+ keys[0] !== 'credentialRevision' ||
+ keys[1] !== 'token' ||
+ (value.token !== null && typeof value.token !== 'string') ||
+ typeof value.credentialRevision !== 'string' ||
+ !value.credentialRevision
+ ) {
+ throw new Error('HCC credential response is malformed')
+ }
+ return { token: value.token as string | null, credentialRevision: value.credentialRevision }
+ }
/**
* Context Mapper client.
diff --cc mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts
index 6f2416c87,961713588..6458aee6a
--- a/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts
+++ b/mcp-host/src/core/adapters/__tests__/toolRegistryAdapter.test.ts
@@@ -134,83 -134,53 +134,130 @@@ describe('McpToolRegistryAdapter', () =
})
})
+ // ─── Principal binding (PR #319 C2/H1) ──────────────────────────────────────
+ //
+ // The userId the adapter forwards to `manager.callTool` (which becomes the
+ // oauth grantScope='user' broker grant subject) MUST be the authenticated task
+ // sender baked into the adapter at construction (taskExecutor threads
+ // `task.sourceMessage.sender`), NEVER a value the model can choose. These lock
+ // that the principal is the constructor identity and cannot be spoofed by a
+ // tool argument named `userId`, and that two per-user adapters never cross.
+ describe('principal binding — broker userId is the authenticated sender, not a tool arg', () => {
+ function capturingManager(): {
+ manager: unknown
+ calls: Array<{ tool: string; params: Record<string, unknown>; options: unknown }>
+ } {
+ const calls: Array<{ tool: string; params: Record<string, unknown>; options: unknown }> = []
+ const manager = {
+ getAllTools: () => [
+ {
+ name: 'gh__do',
+ description: 'demo',
+ inputSchema: { type: 'object' },
+ serverName: 'gh',
+ },
+ ],
+ callTool: vi.fn(async (tool: string, params: Record<string, unknown>, options: unknown) => {
+ calls.push({ tool, params, options })
+ return {
+ toolName: tool,
+ result: { content: [{ type: 'text', text: 'ok' }] },
+ isError: false,
+ }
+ }),
+ }
+ return { manager, calls }
+ }
+
+ it('forwards the constructor userId as options.userId, ignoring a spoofed `userId` arg', async () => {
+ const { manager, calls } = capturingManager()
+ // Adapter built for the authenticated sender "alice".
+ const registry = new McpToolRegistryAdapter(manager as never, 'alice')
+ const tool = registry.get('gh__do')!
+
+ // The model supplies its own `userId` arg trying to impersonate "bob".
+ await tool.execute({ userId: 'bob', foo: 1 })
+
+ expect(calls).toHaveLength(1)
+ // The broker subject is the authenticated identity, never the arg.
+ expect(calls[0].options).toEqual({ userId: 'alice' })
+ // The arg is still forwarded verbatim as tool params (it is data, not identity).
+ expect(calls[0].params).toEqual({ userId: 'bob', foo: 1 })
+ })
+
+ it('two per-user adapters never forward each other’s userId', async () => {
+ const { manager, calls } = capturingManager()
+ const aliceTool = new McpToolRegistryAdapter(manager as never, 'alice').get('gh__do')!
+ const bobTool = new McpToolRegistryAdapter(manager as never, 'bob').get('gh__do')!
+
+ await aliceTool.execute({})
+ await bobTool.execute({})
+
+ expect(calls.map(c => (c.options as { userId?: string }).userId)).toEqual(['alice', 'bob'])
+ // Alice's identity is emitted exactly once, only from her own adapter.
+ expect(calls.filter(c => (c.options as { userId?: string }).userId === 'alice')).toHaveLength(
+ 1
+ )
+ })
+
+ it('an absent authenticated sender forwards userId=undefined (manager fails closed)', async () => {
+ const { manager, calls } = capturingManager()
+ // No sender on the task → no userId (never a body/arg fallback).
+ const tool = new McpToolRegistryAdapter(manager as never).get('gh__do')!
+
+ await tool.execute({ userId: 'anyone' })
+
+ expect(calls[0].options).toEqual({ userId: undefined })
+ })
+ })
+
+ // `sourceRef` is the tool-lane guardrail's `server` identity, so a `server=` deny
+ // rule matches on it. Slicing it off the display name at the first `__` truncates
+ // any server whose own name contains one — the rule then fails to match, and a
+ // deny that does not match lets the call through.
+ it('takes the MCP server identity from the registry, not the __-sliced name', () => {
+ const mockManager = {
+ getAllTools: () => [
+ {
+ name: 'acme__tools__run_query',
+ description: 'run a query',
+ inputSchema: { type: 'object' },
+ serverName: 'acme__tools',
+ },
+ ],
+ callTool: vi.fn(),
+ } as any
+
+ const registry = new McpToolRegistryAdapter(mockManager)
+ const tool = registry.get('acme__tools__run_query')
+
+ expect(tool!.traceDescriptor?.({}, undefined)).toEqual({
+ kind: 'mcp_server_tool',
+ sourceRef: 'acme__tools', // not 'acme'
+ })
+ })
+
+ it('falls back to the name prefix when the registry omits serverName', () => {
+ const mockManager = {
+ getAllTools: () => [
+ {
+ name: 'github__create_issue',
+ description: 'create an issue',
+ inputSchema: { type: 'object' },
+ },
+ ],
+ callTool: vi.fn(),
+ } as any
+
+ const registry = new McpToolRegistryAdapter(mockManager)
+ const tool = registry.get('github__create_issue')
+
+ expect(tool!.traceDescriptor?.({}, undefined)).toEqual({
+ kind: 'mcp_server_tool',
+ sourceRef: 'github',
+ })
+ })
+
it('uses a text summary when MCP content contains only images', async () => {
const mockManager = {
getAllTools: () => [
diff --cc mcp-host/src/core/adapters/toolRegistryAdapter.ts
index fb8eb25c9,f249a6f62..da0855279
--- a/mcp-host/src/core/adapters/toolRegistryAdapter.ts
+++ b/mcp-host/src/core/adapters/toolRegistryAdapter.ts
@@@ -79,7 -80,12 +80,13 @@@ class McpToolAdapter implements Tool
private readonly desc: string,
private readonly schema: Record<string, unknown>,
private readonly mcpManager: McpManager,
+ /**
+ * Authoritative server name from `McpTool.serverName` (set by the MCP client
+ * at connect). Carried explicitly because `traceDescriptor()` feeds the
+ * tool-lane guardrail identity that `server=` rules match on — see below.
+ */
- private readonly serverName: string
++ private readonly serverName: string,
+ private readonly userId?: string
) {}
name() {
@@@ -204,7 -200,7 +219,8 @@@ export class McpToolRegistryAdapter imp
mcpTool.description || '',
mcpTool.inputSchema || {},
this.mcpManager,
- serverNameOf(mcpTool)
++ serverNameOf(mcpTool),
+ this.userId
)
)
}
diff --cc mcp-host/src/main.ts
index 278538935,c549f166d..5ce8ac4ce
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@@ -80,7 -78,14 +84,15 @@@ import
replaceAuthoritativeMcpFleet,
runAuthoritativeMcpInitialization,
} from './mcp/authoritativeFleet'
+import { type BrokerTokenProviderDeps, createBrokerTokenProvider } from './mcp/brokerTokenProvider'
+ import {
+ createMcpAuthorityStalenessDeadline,
+ handleMcpAuthorityPollFailure,
+ isMcpAuthorityStale,
+ revokeMcpAuthorityState,
+ } from './mcp/authorityLifecycle'
+ import type { HandleMcpAuthorityPollFailureOptions } from './mcp/authorityLifecycle'
+ import { McpStatusHeartbeat } from './mcp/statusHeartbeat'
import { startMcpInitializationInBackground } from './mcpBackgroundInit'
import { IncomingMessageHandler, PendingTaskEntry } from './messageHandler'
import {
@@@ -175,9 -176,15 +187,20 @@@ let currentPolicy: LlmPolicy | null = n
let failoverEngine: FailoverEngine | null = null
let bootFallbackEntry: FallbackEntry | null = null
let hostWatcher: HostWatcher | null = null
+ let llmHookWatcher: LlmHookWatcher | null = null
let contextMapperPollTimer: ReturnType<typeof setInterval> | null = null
+ // Periodic guardrail re-resolve — a backstop for dropped LlmHook/Host watch
+ // events (the LlmHookWatcher is the primary, immediate path). Host edits also
+ // apply immediately via onHostChange.
+ let guardrailResolveTimer: ReturnType<typeof setInterval> | null = null
+ const GUARDRAIL_RESOLVE_INTERVAL_MS = 300_000
let contextMapperPollRunner: { trigger(): void; stop(): void } | null = null
- let mcpStatusHeartbeatTimer: ReturnType<typeof setInterval> | null = null
+ let mcpStatusHeartbeat: McpStatusHeartbeat | null = null
++// Sibling cadence to the status heartbeat: evicts idle oauth grantScope='user'
++// partitions (LRU + TTL, mini-spec §6). McpStatusHeartbeat owns one bounded probe
++// round and exposes no pre-tick hook, so eviction runs on its own timer rather
++// than being folded into a probe round.
++let mcpPartitionEvictionTimer: ReturnType<typeof setInterval> | null = null
let lastServerState: Map<string, string> = new Map()
let rpcServer: RPCServer | null = null
let mcpManager: McpManager | null = null
@@@ -788,102 -796,102 +812,198 @@@ export async function admitDevelopmentM
}
}
+/**
+ * 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).
++ * provider from the revision-locked getAuthToken route). The sabor is read from
++ * the HCC v2 inventory field `server.authKind` (mini-spec §3.2) — never from
++ * `auth.type`/`oauth.grantScope`/`contextRef`, which the v2 contract no longer
++ * emits:
+ *
- * - oauth grantScope='user', principal=userId → broker (server, userId)
- * - oauth grantScope='user', principal=SHARED → token-less representative
- * - oauth grantScope='context', principal=SHARED → broker (server, contextRef)
++ * - authKind='oauth-user', principal=userId → broker (server, {userId})
++ * - authKind='oauth-user', principal=SHARED → token-less representative
++ * - authKind='oauth-context', principal=any → broker (server, {}); control-api
++ * resolves the shared grant by server.spec.contextRef server-side, so mcp-host
++ * transports NO context identity (invariant I1).
++ * - anything else (static/none/absent) → token-less; manager owns static.
+ *
+ * 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()
- )
++ if (server.authKind === 'oauth-context') {
++ // Shared identity — one broker grant per (server, context). control-api
++ // keys it by server.spec.contextRef (authoritative) and cross-checks the
++ // body, so mcp-host omits the contextId entirely.
++ return createBrokerTokenProvider(server, {}, brokerTokenProviderDeps())
+ }
- // grantScope === 'user'
- if (principal.kind === 'user') {
- return createBrokerTokenProvider(
- server,
- { userId: principal.userId },
- brokerTokenProviderDeps()
- )
++ if (server.authKind === 'oauth-user') {
++ if (principal.kind === 'user') {
++ return createBrokerTokenProvider(
++ server,
++ { userId: principal.userId },
++ brokerTokenProviderDeps()
++ )
++ }
++ // SHARED principal on a per-user oauth server = catalog representative.
++ return staticTokenProvider(undefined)
+ }
- // SHARED principal on a user-scoped oauth server = catalog representative.
++ // static / none / absent authKind: static providers are built by the manager.
+ return staticTokenProvider(undefined)
+ }
+}
+
+/**
+ * Broker deps shared by every per-connection token provider: reads the gateway
+ * URL and mcp-host control JWT at call time (so token rotation is picked up).
+ * See mcp/brokerTokenProvider.ts for the fail-closed contract.
+ *
+ * The control JWT has a ~10 min TTL and is rotated in-pod by the workflow-auth
+ * self-refresh, which persists the rotated value to the runtime state file. The
+ * config value (env / mounted Secret file) is only the boot seed and is NOT
+ * rotated at that cadence, so reading it alone yields a 401 from the broker once
+ * the first token expires. Read the live persisted source on every call, exactly
+ * like core/tools/workflowTokenProvider.ts does for the workflow broker tools;
+ * loadPersistedWorkflowControlToken falls back to the config seed when the state
+ * file does not exist yet (early boot, dev mode) or fails its runtime-binding /
+ * freshness checks. An empty result normalizes to undefined so the broker keeps
+ * failing closed instead of sending `Bearer `.
+ */
+export function brokerTokenProviderDeps(): BrokerTokenProviderDeps {
+ return {
+ gatewayUrl: () => config.mcpHostGatewayUrl,
+ controlToken: () => {
+ // No seed at all => fail closed. Calling loadPersistedWorkflowControlToken
+ // with '' reaches its "no fallback binding to compare against" branch,
+ // where ANY persisted token with well-formed binding claims is accepted
+ // without being cross-checked against the pod's mounted identity. The seed
+ // is what makes that cross-check possible, so without it there is nothing
+ // to validate the state file against and the broker must send nothing.
+ const seed = workflowControlTokenFromConfig()?.trim()
+ if (!seed) return undefined
+ return loadPersistedWorkflowControlToken(seed) || undefined
+ },
+ // Reactive recovery on a control-api 401, same as every sibling consumer
+ // (setupUsageReporting wires `refreshOnUnauthorized: () => refreshWithRecovery(auth)`
+ // into UsageReporter / GovernedRunReporter / ApprovalPromptHistoryClient).
+ // Reading `runtimeAuth` at call time — not capturing it — matters: the broker
+ // factory is built during MCP init, which can run before setupUsageReporting
+ // assigns it. Without the shared auth there is nothing to refresh, and the
+ // broker keeps its previous behaviour of throwing on 401.
+ refreshControlToken: async () => {
+ const auth = runtimeAuth
+ if (!auth) return
+ await refreshWithRecovery(auth)
+ },
+ }
+}
+
- async function initializeMcpServers(contextRef: string): Promise<void> {
- console.log(`[Main] Initializing MCP servers for context: ${contextRef}`)
+ function ensureAuthenticatedContextMapperClient(): ContextMapperClient {
+ if (contextMapperClient) return contextMapperClient
+ if (!runtimeAuth) runtimeAuth = createMcpHostRuntimeAuth()
+ if (!runtimeAuth) {
+ throw new Error('MCP Host runtime authentication is required for HCC inventory')
+ }
+ const auth = runtimeAuth
+ contextMapperClient = getContextMapperClient({
+ getAccessToken: () => auth.accessToken,
+ refreshOnUnauthorized: () => refreshWithRecovery(auth),
+ onCallerAuthorizationFailure: status => revokeMcpAuthority(`caller_${status}`, true),
+ })
+ return contextMapperClient
+ }
+
+ export { createMcpAuthorityStalenessDeadline, isMcpAuthorityStale }
+
+ type McpAuthorityPollFailureCallbacks = Pick<
+ HandleMcpAuthorityPollFailureOptions,
+ 'revoke' | 'onCallerAuthorizationRejected' | 'onInventoryAuthorityRevoked' | 'onUnavailable'
+ >
+
+ /**
+ * Build the fail-closed polling options from the live main-process state.
+ * Keeping this adapter explicit gives the wiring a small, deterministic test
+ * seam instead of leaving the staleness/revocation callbacks as an untested
+ * inline object inside the timer callback.
+ */
+ export function createMcpAuthorityPollFailureOptions(
+ dependencies: McpAuthorityPollFailureCallbacks & {
+ getManager: () => unknown | null
+ lastSuccessAt: () => number
+ now?: () => number
+ }
+ ): HandleMcpAuthorityPollFailureOptions {
+ return {
+ hasPublishedManager: () => dependencies.getManager() !== null,
+ lastSuccessAt: dependencies.lastSuccessAt,
+ now: dependencies.now ?? Date.now,
+ maxStalenessMs: config.hccAuthorityMaxStalenessMs,
+ revoke: dependencies.revoke,
+ onCallerAuthorizationRejected: dependencies.onCallerAuthorizationRejected,
+ onInventoryAuthorityRevoked: dependencies.onInventoryAuthorityRevoked,
+ onUnavailable: dependencies.onUnavailable,
+ }
+ }
+
+ const mcpAuthorityStalenessDeadline = createMcpAuthorityStalenessDeadline(
+ config.hccAuthorityMaxStalenessMs,
+ () => {
+ if (!isShuttingDown && !config.devMode && mcpManager) {
+ revokeMcpAuthority('authority_stale_deadline', true)
+ }
+ }
+ )
+
+ function recordMcpAuthoritySuccess(successAt: number = Date.now()): void {
+ mcpAuthorityLastSuccessAt = successAt
+ if (!config.devMode) mcpAuthorityStalenessDeadline.recordSuccess(successAt)
+ }
+
+ /**
+ * Revoke the complete locally-published MCP authority before awaiting any
+ * transport cleanup. A fresh poller may recover later with a newly verified
+ * Host JWT and live Host -> Context grant snapshot.
+ */
+ function revokeMcpAuthority(reason: string, restartPolling: boolean): void {
+ revokeMcpAuthorityState({
+ reason,
+ restartPolling,
+ invalidateInitialization: () => {
+ mcpInitializationGeneration += 1
+ },
+ stopPolling: stopContextMapperPolling,
+ clearStalenessDeadline: () => mcpAuthorityStalenessDeadline.clear(),
+ withdrawManager: () => {
+ const closingManager = mcpManager
+ mcpManager = null
+ return closingManager
+ },
+ clearServerState: () => {
+ lastServerState = new Map()
+ },
+ clearLastSuccess: () => {
+ mcpAuthorityLastSuccessAt = 0
+ },
+ coordinator: mcpFleetCoordinator,
+ onCleanupFailure: () => console.error(`[Main] MCP authority cleanup failed (reason=${reason})`),
+ onRevoked: () => console.warn(`[Main] MCP authority revoked (reason=${reason})`),
+ shouldRestartPolling: () => !isShuttingDown && !config.devMode,
+ startPolling: startContextMapperPolling,
+ })
+ }
+
+ async function initializeMcpServers(): Promise<void> {
+ console.log('[Main] Initializing authenticated MCP server inventory')
const initializationGeneration = ++mcpInitializationGeneration
const isInitializationCurrent = (): boolean =>
!isShuttingDown && mcpInitializationGeneration === initializationGeneration
@@@ -893,17 -901,9 +1013,14 @@@
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')
- }
- return contextMapperClient.getAuthToken(serverName)
+ getAuthToken: async (serverName, expectedRevision) => {
+ return ensureAuthenticatedContextMapperClient().getAuthToken(serverName, expectedRevision)
},
installFleet: (nextManager, nextServerState) => {
mcpManager = nextManager
@@@ -1078,36 -1092,29 +1209,49 @@@ export function stopContextMapperPollin
* the connection (spec §4.5, §7.1).
*/
function startMcpStatusHeartbeat(): void {
- if (mcpStatusHeartbeatTimer) return
+ if (mcpStatusHeartbeat) return
const interval = config.mcpStatusHeartbeatInterval
- console.log(`[Main] Starting MCP status heartbeat (interval: ${interval}ms)`)
- mcpStatusHeartbeatTimer = setInterval(() => {
+ const timeoutMs = config.mcpStatusHeartbeatTimeoutMs
+ console.log(
+ `[Main] Starting MCP status heartbeat (interval: ${interval}ms, timeout: ${timeoutMs}ms)`
+ )
+ mcpStatusHeartbeat = new McpStatusHeartbeat({
+ intervalMs: interval,
+ timeoutMs,
+ getRefresher: () => mcpManager,
+ onError: (err: unknown) => {
+ console.error('[Main] MCP status heartbeat failed:', err)
+ },
+ })
+ mcpStatusHeartbeat.start()
++ // Evict idle oauth grantScope='user' partitions on the heartbeat's cadence.
++ // SHARED/static/representative partitions are exempt (manager.evictIdleUserPartitions).
++ mcpPartitionEvictionTimer = 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)
- })
+ }, interval)
}
function stopMcpStatusHeartbeat(): void {
- if (mcpStatusHeartbeatTimer) {
+ if (mcpStatusHeartbeat) {
console.log('[Main] Stopping MCP status heartbeat')
- clearInterval(mcpStatusHeartbeatTimer)
- mcpStatusHeartbeatTimer = null
+ mcpStatusHeartbeat.stop()
+ mcpStatusHeartbeat = null
+ }
++ if (mcpPartitionEvictionTimer) {
++ clearInterval(mcpPartitionEvictionTimer)
++ mcpPartitionEvictionTimer = null
+ }
}
/**
diff --cc mcp-host/src/mcp/__tests__/authorityLifecycle.test.ts
index 000000000,9ed78b8a5..30d2a525f
mode 000000,100644..100644
--- a/mcp-host/src/mcp/__tests__/authorityLifecycle.test.ts
+++ b/mcp-host/src/mcp/__tests__/authorityLifecycle.test.ts
@@@ -1,0 -1,362 +1,372 @@@
+ import { afterEach, describe, expect, it, vi } from 'vitest'
+ import { ContextMapperClient, ContextMapperRequestError } from '../../contextMapperClient'
+ import type { McpServerInfo } from '../../types'
+ import { AuthoritativeMcpFleetCoordinator } from '../authoritativeFleet'
+ import {
+ createMcpAuthorityStalenessDeadline,
+ handleMcpAuthorityPollFailure,
+ revokeMcpAuthorityState,
+ } from '../authorityLifecycle'
+ import { McpClient } from '../client'
-import { McpManager } from '../manager'
++import { McpManager, SHARED_PRINCIPAL, serializeClientKey } from '../manager'
+
+ const securedServer: McpServerInfo = {
+ name: 'secured-server',
+ transport: { type: 'streamableHttp', url: 'http://secured-server.test/mcp' },
+ enabled: true,
+ authRequired: true,
+ credentialRevision: 'credential-revision-1',
+ status: { deployed: true, ready: true, authoritative: true },
+ }
+
+ function deferred(): { promise: Promise<void>; resolve(): void } {
+ let resolve!: () => void
+ const promise = new Promise<void>(resolvePromise => {
+ resolve = resolvePromise
+ })
+ return { promise, resolve }
+ }
+
+ function retainedClient(
+ manager: McpManager,
+ serverName = securedServer.name
+ ): McpClient | undefined {
+ return (
+ manager as unknown as {
+ clients: Map<string, McpClient>
+ }
- ).clients.get(serverName)
++ ).clients.get(serializeClientKey(serverName, SHARED_PRINCIPAL))
+ }
+
+ function pendingClient(
+ manager: McpManager,
+ serverName = securedServer.name
+ ): McpClient | undefined {
+ return (
+ manager as unknown as {
+ pendingAdmissions: Map<string, { client: McpClient }>
+ }
- ).pendingAdmissions.get(serverName)?.client
++ ).pendingAdmissions.get(serializeClientKey(serverName, SHARED_PRINCIPAL))?.client
+ }
+
+ function createLifecycleHarness(
+ manager: McpManager,
+ coordinator = new AuthoritativeMcpFleetCoordinator(1, 1, true)
+ ) {
+ let currentManager: McpManager | null = manager
+ let serverState = new Map([[securedServer.name, 'credential-revision-1']])
+ let lastSuccessAt = 10_000
+ let generation = 7
+ let pollerRunning = true
+ let clearDeadline: () => void = () => undefined
+ const effects: string[] = []
+ const reasons: string[] = []
+
+ const originalCloseManager = coordinator.closeManager.bind(coordinator)
+ vi.spyOn(coordinator, 'closeManager').mockImplementation(closingManager => {
+ effects.push('coordinator-close')
+ originalCloseManager(closingManager)
+ })
+ const originalScheduleCleanup = coordinator.scheduleCleanup.bind(coordinator)
+ vi.spyOn(coordinator, 'scheduleCleanup').mockImplementation(cleanup => {
+ effects.push('cleanup-scheduled')
+ originalScheduleCleanup(cleanup)
+ })
+ const originalManagerClose = manager.close.bind(manager)
+ vi.spyOn(manager, 'close').mockImplementation(scheduleCleanup => {
+ effects.push('manager-close')
+ return originalManagerClose(scheduleCleanup)
+ })
+
+ const revoke = (reason: string, restartPolling: boolean): void => {
+ reasons.push(reason)
+ revokeMcpAuthorityState({
+ reason,
+ restartPolling,
+ invalidateInitialization: () => {
+ effects.push('generation-invalidated')
+ generation += 1
+ },
+ stopPolling: () => {
+ effects.push('polling-stopped')
+ pollerRunning = false
+ },
+ clearStalenessDeadline: () => {
+ effects.push('deadline-cleared')
+ clearDeadline()
+ },
+ withdrawManager: () => {
+ effects.push('manager-withdrawn')
+ const closingManager = currentManager
+ currentManager = null
+ return closingManager
+ },
+ clearServerState: () => {
+ effects.push('server-state-cleared')
+ serverState = new Map()
+ },
+ clearLastSuccess: () => {
+ effects.push('last-success-cleared')
+ lastSuccessAt = 0
+ },
+ coordinator,
+ onCleanupFailure: () => effects.push('cleanup-failed'),
+ onRevoked: () => effects.push('revoked'),
+ shouldRestartPolling: () => true,
+ startPolling: () => {
+ effects.push('polling-started')
+ pollerRunning = true
+ },
+ })
+ }
+
+ return {
+ coordinator,
+ effects,
+ reasons,
+ revoke,
+ setDeadlineClear: (clear: () => void) => {
+ clearDeadline = clear
+ },
+ state: () => ({
+ currentManager,
+ serverState,
+ lastSuccessAt,
+ generation,
+ pollerRunning,
+ }),
+ }
+ }
+
+ async function captureError(effect: () => Promise<unknown>): Promise<unknown> {
+ try {
+ await effect()
+ } catch (error) {
+ return error
+ }
+ throw new Error('Expected operation to reject')
+ }
+
+ describe('MCP authority lifecycle', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+ })
+
+ it.each([
+ { status: 401 as const, expectedFetches: 2, expectedRefreshes: 1 },
+ { status: 403 as const, expectedFetches: 1, expectedRefreshes: 0 },
+ ])(
+ 'withdraws the live fleet synchronously and restarts polling after persistent $status',
+ async ({ status, expectedFetches, expectedRefreshes }) => {
+ vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async function (this: McpClient) {
++ // Mimic the real connect's JIT token resolution so the post-revoke wipe
++ // assertion below exercises currentAuthToken.
++ ;(this as unknown as { currentAuthToken?: string }).currentAuthToken = await (
++ this as unknown as { tokenProvider?: { resolve(): Promise<string | undefined> } }
++ ).tokenProvider?.resolve()
+ ;(this as unknown as { connected: boolean }).connected = true
+ })
+ const manager = new McpManager()
+ await manager.addServer(securedServer, 'sensitive-upstream-bearer')
+ const installedClient = retainedClient(manager)
+ expect(installedClient).toBeDefined()
+
+ const harness = createLifecycleHarness(manager)
+ harness.coordinator.publishSnapshot(manager, [securedServer])
+ const refresh = vi.fn().mockResolvedValue(undefined)
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status }))
+ vi.stubGlobal('fetch', fetchMock)
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: {
+ getAccessToken: () => 'host-access-token',
+ refreshOnUnauthorized: refresh,
+ onCallerAuthorizationFailure: rejectedStatus =>
+ harness.revoke(`caller_${rejectedStatus}`, true),
+ },
+ })
+
+ const error = await captureError(() => client.pollServers())
+ expect(error).toBeInstanceOf(ContextMapperRequestError)
+ const disposition = handleMcpAuthorityPollFailure(error, {
+ hasPublishedManager: () => harness.state().currentManager !== null,
+ lastSuccessAt: () => harness.state().lastSuccessAt,
+ now: () => 70_000,
+ maxStalenessMs: 60_000,
+ revoke: harness.revoke,
+ onCallerAuthorizationRejected: vi.fn(),
+ onInventoryAuthorityRevoked: vi.fn(),
+ onUnavailable: vi.fn(),
+ })
+
+ expect(disposition).toBe('caller_authorization_rejected')
+ expect(fetchMock).toHaveBeenCalledTimes(expectedFetches)
+ expect(refresh).toHaveBeenCalledTimes(expectedRefreshes)
+ expect(harness.reasons).toEqual([`caller_${status}`])
+ expect(harness.state()).toMatchObject({
+ currentManager: null,
+ lastSuccessAt: 0,
+ generation: 8,
+ pollerRunning: true,
+ })
+ expect(harness.state().serverState.size).toBe(0)
- expect((installedClient as unknown as { authToken?: string }).authToken).toBeUndefined()
++ expect((installedClient as unknown as { currentAuthToken?: string }).currentAuthToken).toBeUndefined()
+ expect(manager.getConnectedServers()).toEqual([])
+ expect(manager.getKnownServers()).toEqual([])
+ expect(harness.effects).toEqual([
+ 'generation-invalidated',
+ 'polling-stopped',
+ 'deadline-cleared',
+ 'manager-withdrawn',
+ 'server-state-cleared',
+ 'last-success-cleared',
+ 'coordinator-close',
+ 'manager-close',
+ 'cleanup-scheduled',
+ 'revoked',
+ 'polling-started',
+ ])
+ await expect(manager.addServer(securedServer, 'new-bearer')).resolves.toBe('stale')
+ await harness.coordinator.drainCleanups()
+ }
+ )
+
+ it('classifies an actual inventory 404 as complete authority revocation', async () => {
+ const manager = new McpManager()
+ const harness = createLifecycleHarness(manager)
+ harness.coordinator.publishSnapshot(manager, [securedServer])
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 404 })))
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: {
+ getAccessToken: () => 'host-access-token',
+ refreshOnUnauthorized: vi.fn(),
+ onCallerAuthorizationFailure: vi.fn(),
+ },
+ })
+ const error = await captureError(() => client.pollServers())
+ const inventoryRevoked = vi.fn()
+
+ const disposition = handleMcpAuthorityPollFailure(error, {
+ hasPublishedManager: () => harness.state().currentManager !== null,
+ lastSuccessAt: () => harness.state().lastSuccessAt,
+ now: () => 70_000,
+ maxStalenessMs: 60_000,
+ revoke: harness.revoke,
+ onCallerAuthorizationRejected: vi.fn(),
+ onInventoryAuthorityRevoked: inventoryRevoked,
+ onUnavailable: vi.fn(),
+ })
+
+ expect(disposition).toBe('inventory_not_found')
+ expect(inventoryRevoked).toHaveBeenCalledTimes(1)
+ expect(harness.reasons).toEqual(['inventory_not_found'])
+ expect(harness.state()).toMatchObject({ currentManager: null, pollerRunning: true })
+ await harness.coordinator.drainCleanups()
+ })
+
+ it('revokes the full state at the absolute staleness deadline and restarts recovery polling', () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-08-20T00:00:00.000Z'))
+ const manager = new McpManager()
+ const harness = createLifecycleHarness(manager)
+ harness.coordinator.publishSnapshot(manager, [securedServer])
+ const deadline = createMcpAuthorityStalenessDeadline(60_000, () =>
+ harness.revoke('authority_stale_deadline', true)
+ )
+ harness.setDeadlineClear(deadline.clear)
+
+ deadline.recordSuccess()
+ vi.advanceTimersByTime(60_000)
+
+ expect(harness.reasons).toEqual(['authority_stale_deadline'])
+ expect(harness.state()).toMatchObject({
+ currentManager: null,
+ lastSuccessAt: 0,
+ generation: 8,
+ pollerRunning: true,
+ })
+ expect(harness.state().serverState.size).toBe(0)
+ })
+
+ it('revokes an unavailable stale fleet through the poll-error path', async () => {
+ const manager = new McpManager()
+ const harness = createLifecycleHarness(manager)
+ harness.coordinator.publishSnapshot(manager, [securedServer])
+ const unavailable = vi.fn()
+
+ const disposition = handleMcpAuthorityPollFailure(new Error('transport unavailable'), {
+ hasPublishedManager: () => harness.state().currentManager !== null,
+ lastSuccessAt: () => harness.state().lastSuccessAt,
+ now: () => 70_000,
+ maxStalenessMs: 60_000,
+ revoke: harness.revoke,
+ onCallerAuthorizationRejected: vi.fn(),
+ onInventoryAuthorityRevoked: vi.fn(),
+ onUnavailable: unavailable,
+ })
+
+ expect(disposition).toBe('authority_stale')
+ expect(unavailable).toHaveBeenCalledTimes(1)
+ expect(harness.reasons).toEqual(['authority_stale'])
+ expect(harness.state()).toMatchObject({ currentManager: null, pollerRunning: true })
+ await harness.coordinator.drainCleanups()
+ })
+
+ it('fences a delayed admission so revocation cannot republish its bearer or tools', async () => {
+ const connectStarted = deferred()
+ const releaseConnect = deferred()
+ vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async function (this: McpClient) {
++ // Mimic the real connect's JIT token resolution before the transport pause
++ // so the fencing assertions (bearer held, then wiped) observe it.
++ ;(this as unknown as { currentAuthToken?: string }).currentAuthToken = await (
++ this as unknown as { tokenProvider?: { resolve(): Promise<string | undefined> } }
++ ).tokenProvider?.resolve()
+ connectStarted.resolve()
+ await releaseConnect.promise
+ if ((this as unknown as { retired: boolean }).retired) {
+ throw new Error('MCP client is closed')
+ }
+ ;(this as unknown as { connected: boolean }).connected = true
+ })
+ const manager = new McpManager()
+ const coordinator = new AuthoritativeMcpFleetCoordinator(1, 1, true)
+ const lease = coordinator.publishSnapshot(manager, [securedServer])
+ const harness = createLifecycleHarness(manager, coordinator)
+ const committed = vi.fn()
+ let outcome: string | undefined
+ const admission = coordinator.runAdmission(
+ manager,
+ securedServer.name,
+ lease,
+ async isCurrent => {
+ outcome = await manager.addServer(securedServer, 'late-sensitive-bearer', {
+ isCurrent,
+ onCommit: committed,
+ scheduleCleanup: cleanup => coordinator.scheduleCleanup(cleanup),
+ })
+ }
+ )
+
+ await connectStarted.promise
+ const candidate = pendingClient(manager)
+ expect(candidate).toBeDefined()
- expect((candidate as unknown as { authToken?: string }).authToken).toBe('late-sensitive-bearer')
++ expect((candidate as unknown as { currentAuthToken?: string }).currentAuthToken).toBe('late-sensitive-bearer')
+
+ harness.revoke('caller_403', true)
+
+ expect(harness.state().currentManager).toBeNull()
- expect((candidate as unknown as { authToken?: string }).authToken).toBeUndefined()
++ expect((candidate as unknown as { currentAuthToken?: string }).currentAuthToken).toBeUndefined()
+ expect(manager.getConnectedServers()).toEqual([])
+ expect(manager.getKnownServers()).toEqual([])
+ releaseConnect.resolve()
+ await admission
+ await coordinator.drainCleanups()
+
+ expect(outcome).toBe('stale')
+ expect(committed).not.toHaveBeenCalled()
+ expect(manager.getAllTools()).toEqual([])
+ expect(manager.getConnectedServers()).toEqual([])
+ expect(harness.state().currentManager).toBeNull()
+ })
+ })
diff --cc mcp-host/src/mcp/__tests__/authorizationRevocation.test.ts
index 000000000,77e52e830..39c526a8b
mode 000000,100644..100644
--- a/mcp-host/src/mcp/__tests__/authorizationRevocation.test.ts
+++ b/mcp-host/src/mcp/__tests__/authorizationRevocation.test.ts
@@@ -1,0 -1,23 +1,31 @@@
+ import { describe, expect, it } from 'vitest'
+ import type { McpServerInfo } from '../../types'
-import { McpClient } from '../client'
++import { McpClient, staticTokenProvider } from '../client'
+
+ const server: McpServerInfo = {
+ name: 'scoped-server',
+ transport: { type: 'streamableHttp', url: 'http://scoped-server.test/mcp' },
+ enabled: true,
+ authRequired: true,
+ credentialRevision: 'credential-revision-1',
+ status: { deployed: true, ready: true },
+ }
+
+ describe('MCP credential revocation', () => {
+ it('wipes the retained bearer synchronously when a client is retired', async () => {
- const client = new McpClient(server, 'sensitive-upstream-bearer')
++ const client = new McpClient(server, staticTokenProvider('sensitive-upstream-bearer'))
++ // Simulate a live connection: connect() resolves the provider into
++ // currentAuthToken, which retire() must clear synchronously. Seed it
++ // directly so the assertion exercises retire()'s wipe, not the unconnected
++ // (already-undefined) state.
++ ;(client as unknown as { currentAuthToken?: string }).currentAuthToken =
++ 'sensitive-upstream-bearer'
+
+ const cleanup = client.retire()
+
- expect((client as unknown as { authToken?: string }).authToken).toBeUndefined()
++ expect(
++ (client as unknown as { currentAuthToken?: string }).currentAuthToken
++ ).toBeUndefined()
+ await expect(cleanup()).resolves.toBeUndefined()
+ })
+ })
diff --cc mcp-host/src/mcp/__tests__/managerPartition.test.ts
index 9817647e7,000000000..2dea562ad
mode 100644,000000..100644
--- a/mcp-host/src/mcp/__tests__/managerPartition.test.ts
+++ b/mcp-host/src/mcp/__tests__/managerPartition.test.ts
@@@ -1,494 -1,0 +1,494 @@@
+/**
+ * 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 { createBrokerTokenProvider } from '../brokerTokenProvider'
+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' },
++ // HCC v2 inventory shape: the seam dispatches on authKind, not auth/oauth.
++ authKind: 'oauth-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)
+ })
+})
+
+// ─── Broker principal binding (PR #319 C2/H1) ────────────────────────────────
+//
+// End-to-end proof of the load-bearing invariant: the userId a tool call
+// carries (options.userId — the authenticated task sender, see
+// toolRegistryAdapter) is the SAME value the mcp-host POSTs to the control-api
+// broker as the grant subject. Composes the REAL manager with the REAL
+// brokerTokenProvider (only the network `fetch` is stubbed); the broker
+// principal is NEVER a hand-minted fixture. control-api trusting that body
+// userId is the documented seam — mcp-host's contract is that it only ever
+// sends the caller's own identity.
+
+describe('Broker principal binding: POST subject is the caller, never crossed', () => {
+ /** Factory wiring the REAL broker provider for user principals, mirroring
+ * main.ts createMcpTokenProviderFactory grantScope='user': user → broker
+ * (server, userId); SHARED → token-less catalog representative. Captures every
+ * broker POST body so the test asserts what identity actually left the host. */
+ function brokerFactory(): {
+ factory: McpTokenProviderFactory
+ bodies: Array<{ mcpServerName?: string; userId?: string; contextId?: string }>
+ } {
+ const bodies: Array<{ mcpServerName?: string; userId?: string; contextId?: string }> = []
+ const fetchImpl = vi.fn(async (_url: string, init: RequestInit) => {
+ const body = JSON.parse(init.body as string) as { userId?: string }
+ bodies.push(body)
+ return {
+ status: 200,
+ json: async () => ({ token: `tok-for-${body.userId}`, expiresAt: null }),
+ } as unknown as Response
+ })
+ const factory: McpTokenProviderFactory = (server, principal) =>
+ principal.kind === 'user'
+ ? createBrokerTokenProvider(
+ server,
+ { userId: principal.userId },
+ {
+ gatewayUrl: () => 'http://gateway:8092',
+ controlToken: () => 'control-jwt',
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ }
+ )
+ : { resolve: async () => undefined, refresh: async () => undefined }
+ return { factory, bodies }
+ }
+
+ it('the userId POSTed to the broker equals the callTool userId (per caller)', async () => {
+ const { factory, bodies } = brokerFactory()
+ 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' })
+
+ // Every broker exchange carries exactly the caller's own identity — no other.
+ expect(bodies).toContainEqual({ mcpServerName: 'gh', userId: 'alice' })
+ expect(bodies).toContainEqual({ mcpServerName: 'gh', userId: 'bob' })
+ expect(bodies.every(b => b.userId === 'alice' || b.userId === 'bob')).toBe(true)
+ // Alice's identity is emitted once; bob's connect never POSTs alice's userId.
+ expect(bodies.filter(b => b.userId === 'alice')).toHaveLength(1)
+
+ // And the resolved Bearer lands only on that caller's own connection.
+ const authHeaders = sdk.transports.map(t => t.requestHeaders['Authorization'])
+ expect(authHeaders).toContain('Bearer tok-for-alice')
+ expect(authHeaders).toContain('Bearer tok-for-bob')
+ expect(authHeaders.filter(h => h === 'Bearer tok-for-alice')).toHaveLength(1)
+ })
+
+ it('never POSTs a userId for the token-less SHARED catalog representative', async () => {
+ const { factory, bodies } = brokerFactory()
+ const manager = new McpManager(undefined, undefined, factory)
+ // addServer opens the SHARED representative (catalog population) with no user.
+ await manager.addServer(oauthUserServer())
+
+ // No per-user call yet → the representative must not have brokered any grant.
+ expect(bodies).toEqual([])
+ })
+})
+
+// ─── 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 --cc mcp-host/src/mcp/authoritativeFleet.ts
index 5bf195fac,cbb351a8f..14f9fe32c
--- a/mcp-host/src/mcp/authoritativeFleet.ts
+++ b/mcp-host/src/mcp/authoritativeFleet.ts
@@@ -461,17 -463,11 +463,23 @@@ async function runMcpFleetEffects<T>
async function resolveRequiredMcpAuthToken(
server: McpServerInfo,
- getAuthToken: (serverName: string) => Promise<string | undefined>
+ getAuthToken: (
+ serverName: string,
+ expectedCredentialRevision?: 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') {
++ // Read from the HCC v2 `authKind` (mini-spec §3.2/§4.4): under v2 `auth` is
++ // never emitted, so gating on it would route an oauth server into the static
++ // getAuthToken path and make HCC's getCredential throw.
++ if (server.authKind === 'oauth-user' || server.authKind === 'oauth-context') {
+ return undefined
+ }
+
if (
!server.enabled ||
!server.status?.ready ||
diff --cc mcp-host/src/mcp/client.ts
index 80185879f,9ff0cac07..bae29aa0b
--- a/mcp-host/src/mcp/client.ts
+++ b/mcp-host/src/mcp/client.ts
@@@ -5,70 -5,21 +5,61 @@@
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 { ListToolsResultSchema } from '@modelcontextprotocol/sdk/types.js'
import { McpServerInfo, McpTool } from '../types'
+import { extractStructuredHttpStatus, isAuthError } from './serverStatus'
+ import {
+ type McpToolCallOptions,
+ ensureNotAborted,
+ remainingBudgetMs,
+ requestOptions,
+ resolveMcpRequestTimeoutMs,
+ withRequestTimeout,
+ } from './requestOptions'
- const DEFAULT_MCP_TOOL_TIMEOUT_MS = 3_600_000
- const DEFAULT_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS = 3_600_000
- const MCP_TOOL_TIMEOUT_ENV = 'CLERUM_MCP_TOOL_TIMEOUT_MS'
- const MCP_TOOL_MAX_TOTAL_TIMEOUT_ENV = 'CLERUM_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS'
+ export type { McpToolCallOptions } from './requestOptions'
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 {
- timeout: number
- maxTotalTimeout: number
- signal?: AbortSignal
- }
+
interface McpCallRecovery {
sourceEpoch: number
sourceClient: Client
@@@ -423,6 -251,10 +309,10 @@@ export class McpClient
*/
retire(): () => Promise<void> {
this.retired = true
+ // The credential is no longer authoritative once this client is detached.
+ // Clear the retained value synchronously before asynchronous transport
+ // cleanup so a retired object cannot keep the old bearer alive in memory.
- this.authToken = undefined
++ this.currentAuthToken = undefined
this.retirementController.abort(this.lifecycleError('closed'))
return this.detachConnection()
}
diff --cc mcp-host/src/mcp/manager.ts
index 0c5c3f3c2,2a44a5de7..2fedcf999
--- a/mcp-host/src/mcp/manager.ts
+++ b/mcp-host/src/mcp/manager.ts
@@@ -1,22 -1,19 +1,31 @@@
/**
* 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 interface McpStatusRefreshSummary {
+ serverCount: number
+ succeeded: number
+ failed: number
+ toolCount: number
+ outputSchemaCount: number
+ aborted: boolean
+ }
+
export type McpAdmissionOutcome = 'applied' | 'stale'
export interface McpAdmissionControl {
isCurrent?: () => boolean
@@@ -120,56 -59,6 +129,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') {
++ if (serverConfig.authKind === 'oauth-user' || serverConfig.authKind === 'oauth-context') {
+ // 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) {
@@@ -749,47 -429,8 +758,48 @@@
}
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'
++ // Only the per-user oauth sabor gets per-user partitions. oauth-context and
++ // static both resolve on the SHARED representative (the else branch below).
++ const isOauthUser = info?.authKind === 'oauth-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,
@@@ -846,27 -459,77 +856,84 @@@
* 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.
+ * Probes a stable client snapshot. State is written only after every probe
+ * settles; an aborted round never mutates the last known server status.
*/
- async refreshAllServerStatus(): Promise<number> {
+ async refreshAllServerStatus(options: McpToolCallOptions = {}): Promise<McpStatusRefreshSummary> {
- const entries = [...this.clients.entries()]
++ // One representative client per server. The ClientKey index partitions an
++ // oauth grantScope='user' server into per-user clients, but a status round
++ // probes each server once via its representative; iterating raw clients would
++ // double-count those partitions in the summary tally.
+ 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(
+ if (options.signal?.aborted) {
+ return {
+ serverCount: entries.length,
+ succeeded: 0,
+ failed: 0,
+ toolCount: 0,
+ outputSchemaCount: 0,
+ aborted: true,
+ }
+ }
+
+ const results = await Promise.all(
entries.map(async ([name, client]) => {
- const result = await client.probeTools()
- if (this.representativeClient(name) !== client) return
- if (!result.ok && result.stale) return
- if (result.ok) {
- this.statusTracker.updateToolCount(name, result.toolCount)
- } else {
- this.statusTracker.updateToolCount(name, 0, { refreshError: result.error })
+ try {
+ return {
+ name,
+ client,
+ // Probes share the round's abort signal directly: the heartbeat owns
+ // round-level cancellation and no per-probe cancellation capability
+ // exists, so wrapping the signal would only fake a seam.
+ result: await client.probeTools({
+ timeoutMs: options.timeoutMs,
+ signal: options.signal,
+ }),
+ }
+ } catch (error) {
+ return { name, client, result: { ok: false as const, error, stale: false } }
}
})
)
- return entries.length
+ // A probe only counts toward the round's tally when its result is
+ // authoritative for the currently-installed client: never a client swapped
+ // out mid-round, never a stale-error probe that raced a reconnect. This is
+ // the same predicate the status commit below uses, so summary.succeeded /
+ // summary.failed match what was written — a benign mid-round swap can't
+ // inflate `failed` and flip the run's outcome on the series #148 watches.
+ const committed = results.filter(
+ ({ name, client, result }) =>
- this.clients.get(name) === client && !(!result.ok && result.stale)
++ this.representativeClient(name) === client && !(!result.ok && result.stale)
+ )
+ const succeeded = committed.filter(({ result }) => result.ok).length
+ const summary: McpStatusRefreshSummary = {
+ serverCount: entries.length,
+ succeeded,
+ failed: committed.length - succeeded,
+ toolCount: committed.reduce(
+ (total, { result }) => total + (result.ok ? result.toolCount : 0),
+ 0
+ ),
+ outputSchemaCount: committed.reduce(
+ (total, { result }) => total + (result.ok ? result.outputSchemaCount : 0),
+ 0
+ ),
+ aborted: options.signal?.aborted === true,
+ }
+ if (summary.aborted) return summary
+
+ for (const { name, result } of committed) {
+ if (result.ok) {
+ this.statusTracker.updateToolCount(name, result.toolCount)
+ } else {
+ this.statusTracker.updateToolCount(name, 0, { refreshError: result.error })
+ }
+ }
+ return summary
}
/**
diff --cc mcp-host/src/mcp/requestOptions.ts
index 000000000,66baa8430..83fe9ed6b
mode 000000,100644..100644
--- a/mcp-host/src/mcp/requestOptions.ts
+++ b/mcp-host/src/mcp/requestOptions.ts
@@@ -1,0 -1,119 +1,124 @@@
+ const DEFAULT_MCP_TOOL_TIMEOUT_MS = 3_600_000
+ const DEFAULT_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS = 3_600_000
+ const MCP_TOOL_TIMEOUT_ENV = 'CLERUM_MCP_TOOL_TIMEOUT_MS'
+ const MCP_TOOL_MAX_TOTAL_TIMEOUT_ENV = 'CLERUM_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS'
+
+ 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
+ }
+
+ export interface McpSdkRequestOptions {
+ timeout: number
+ maxTotalTimeout: number
+ signal?: AbortSignal
+ }
+
+ function readPositiveSafeIntegerEnv(name: string, defaultValue: number): number {
+ const raw = process.env[name]
+ if (raw === undefined || raw === '') return defaultValue
+ if (!/^\d+$/.test(raw)) throw new Error(`${name} must be a positive safe integer`)
+ const value = Number.parseInt(raw, 10)
+ if (!Number.isSafeInteger(value) || value < 1) {
+ throw new Error(`${name} must be a positive safe integer`)
+ }
+ return value
+ }
+
+ export function resolveMcpRequestTimeoutMs(callerTimeoutMs?: number): number {
+ const configuredTimeoutMs = readPositiveSafeIntegerEnv(
+ MCP_TOOL_TIMEOUT_ENV,
+ DEFAULT_MCP_TOOL_TIMEOUT_MS
+ )
+ const configuredMaxTotalTimeoutMs = readPositiveSafeIntegerEnv(
+ MCP_TOOL_MAX_TOTAL_TIMEOUT_ENV,
+ DEFAULT_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS
+ )
+ if (
+ configuredMaxTotalTimeoutMs < configuredTimeoutMs &&
+ (callerTimeoutMs === undefined || callerTimeoutMs > configuredMaxTotalTimeoutMs)
+ ) {
+ throw new Error(
+ `${MCP_TOOL_MAX_TOTAL_TIMEOUT_ENV} must be greater than or equal to ${MCP_TOOL_TIMEOUT_ENV}`
+ )
+ }
+ if (callerTimeoutMs !== undefined) {
+ if (!Number.isSafeInteger(callerTimeoutMs) || callerTimeoutMs < 1) {
+ throw new Error('caller MCP timeout must be a positive safe integer')
+ }
+ return Math.min(configuredTimeoutMs, configuredMaxTotalTimeoutMs, callerTimeoutMs)
+ }
+ return Math.min(configuredTimeoutMs, configuredMaxTotalTimeoutMs)
+ }
+
+ export function ensureNotAborted(signal: AbortSignal | undefined): void {
+ if (!signal?.aborted) return
+ throw abortError(signal, 'aborted')
+ }
+
+ function abortError(signal: AbortSignal | undefined, fallback: string): Error {
+ // Preserve an Error abort reason verbatim (e.g. the lifecycle 'closed' /
+ // 'superseded' error propagated through retirementController.abort()), so a
+ // retired/superseded connection surfaces its real cause instead of 'aborted'.
+ if (signal?.reason instanceof Error) return signal.reason
+ const reason =
+ typeof signal?.reason === 'string' && signal.reason.trim() ? signal.reason : fallback
+ return new Error(reason)
+ }
+
+ export function withRequestTimeout<T>(
+ operation: Promise<T>,
+ options: McpToolCallOptions,
+ timeoutMessage: string
+ ): Promise<T> {
+ ensureNotAborted(options.signal)
+ const timeoutMs = resolveMcpRequestTimeoutMs(options.timeoutMs)
+ return new Promise((resolve, reject) => {
+ let settled = false
+ const cleanup = () => {
+ clearTimeout(timer)
+ options.signal?.removeEventListener('abort', onAbort)
+ }
+ const resolveOnce = (value: T) => {
+ if (settled) return
+ settled = true
+ cleanup()
+ resolve(value)
+ }
+ const rejectOnce = (error: unknown) => {
+ if (settled) return
+ settled = true
+ cleanup()
+ reject(error)
+ }
+ const onAbort = () => rejectOnce(abortError(options.signal, 'aborted'))
+ const timer = setTimeout(
+ () =>
+ rejectOnce(new Error(options.timeoutMs !== undefined ? 'step-timeout' : timeoutMessage)),
+ timeoutMs
+ )
+ options.signal?.addEventListener('abort', onAbort, { once: true })
+ operation.then(resolveOnce, rejectOnce)
+ })
+ }
+
+ export function remainingBudgetMs(deadlineMs: number | undefined): number | undefined {
+ if (deadlineMs === undefined) return undefined
+ const remainingMs = deadlineMs - Date.now()
+ if (remainingMs <= 0) throw new Error('step-timeout')
+ return remainingMs
+ }
+
+ export function requestOptions(
+ timeoutMs: number | undefined,
+ signal: AbortSignal | undefined
+ ): McpSdkRequestOptions {
+ ensureNotAborted(signal)
+ const timeout = resolveMcpRequestTimeoutMs(timeoutMs)
+ return { timeout, maxTotalTimeout: timeout, ...(signal ? { signal } : {}) }
+ }
diff --cc mcp-host/src/mcp/serverStatus.ts
index bcacc03d4,a5f15ed99..d0e19adea
--- a/mcp-host/src/mcp/serverStatus.ts
+++ b/mcp-host/src/mcp/serverStatus.ts
@@@ -135,19 -121,7 +138,19 @@@ export function extractHttpStatus(error
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 {
+ function extractErrorCode(error: unknown): string | number | null {
if (error && typeof error === 'object') {
const code = (error as Record<string, unknown>).code
if (typeof code === 'string') return code
diff --cc mcp-host/src/types.ts
index f812880ec,b28383662..c48b99f15
--- a/mcp-host/src/types.ts
+++ b/mcp-host/src/types.ts
@@@ -183,14 -176,22 +192,36 @@@ export interface McpServerStatus
export interface McpServerInfo {
name: string
description?: string
- contextRef: string
+ /**
+ * Present only for development/legacy in-process configuration. The HCC v2
+ * Host inventory deliberately omits Context identity: HCC derives it from
+ * the authenticated Host JWT and never returns it to the caller.
+ */
+ contextRef?: string
transport: McpServerTransport
+ /** Legacy development shape. HCC v2 returns only authRequired. */
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
+ /** Whether the scoped HCC credential route must return a bearer. */
+ authRequired?: boolean
+ /**
+ * Opaque HCC authority revision. It changes when the authorized server,
+ * auth selector, or referenced Secret identity/resourceVersion changes.
+ */
+ credentialRevision?: string
++ /**
++ * Non-secret credential-mode policy emitted by the HCC v2 inventory. Drives the
++ * token-provider dispatch in the mcp-host seam (mini-spec §3.2): `static` uses
++ * the revision-locked getAuthToken route; `oauth-user`/`oauth-context` build a
++ * broker provider. Absent → treated as `static` (fail-closed). It carries NO
++ * authority (never contextRef/secretRef/token) — that is the invariant (I1)
++ * keeping it on the policy side of the decoder's forbidden-metadata guard.
++ */
++ authKind?: 'static' | 'oauth-user' | 'oauth-context'
enabled: boolean
status: McpServerStatus
}