Skip to content

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

TypeScript

fix(np-08): bind HCC MCP credentials to live Host context

Alfredo Lopez8c296a9708e1
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.yml
index 18daf933c..f480a5818 100644
--- a/.github/workflows/ci-public.yml
+++ b/.github/workflows/ci-public.yml
@@ -468,6 +468,9 @@ jobs:
- name: Test pre-gate runtime assertions
run: bash scripts/tests/test-minikube-pre-gate-runtime.sh
+ - name: Test NP-08 Host clients have no v1 fallback
+ run: bash scripts/tests/test-np08-v1-reference-inventory.sh
+
# ADMIN_PASSWORD is a required precondition of full-setup.sh Step 1 on the
# default (minimal) seed profile. Two cases in this harness execute the
# script against stubbed docker/minikube/kubectl, so without it they abort
diff --git a/control-api/src/routes/auth/mcp-host/issue.routes.ts b/control-api/src/routes/auth/mcp-host/issue.routes.ts
index 82a651655..59f7dcb42 100644
--- a/control-api/src/routes/auth/mcp-host/issue.routes.ts
+++ b/control-api/src/routes/auth/mcp-host/issue.routes.ts
@@ -62,10 +62,23 @@ function resolveHostName(body: unknown): { hostName: string } | { error: string
if (typeof raw !== 'string') return { error: 'host_required' }
const trimmed = raw.trim()
if (!trimmed) return { error: 'host_required' }
- if (trimmed.length > 63 || !HOST_NAME_RE.test(trimmed)) return { error: 'invalid_host_name' }
+ if (trimmed !== raw || trimmed.length > 63 || !HOST_NAME_RE.test(trimmed)) {
+ return { error: 'invalid_host_name' }
+ }
return { hostName: trimmed }
}
+function resolveHostUid(body: unknown): { hostUid: string } | { error: string } {
+ if (!body || typeof body !== 'object') return { error: 'host_uid_required' }
+ const raw = (body as { hostUid?: unknown }).hostUid
+ if (typeof raw !== 'string') return { error: 'host_uid_required' }
+ const trimmed = raw.trim()
+ if (!trimmed || trimmed !== raw || trimmed.length > 128 || /[^A-Za-z0-9._:-]/.test(trimmed)) {
+ return { error: 'invalid_host_uid' }
+ }
+ return { hostUid: trimmed }
+}
+
function resolveIssueTarget(req: {
params: { namespace?: string; name?: string; recipe?: string }
}): { namespace: string; name: string } | { error: string } {
@@ -114,27 +127,39 @@ export function createAuthMcpHostIssueRoutes(): Router {
return res.status(400).json({ error: 'invalid_issuance_namespace' })
}
+ if (provisioner.iss === 'hcc' && recipeName !== 'standalone') {
+ return res.status(403).json({ error: 'provisioner_target_mismatch' })
+ }
+
// 1st-party (hcc): hostRefs[0] is the actual Host CRD name so per-event
// identity binding can verify the bearer pod is acting on its own behalf.
// 3rd-party (wrc): hostRefs[0] keeps the recipe-binding shape — recipe
// pods don't run on a single named host. Authorization for recipe tokens
// uses recipeNamespace/recipeName instead.
let hostRefs: string[]
+ let hccCredential: { hostUid: string } | undefined
if (provisioner.iss === 'hcc') {
const hostResolved = resolveHostName(req.body)
if ('error' in hostResolved) {
return res.status(400).json({ error: hostResolved.error })
}
+ const uidResolved = resolveHostUid(req.body)
+ if ('error' in uidResolved) {
+ return res.status(400).json({ error: uidResolved.error })
+ }
hostRefs = [hostResolved.hostName]
+ hccCredential = { hostUid: uidResolved.hostUid }
} else {
hostRefs = [`${recipeNamespace}/${recipeName}`]
}
const access = issueMcpHostAccessJwt(recipeNamespace, recipeName, hostRefs, {
workflowControlScopes: controlScopes.scopes,
+ hccCredential,
})
const refresh = issueMcpHostRefreshJwt(recipeNamespace, recipeName, hostRefs, {
workflowControlScopes: controlScopes.scopes,
+ hccCredential,
})
const control = issueMcpHostControlJwt(recipeNamespace, recipeName, hostRefs, {
scopes: controlScopes.scopes,
@@ -142,15 +167,11 @@ export function createAuthMcpHostIssueRoutes(): Router {
req.log?.info(
{
event: 'mcp_host_credentials_issued',
- recipeNamespace,
- recipeName,
provisioner: provisioner.iss,
- sub: provisioner.sub,
- jti: provisioner.jti,
accessTtlSec: access.expiresInSeconds,
controlTtlSec: control.expiresInSeconds,
- hostRefs,
- workflowControlScopes: controlScopes.scopes,
+ workflowControlScopeCount: controlScopes.scopes.length,
+ hccQualified: hccCredential !== undefined,
},
'mcpHost credentials issued'
)
diff --git a/control-api/src/routes/mcp-host/renewal/refresh.routes.ts b/control-api/src/routes/mcp-host/renewal/refresh.routes.ts
index 00dcf419d..0a710a645 100644
--- a/control-api/src/routes/mcp-host/renewal/refresh.routes.ts
+++ b/control-api/src/routes/mcp-host/renewal/refresh.routes.ts
@@ -7,6 +7,7 @@ import {
mcpHostJwtRefreshTotal,
} from '../../../observability/metrics.js'
import {
+ MCP_HOST_CREDENTIAL_CAPABILITY,
consumeMcpHostRefreshJwt,
getMcpHostRefreshRateLimitKey,
issueMcpHostAccessJwt,
@@ -58,19 +59,23 @@ export function createMcpHostRefreshRoutes(): Router {
return res.status(401).json({ error: 'Unauthorized' })
}
+ const hccCredential = claims.mcpCapabilities.includes(MCP_HOST_CREDENTIAL_CAPABILITY)
+ ? { hostUid: claims.host_uid! }
+ : undefined
+
// Preserve hostRefs from the incoming refresh token so the host
// identity binding (1st-party hostRefs[0]) survives rotation.
const access = issueMcpHostAccessJwt(
claims.recipeNamespace,
claims.recipeName,
claims.hostRefs,
- { workflowControlScopes: claims.workflowControlScopes }
+ { workflowControlScopes: claims.workflowControlScopes, hccCredential }
)
const refresh = issueMcpHostRefreshJwt(
claims.recipeNamespace,
claims.recipeName,
claims.hostRefs,
- { workflowControlScopes: claims.workflowControlScopes }
+ { workflowControlScopes: claims.workflowControlScopes, hccCredential }
)
const control = issueMcpHostControlJwt(
claims.recipeNamespace,
diff --git a/control-api/src/routes/mcp-host/renewal/reissue.routes.ts b/control-api/src/routes/mcp-host/renewal/reissue.routes.ts
index ca3b160bc..afb7bdbac 100644
--- a/control-api/src/routes/mcp-host/renewal/reissue.routes.ts
+++ b/control-api/src/routes/mcp-host/renewal/reissue.routes.ts
@@ -4,6 +4,7 @@ import { mcpHostHttpMetrics } from '../../../middleware/mcpHostHttpMetrics.js'
import { rateLimitMiddleware } from '../../../middleware/rateLimitMiddleware.js'
import { mcpHostJwtReissueTotal } from '../../../observability/metrics.js'
import {
+ MCP_HOST_CREDENTIAL_CAPABILITY,
consumeExpiredRefreshJti,
getMcpHostExpiredRefreshRateLimitKey,
issueMcpHostAccessJwt,
@@ -101,7 +102,6 @@ export function createMcpHostReissueRoutes(): Router {
reason: 'recipe_name_mismatch',
route: 'workflow_auth_reissue',
mode,
- jwtRecipe: claims.recipeName,
},
'auth denied'
)
@@ -119,7 +119,6 @@ export function createMcpHostReissueRoutes(): Router {
reason: 'missing_host_ref',
route: 'workflow_auth_reissue',
mode,
- recipeNamespace: claims.recipeNamespace,
},
'auth denied'
)
@@ -133,8 +132,6 @@ export function createMcpHostReissueRoutes(): Router {
reason: 'host_ref_mismatch',
route: 'workflow_auth_reissue',
mode,
- hostRef,
- recipeNamespace: claims.recipeNamespace,
},
'auth denied'
)
@@ -147,7 +144,6 @@ export function createMcpHostReissueRoutes(): Router {
event: 'auth_denied',
reason: 'unsupported_reissue_namespace',
route: 'workflow_auth_reissue',
- recipeNamespace: claims.recipeNamespace,
},
'auth denied'
)
@@ -164,19 +160,23 @@ export function createMcpHostReissueRoutes(): Router {
return res.status(401).json({ error: 'Unauthorized' })
}
+ const hccCredential = claims.mcpCapabilities.includes(MCP_HOST_CREDENTIAL_CAPABILITY)
+ ? { hostUid: claims.host_uid! }
+ : undefined
+
// Preserve hostRefs from the incoming (expired) refresh token so
// the host identity binding survives the recovery re-issue.
const access = issueMcpHostAccessJwt(
claims.recipeNamespace,
claims.recipeName,
claims.hostRefs,
- { workflowControlScopes: claims.workflowControlScopes }
+ { workflowControlScopes: claims.workflowControlScopes, hccCredential }
)
const refresh = issueMcpHostRefreshJwt(
claims.recipeNamespace,
claims.recipeName,
claims.hostRefs,
- { workflowControlScopes: claims.workflowControlScopes }
+ { workflowControlScopes: claims.workflowControlScopes, hccCredential }
)
const control = issueMcpHostControlJwt(
claims.recipeNamespace,
@@ -190,9 +190,7 @@ export function createMcpHostReissueRoutes(): Router {
{
event: 'workflow_auth_reissued',
mode,
- recipeNamespace: claims.recipeNamespace,
- recipeName: claims.recipeName,
- hostRef,
+ hccQualified: hccCredential !== undefined,
},
'workflow auth re-issued'
)
diff --git a/control-api/src/utils/auth/mcpHostJwtToken.ts b/control-api/src/utils/auth/mcpHostJwtToken.ts
index eaa376d62..28fae32b8 100644
--- a/control-api/src/utils/auth/mcpHostJwtToken.ts
+++ b/control-api/src/utils/auth/mcpHostJwtToken.ts
@@ -14,12 +14,27 @@ const revokedRefreshJtis = new Set<string>()
const MAX_CACHED_JTIS = 10_000
const EXPIRED_REFRESH_REISSUE_GRACE_SECONDS = 5 * 60
-/**
- * jsonwebtoken normalizes a single `aud` to a string and multiple to an array.
- * Our claims model carries a single audience string, so unwrap consistently.
- */
-function firstAudience(aud: jwt.JwtPayload['aud']): string {
- return Array.isArray(aud) ? aud[0] : (aud as string)
+export const MCP_HOST_WORKFLOW_AUDIENCE = 'workflow-approvals'
+export const MCP_HOST_HCC_AUDIENCE = 'host-context-controller'
+export const MCP_HOST_CREDENTIAL_CAPABILITY = 'mcp:credential:read'
+const HCC_HOST_NAME_RE = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/
+
+type McpHostCredentialLineage = {
+ hostUid: string
+}
+
+function normalizeAudienceClaim(aud: jwt.JwtPayload['aud']): string[] | null {
+ const values = typeof aud === 'string' ? [aud] : Array.isArray(aud) ? aud : null
+ if (!values || values.length === 0 || values.some(value => typeof value !== 'string')) {
+ return null
+ }
+ if (new Set(values).size !== values.length) return null
+
+ const actual = new Set(values)
+ const workflowOnly = actual.size === 1 && actual.has(MCP_HOST_WORKFLOW_AUDIENCE)
+ const hccQualified =
+ actual.size === 2 && actual.has(MCP_HOST_WORKFLOW_AUDIENCE) && actual.has(MCP_HOST_HCC_AUDIENCE)
+ return workflowOnly || hccQualified ? values : null
}
// Eviction is FIFO (Set iterator is insertion-ordered), not LRU. At
@@ -108,8 +123,10 @@ export type McpHostAccessClaims = {
hostRefs: string[]
scope: 'workflow:approval:request'
workflowControlScopes: McpHostControlScope[]
+ mcpCapabilities: string[]
+ host_uid?: string
iss: string
- aud: string
+ aud: string | string[]
jti: string
exp: number
}
@@ -121,8 +138,10 @@ export type McpHostRefreshClaims = {
hostRefs: string[]
scope: 'workflow:approval:refresh'
workflowControlScopes: McpHostControlScope[]
+ mcpCapabilities: string[]
+ host_uid?: string
iss: string
- aud: string
+ aud: string | string[]
jti: string
exp: number
}
@@ -189,8 +208,12 @@ function issueToken(
scope: 'workflow:approval:request' | 'workflow:approval:refresh',
ttlSec: number,
hostRefs: string[],
- workflowControlScopes: McpHostControlScope[] = []
+ workflowControlScopes: McpHostControlScope[] = [],
+ hccCredential?: McpHostCredentialLineage
): { token: string; expiresInSeconds: number } {
+ if (hccCredential) {
+ assertHccCredentialLineage(recipeNamespace, recipeName, hostRefs, hccCredential)
+ }
const token = jwt.sign(
{
sub: `${recipeNamespace}/${recipeName}`,
@@ -199,12 +222,20 @@ function issueToken(
hostRefs,
scope,
workflowControlScopes,
+ ...(hccCredential
+ ? {
+ host_uid: hccCredential.hostUid,
+ mcpCapabilities: [MCP_HOST_CREDENTIAL_CAPABILITY],
+ }
+ : {}),
},
config.adminJwtPrivateKey,
{
algorithm: 'RS256',
issuer: config.adminJwtIssuer,
- audience: 'workflow-approvals',
+ audience: hccCredential
+ ? [MCP_HOST_WORKFLOW_AUDIENCE, MCP_HOST_HCC_AUDIENCE]
+ : MCP_HOST_WORKFLOW_AUDIENCE,
jwtid: randomUUID(),
expiresIn: ttlSec,
}
@@ -216,7 +247,10 @@ export function issueMcpHostAccessJwt(
recipeNamespace: string,
recipeName: string,
hostRefs?: string[],
- options: { workflowControlScopes?: McpHostControlScope[] } = {}
+ options: {
+ workflowControlScopes?: McpHostControlScope[]
+ hccCredential?: McpHostCredentialLineage
+ } = {}
): { token: string; expiresInSeconds: number } {
const refs = normalizeIssuedMcpHostHostRefs(recipeNamespace, recipeName, hostRefs)
const workflowControlScopes = normalizeMcpHostControlScopes(options.workflowControlScopes ?? [])
@@ -227,7 +261,8 @@ export function issueMcpHostAccessJwt(
'workflow:approval:request',
config.mcpHostJwtAccessTtlSec,
refs,
- workflowControlScopes
+ workflowControlScopes,
+ options.hccCredential
)
mcpHostJwtIssueTotal.inc({ kind: 'access' }, 1)
return out
@@ -237,7 +272,10 @@ export function issueMcpHostRefreshJwt(
recipeNamespace: string,
recipeName: string,
hostRefs?: string[],
- options: { workflowControlScopes?: McpHostControlScope[] } = {}
+ options: {
+ workflowControlScopes?: McpHostControlScope[]
+ hccCredential?: McpHostCredentialLineage
+ } = {}
): { token: string; expiresInSeconds: number } {
const refs = normalizeIssuedMcpHostHostRefs(recipeNamespace, recipeName, hostRefs)
const workflowControlScopes = normalizeMcpHostControlScopes(options.workflowControlScopes ?? [])
@@ -248,7 +286,8 @@ export function issueMcpHostRefreshJwt(
'workflow:approval:refresh',
config.mcpHostJwtRefreshTtlSec,
refs,
- workflowControlScopes
+ workflowControlScopes,
+ options.hccCredential
)
mcpHostJwtIssueTotal.inc({ kind: 'refresh' }, 1)
return out
@@ -315,6 +354,63 @@ function normalizeMcpHostHostRefs(value: unknown): string[] | null {
return hostRefs
}
+function normalizeHostUid(value: unknown): string | null {
+ if (typeof value !== 'string') return null
+ const normalized = value.trim()
+ if (!normalized || normalized !== value || normalized.length > 128) return null
+ if (/[^A-Za-z0-9._:-]/.test(normalized)) return null
+ return normalized
+}
+
+function assertHccCredentialLineage(
+ recipeNamespace: string,
+ recipeName: string,
+ hostRefs: string[],
+ lineage: McpHostCredentialLineage
+): void {
+ if (
+ recipeNamespace !== config.hostsNamespace ||
+ recipeName !== 'standalone' ||
+ hostRefs.length !== 1 ||
+ hostRefs[0].length > 63 ||
+ !HCC_HOST_NAME_RE.test(hostRefs[0]) ||
+ !normalizeHostUid(lineage.hostUid)
+ ) {
+ throw new Error('invalid HCC mcp-host credential lineage')
+ }
+}
+
+function validateMcpCredentialLineage(
+ payload: jwt.JwtPayload,
+ audiences: string[],
+ recipeNamespace: string,
+ recipeName: string,
+ hostRefs: string[]
+): { hostUid?: string; capabilities: string[] } | null {
+ const hccQualified = audiences.includes(MCP_HOST_HCC_AUDIENCE)
+ if (!hccQualified) {
+ if (payload.host_uid !== undefined || payload.mcpCapabilities !== undefined) return null
+ return { capabilities: [] }
+ }
+
+ const hostUid = normalizeHostUid(payload.host_uid)
+ const capabilities = payload.mcpCapabilities
+ if (
+ recipeNamespace !== config.hostsNamespace ||
+ recipeName !== 'standalone' ||
+ hostRefs.length !== 1 ||
+ hostRefs[0].length > 63 ||
+ !HCC_HOST_NAME_RE.test(hostRefs[0]) ||
+ !hostUid ||
+ !Array.isArray(capabilities) ||
+ capabilities.length !== 1 ||
+ capabilities[0] !== MCP_HOST_CREDENTIAL_CAPABILITY
+ ) {
+ return null
+ }
+ return { hostUid, capabilities: [MCP_HOST_CREDENTIAL_CAPABILITY] }
+}
+
function normalizeIssuedMcpHostHostRefs(
recipeNamespace: string,
recipeName: string,
@@ -331,18 +427,33 @@ function validateClaims(
): McpHostAccessClaims | McpHostRefreshClaims | null {
const hostRefs = normalizeMcpHostHostRefs(payload?.hostRefs)
const workflowControlScopes = normalizeMcpHostControlScopes(payload?.workflowControlScopes ?? [])
+ const audiences = normalizeAudienceClaim(payload?.aud)
if (
typeof payload?.sub !== 'string' ||
typeof payload?.recipeNamespace !== 'string' ||
typeof payload?.recipeName !== 'string' ||
+ payload.recipeNamespace.trim() !== payload.recipeNamespace ||
+ payload.recipeName.trim() !== payload.recipeName ||
+ !payload.recipeNamespace ||
+ !payload.recipeName ||
+ payload.sub !== `${payload.recipeNamespace}/${payload.recipeName}` ||
!hostRefs ||
!workflowControlScopes ||
+ !audiences ||
payload?.scope !== expectedScope ||
typeof payload?.jti !== 'string' ||
typeof payload?.exp !== 'number'
) {
return null
}
+ const lineage = validateMcpCredentialLineage(
+ payload,
+ audiences,
+ payload.recipeNamespace,
+ payload.recipeName,
+ hostRefs
+ )
+ if (!lineage) return null
return {
sub: payload.sub,
recipeNamespace: payload.recipeNamespace,
@@ -350,8 +461,10 @@ function validateClaims(
hostRefs,
scope: expectedScope as 'workflow:approval:request' | 'workflow:approval:refresh',
workflowControlScopes,
+ mcpCapabilities: lineage.capabilities,
+ ...(lineage.hostUid ? { host_uid: lineage.hostUid } : {}),
iss: payload.iss as string,
- aud: firstAudience(payload.aud),
+ aud: audiences.length === 1 ? audiences[0] : audiences,
jti: payload.jti,
exp: payload.exp,
}
@@ -362,7 +475,7 @@ export function verifyMcpHostAccessJwt(token: string): McpHostAccessClaims | nul
const payload = jwt.verify(token, getWorkflowJwtPublicKey(), {
algorithms: ['RS256'],
issuer: config.adminJwtIssuer,
- audience: 'workflow-approvals',
+ audience: MCP_HOST_WORKFLOW_AUDIENCE,
}) as jwt.JwtPayload
return validateClaims(payload, 'workflow:approval:request') as McpHostAccessClaims
} catch {
@@ -408,7 +521,7 @@ export function verifyMcpHostControlJwt(token: string): McpHostControlClaims | n
typ: 'service',
scopes,
iss: payload.iss as string,
- aud: firstAudience(payload.aud),
+ aud: 'mcp-host',
jti,
exp,
}
@@ -426,7 +539,7 @@ export function getMcpHostRefreshRateLimitKey(
const payload = jwt.verify(token, getWorkflowJwtPublicKey(), {
algorithms: ['RS256'],
issuer: config.adminJwtIssuer,
- audience: 'workflow-approvals',
+ audience: MCP_HOST_WORKFLOW_AUDIENCE,
ignoreExpiration: expiredGraceSeconds > 0,
}) as jwt.JwtPayload
@@ -468,7 +581,7 @@ export async function verifyMcpHostRefreshJwt(token: string): Promise<McpHostRef
const payload = jwt.verify(token, getWorkflowJwtPublicKey(), {
algorithms: ['RS256'],
issuer: config.adminJwtIssuer,
- audience: 'workflow-approvals',
+ audience: MCP_HOST_WORKFLOW_AUDIENCE,
}) as jwt.JwtPayload
const claims = validateClaims(
@@ -520,7 +633,7 @@ export async function verifyExpiredMcpHostRefreshJwtDetailed(
payload = jwt.verify(token, getWorkflowJwtPublicKey(), {
algorithms: ['RS256'],
issuer: config.adminJwtIssuer,
- audience: 'workflow-approvals',
+ audience: MCP_HOST_WORKFLOW_AUDIENCE,
// Critical: do NOT let jsonwebtoken reject expiration here. This route
// applies its own bounded grace window after normal claim validation.
ignoreExpiration: true,
@@ -573,7 +686,7 @@ export async function consumeMcpHostRefreshJwt(
const payload = jwt.verify(token, getWorkflowJwtPublicKey(), {
algorithms: ['RS256'],
issuer: config.adminJwtIssuer,
- audience: 'workflow-approvals',
+ audience: MCP_HOST_WORKFLOW_AUDIENCE,
}) as jwt.JwtPayload
const claims = validateClaims(
diff --git a/control-api/test/mcpHostJwtToken.hostRefs.test.ts b/control-api/test/mcpHostJwtToken.hostRefs.test.ts
index 23f1d980f..ac31aebcf 100644
--- a/control-api/test/mcpHostJwtToken.hostRefs.test.ts
+++ b/control-api/test/mcpHostJwtToken.hostRefs.test.ts
@@ -3,6 +3,9 @@ import jwt from 'jsonwebtoken'
import { config } from '../src/config.js'
import {
ALL_MCP_HOST_CONTROL_SCOPES,
+ MCP_HOST_CREDENTIAL_CAPABILITY,
+ MCP_HOST_HCC_AUDIENCE,
+ MCP_HOST_WORKFLOW_AUDIENCE,
type McpHostAccessClaims,
getMcpHostCallerKey,
getMcpHostExpiredRefreshRateLimitKey,
@@ -54,6 +57,75 @@ describe('mcpHostJwtToken — hostRefs JWT claim', () => {
})
})
+ describe('HCC-qualified credential lineage', () => {
+ it('issues and verifies the existing access form with exact HCC authority claims', () => {
+ const { token } = issueMcpHostAccessJwt(config.hostsNamespace, 'standalone', ['chatllm'], {
+ hccCredential: { hostUid: 'host-uid-chatllm' },
+ })
+ const decoded = jwt.decode(token) as Record<string, unknown>
+ expect(decoded.aud).toEqual([MCP_HOST_WORKFLOW_AUDIENCE, MCP_HOST_HCC_AUDIENCE])
+ expect(decoded.host_uid).toBe('host-uid-chatllm')
+ expect(decoded.mcpCapabilities).toEqual([MCP_HOST_CREDENTIAL_CAPABILITY])
+
+ expect(verifyMcpHostAccessJwt(token)).toMatchObject({
+ hostRefs: ['chatllm'],
+ host_uid: 'host-uid-chatllm',
+ mcpCapabilities: [MCP_HOST_CREDENTIAL_CAPABILITY],
+ })
+ })
+
+ it('rejects workflow-only tokens that inject HCC-only claims', () => {
+ const token = jwt.sign(
+ {
+ sub: `${config.hostsNamespace}/standalone`,
+ recipeNamespace: config.hostsNamespace,
+ recipeName: 'standalone',
+ hostRefs: ['chatllm'],
+ host_uid: 'forged-host-uid',
+ mcpCapabilities: [MCP_HOST_CREDENTIAL_CAPABILITY],
+ scope: 'workflow:approval:request',
+ workflowControlScopes: [],
+ },
+ config.adminJwtPrivateKey,
+ {
+ algorithm: 'RS256',
+ issuer: config.adminJwtIssuer,
+ audience: MCP_HOST_WORKFLOW_AUDIENCE,
+ jwtid: 'workflow-only-injected-hcc-claims',
+ expiresIn: 300,
+ }
+ )
+
+ expect(verifyMcpHostAccessJwt(token)).toBeNull()
+ })
+
+ it('rejects duplicate and third-party audience values even with a valid signature', () => {
+ const base = {
+ sub: `${config.hostsNamespace}/standalone`,
+ recipeNamespace: config.hostsNamespace,
+ recipeName: 'standalone',
+ hostRefs: ['chatllm'],
+ host_uid: 'host-uid-chatllm',
+ mcpCapabilities: [MCP_HOST_CREDENTIAL_CAPABILITY],
+ scope: 'workflow:approval:request',
+ workflowControlScopes: [],
+ }
+ for (const audience of [
+ [MCP_HOST_WORKFLOW_AUDIENCE, MCP_HOST_HCC_AUDIENCE, MCP_HOST_HCC_AUDIENCE],
+ [MCP_HOST_WORKFLOW_AUDIENCE, MCP_HOST_HCC_AUDIENCE, 'unrelated-service'],
+ ]) {
+ const token = jwt.sign(base, config.adminJwtPrivateKey, {
+ algorithm: 'RS256',
+ issuer: config.adminJwtIssuer,
+ audience,
+ jwtid: `bad-audience-${audience.length}-${audience.at(-1)}`,
+ expiresIn: 300,
+ })
+ expect(verifyMcpHostAccessJwt(token)).toBeNull()
+ }
+ })
+ })
+
describe('getMcpHostRefreshRateLimitKey', () => {
it('derives the rate-limit key only from a signed refresh JWT', () => {
const { token } = issueMcpHostRefreshJwt('sandbox-recipes', 'rate-limited-recipe')
@@ -390,6 +462,8 @@ describe('mcpHostJwtToken — hostRefs JWT claim', () => {
recipeName: 'recipe1',
hostRefs: ['ns1/recipe1'],
scope: 'workflow:approval:request' as const,
+ workflowControlScopes: [],
+ mcpCapabilities: [],
iss: 'test',
aud: 'test',
jti: 'test-jti',
@@ -405,6 +479,8 @@ describe('mcpHostJwtToken — hostRefs JWT claim', () => {
recipeName: 'recipe1',
hostRefs: ['ns1/recipe1'],
scope: 'workflow:approval:request',
+ workflowControlScopes: [],
+ mcpCapabilities: [],
iss: 'test',
aud: 'test',
jti: 'test-jti',
@@ -420,6 +496,8 @@ describe('mcpHostJwtToken — hostRefs JWT claim', () => {
recipeName: 'recipe1',
hostRefs: ['ns1/recipe1', 'ns2/recipe2'],
scope: 'workflow:approval:request',
+ workflowControlScopes: [],
+ mcpCapabilities: [],
iss: 'test',
aud: 'test',
jti: 'test-jti',
@@ -436,6 +514,8 @@ describe('mcpHostJwtToken — hostRefs JWT claim', () => {
recipeName: 'recipe1',
hostRefs: ['ns1/*'],
scope: 'workflow:approval:request',
+ workflowControlScopes: [],
+ mcpCapabilities: [],
iss: 'test',
aud: 'test',
jti: 'test-jti',
diff --git a/control-api/test/network.gateway.intent.test.ts b/control-api/test/network.gateway.intent.test.ts
index a3a77802e..c44f7cd2d 100644
--- a/control-api/test/network.gateway.intent.test.ts
+++ b/control-api/test/network.gateway.intent.test.ts
@@ -355,13 +355,13 @@ describe('network/gateway intent (manifest-level)', () => {
// hard-413s while the client-side cap says it should have worked.
const hccDeployment = read(`${BASE}/control-plane/host-context-controller.yaml`)
const gfscCapMatch = hccDeployment.match(
- /GFS_MAX_WRITE_BODY_BYTES[\s\S]{0,80}?value:\s*"?(\d+)"?/
+ /GFS_MAX_WRITE_BODY_BYTES[\s\S]{0,80}?value:\s*(["']?)(\d+)\1/
)
expect(
gfscCapMatch,
'GFS_MAX_WRITE_BODY_BYTES env must be set on the HCC deployment'
).not.toBeNull()
- expect(Number(gfscCapMatch![1])).toBe(GFSC_WRITE_CAP)
+ expect(Number(gfscCapMatch![2])).toBe(GFSC_WRITE_CAP)
// 2. Both clients advertise the same hard binary part cap and product cap.
const parseClientCaps = (relPath: string): { product: number; part: number } => {
diff --git a/control-api/test/routes.auth.mcp-host.issue.test.ts b/control-api/test/routes.auth.mcp-host.issue.test.ts
index 56c6c089a..1f21cd810 100644
--- a/control-api/test/routes.auth.mcp-host.issue.test.ts
+++ b/control-api/test/routes.auth.mcp-host.issue.test.ts
@@ -3,7 +3,12 @@ import jwt from 'jsonwebtoken'
import request from 'supertest'
import { createApp } from '../src/app.js'
import { config } from '../src/config.js'
-import { ALL_MCP_HOST_CONTROL_SCOPES } from '../src/utils/auth/mcpHostJwtToken.js'
+import {
+ ALL_MCP_HOST_CONTROL_SCOPES,
+ MCP_HOST_CREDENTIAL_CAPABILITY,
+ MCP_HOST_HCC_AUDIENCE,
+ MCP_HOST_WORKFLOW_AUDIENCE,
+} from '../src/utils/auth/mcpHostJwtToken.js'
import { MockGateway } from './mockGateway.js'
vi.mock('../src/services/notificationEmitter.js', () => ({
@@ -114,7 +119,7 @@ describe('routes/auth/mcp-host issue', () => {
const res = await request(app)
.post('/api/v1/auth/mcp-host/mcp-host/standalone/tokens')
.set('Authorization', `Bearer ${signInternalControlJwt('hcc')}`)
- .send({ ...ISSUE_BODY, host: 'trader' })
+ .send({ ...ISSUE_BODY, host: 'trader', hostUid: 'host-uid-trader' })
expect(res.status).toBe(200)
expect(res.body).toHaveProperty('mcpHostAccessToken')
@@ -124,10 +129,20 @@ describe('routes/auth/mcp-host issue', () => {
expect(res.body.hostRefs).toEqual(['trader'])
const controlClaims = jwt.decode(res.body.mcpHostControlToken) as Record<string, unknown>
+ const accessClaims = jwt.decode(res.body.mcpHostAccessToken) as Record<string, unknown>
+ const refreshClaims = jwt.decode(res.body.mcpHostRefreshToken) as Record<string, unknown>
expect(controlClaims.scopes).toEqual(ALL_MCP_HOST_CONTROL_SCOPES)
expect(controlClaims.scope).toBeUndefined()
expect(controlClaims.aud).toBe('mcp-host')
expect(controlClaims.hostRefs).toEqual(['trader'])
+ for (const claims of [accessClaims, refreshClaims]) {
+ expect(claims.aud).toEqual([MCP_HOST_WORKFLOW_AUDIENCE, MCP_HOST_HCC_AUDIENCE])
+ expect(claims.host_uid).toBe('host-uid-trader')
+ expect(claims.mcpCapabilities).toEqual([MCP_HOST_CREDENTIAL_CAPABILITY])
+ expect(claims.hostRefs).toEqual(['trader'])
+ }
+ expect(controlClaims.host_uid).toBeUndefined()
+ expect(controlClaims.mcpCapabilities).toBeUndefined()
})
it('uses the workflowControlScopes declared by the trusted provisioner', async () => {
@@ -201,6 +216,47 @@ describe('routes/auth/mcp-host issue', () => {
expect(res.body.error).toBe('invalid_host_name')
})
+ it('rejects a non-canonical HCC Host name instead of normalizing caller input', async () => {
+ const res = await request(app)
+ .post('/api/v1/auth/mcp-host/mcp-host/standalone/tokens')
+ .set('Authorization', `Bearer ${signInternalControlJwt('hcc')}`)
+ .send({ ...ISSUE_BODY, host: ' trader ' })
+
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('invalid_host_name')
+ })
+
+ it('rejects HCC issuance without the live Host UID', async () => {
+ const res = await request(app)
+ .post('/api/v1/auth/mcp-host/mcp-host/standalone/tokens')
+ .set('Authorization', `Bearer ${signInternalControlJwt('hcc')}`)
+ .send({ ...ISSUE_BODY, host: 'trader' })
+
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('host_uid_required')
+ })
+
+ it('does not let a WRC body upgrade a workflow token into HCC credential authority', async () => {
+ const res = await request(app)
+ .post('/api/v1/auth/mcp-host/sandbox-recipes/test-recipe/tokens')
+ .set('Authorization', `Bearer ${signInternalControlJwt('wrc')}`)
+ .send({
+ ...ISSUE_BODY,
+ host: 'trader',
+ hostUid: 'forged-host-uid',
+ mcpCapabilities: [MCP_HOST_CREDENTIAL_CAPABILITY],
+ audience: MCP_HOST_HCC_AUDIENCE,
+ })
+
+ expect(res.status).toBe(200)
+ for (const encoded of [res.body.mcpHostAccessToken, res.body.mcpHostRefreshToken]) {
+ const claims = jwt.decode(encoded) as Record<string, unknown>
+ expect(claims.aud).toBe(MCP_HOST_WORKFLOW_AUDIENCE)
+ expect(claims.host_uid).toBeUndefined()
+ expect(claims.mcpCapabilities).toBeUndefined()
+ }
+ })
+
it('rejects HCC issuance with an empty / whitespace host', async () => {
const res = await request(app)
.post('/api/v1/auth/mcp-host/mcp-host/standalone/tokens')
@@ -241,6 +297,16 @@ describe('routes/auth/mcp-host issue', () => {
expect(res.body.error).toBe('provisioner_namespace_mismatch')
})
+ it('rejects a non-standalone HCC issuance target before signing', async () => {
+ const res = await request(app)
+ .post('/api/v1/auth/mcp-host/mcp-host/other-recipe/tokens')
+ .set('Authorization', `Bearer ${signInternalControlJwt('hcc')}`)
+ .send({ ...ISSUE_BODY, host: 'trader', hostUid: 'host-uid-trader' })
+
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('provisioner_target_mismatch')
+ })
+
it('rejects WRC for mcp-host namespace', async () => {
const res = await request(app)
.post('/api/v1/auth/mcp-host/mcp-host/standalone/tokens')
@@ -281,7 +347,7 @@ describe('routes/auth/mcp-host issue', () => {
const res = await request(app)
.post('/api/v1/auth/mcp-host/agents/standalone/tokens')
.set('Authorization', `Bearer ${signInternalControlJwt('hcc')}`)
- .send({ ...ISSUE_BODY, host: 'chatllm' })
+ .send({ ...ISSUE_BODY, host: 'chatllm', hostUid: 'host-uid-chatllm' })
expect(res.status).toBe(200)
expect(res.body).toHaveProperty('mcpHostAccessToken')
diff --git a/control-api/test/routes.mcp-host.renewal.reissue.test.ts b/control-api/test/routes.mcp-host.renewal.reissue.test.ts
index eda98d3ca..52737fbfd 100644
--- a/control-api/test/routes.mcp-host.renewal.reissue.test.ts
+++ b/control-api/test/routes.mcp-host.renewal.reissue.test.ts
@@ -3,7 +3,12 @@ import jwt from 'jsonwebtoken'
import request from 'supertest'
import { createApp } from '../src/app.js'
import { config } from '../src/config.js'
-import { issueMcpHostAccessJwt } from '../src/utils/auth/mcpHostJwtToken.js'
+import {
+ MCP_HOST_CREDENTIAL_CAPABILITY,
+ MCP_HOST_HCC_AUDIENCE,
+ MCP_HOST_WORKFLOW_AUDIENCE,
+ issueMcpHostAccessJwt,
+} from '../src/utils/auth/mcpHostJwtToken.js'
import { MockGateway } from './mockGateway.js'
// Preserve the real mcpHostJwtToken helpers — we want the full RS256 sign
@@ -88,7 +93,8 @@ function issueExpiredRefreshToken(
recipe = RECIPE,
expiredSeconds = 60,
hostRefs = [`${ns}/${recipe}`],
- workflowControlScopes = ['workflow:list', 'workflow:read']
+ workflowControlScopes = ['workflow:list', 'workflow:read'],
+ hccCredential?: { hostUid: string }
): string {
// Use the real private key but override expiresIn to a past timestamp via
// the `exp` claim directly. `jwt.sign` with a numeric `exp` bypasses the
@@ -102,13 +108,21 @@ function issueExpiredRefreshToken(
hostRefs,
scope: 'workflow:approval:refresh',
workflowControlScopes,
+ ...(hccCredential
+ ? {
+ host_uid: hccCredential.hostUid,
+ mcpCapabilities: [MCP_HOST_CREDENTIAL_CAPABILITY],
+ }
+ : {}),
exp: now - expiredSeconds,
},
config.adminJwtPrivateKey,
{
algorithm: 'RS256',
issuer: config.adminJwtIssuer,
- audience: 'workflow-approvals',
+ audience: hccCredential
+ ? [MCP_HOST_WORKFLOW_AUDIENCE, MCP_HOST_HCC_AUDIENCE]
+ : MCP_HOST_WORKFLOW_AUDIENCE,
jwtid: `jti-expired-${Math.random().toString(36).slice(2)}`,
}
)
@@ -180,6 +194,33 @@ describe('POST /api/v1/workflow-auth/reissue', () => {
expect(res.status).toBe(200)
})
+ it('preserves HCC audience, Host UID, and capability through bounded reissue', async () => {
+ const token = issueExpiredRefreshToken(
+ HOST_NS,
+ STANDALONE_RECIPE,
+ 60,
+ [HOST_REF],
+ ['workflow:list'],
+ { hostUid: 'signed-host-uid' }
+ )
+ const res = await request(app)
+ .post('/api/v1/workflow-auth/reissue')
+ .set('Authorization', `Bearer ${token}`)
+ .send({
+ host_ref: HOST_REF,
+ hostUid: 'body-controlled-uid',
+ mcpCapabilities: [],
+ })
+
+ expect(res.status).toBe(200)
+ for (const encoded of [res.body.accessToken, res.body.refreshToken]) {
+ const claims = jwt.decode(encoded) as Record<string, unknown>
+ expect(claims.aud).toEqual([MCP_HOST_WORKFLOW_AUDIENCE, MCP_HOST_HCC_AUDIENCE])
+ expect(claims.host_uid).toBe('signed-host-uid')
+ expect(claims.mcpCapabilities).toEqual([MCP_HOST_CREDENTIAL_CAPABILITY])
+ }
+ })
+
it('returns 401 when the Authorization header is missing', async () => {
const res = await request(app)
.post('/api/v1/workflow-auth/reissue')
diff --git a/control-api/test/routes.mcp-host.user-approval-requests.test.ts b/control-api/test/routes.mcp-host.user-approval-requests.test.ts
index 3ee094f82..b76350597 100644
--- a/control-api/test/routes.mcp-host.user-approval-requests.test.ts
+++ b/control-api/test/routes.mcp-host.user-approval-requests.test.ts
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import jwt from 'jsonwebtoken'
import request from 'supertest'
import { createApp } from '../src/app.js'
import * as notificationDeliveryQueueService from '../src/services/notificationDeliveryQueueService.js'
@@ -211,6 +212,7 @@ describe('User Approval Request Routes', () => {
hostRefs: [`${NS}/${RECIPE}`],
scope: 'workflow:approval:refresh',
workflowControlScopes: ['workflow:list', 'workflow:read'],
+ mcpCapabilities: [],
iss: 'test-issuer',
aud: 'workflow-approvals',
jti: 'jti-1',
@@ -227,6 +229,43 @@ describe('User Approval Request Routes', () => {
expect(res.body).toHaveProperty('controlExpiresInSeconds')
})
+ it('preserves HCC authority only from verified refresh lineage and ignores body upgrades', async () => {
+ const { refreshToken } = issueTestTokens()
+ vi.mocked(mcpHostJwt.consumeMcpHostRefreshJwt).mockResolvedValueOnce({
+ sub: 'mcp-host/standalone',
+ recipeNamespace: 'mcp-host',
+ recipeName: 'standalone',
+ hostRefs: ['chatllm'],
+ host_uid: 'signed-host-uid',
+ scope: 'workflow:approval:refresh',
+ workflowControlScopes: ['workflow:list'],
+ mcpCapabilities: [mcpHostJwt.MCP_HOST_CREDENTIAL_CAPABILITY],
+ iss: 'control-api',
+ aud: [mcpHostJwt.MCP_HOST_WORKFLOW_AUDIENCE, mcpHostJwt.MCP_HOST_HCC_AUDIENCE],
+ jti: 'hcc-refresh-jti',
+ exp: Math.floor(Date.now() / 1000) + 3600,
+ })
+
+ const res = await request(app)
+ .post('/api/v1/workflow-auth/refresh')
+ .set('Authorization', `Bearer ${refreshToken}`)
+ .send({ hostUid: 'body-controlled-uid', mcpCapabilities: [] })
+
+ expect(res.status).toBe(200)
+ for (const encoded of [res.body.accessToken, res.body.refreshToken]) {
+ const claims = jwt.decode(encoded) as Record<string, unknown>
+ expect(claims.aud).toEqual([
+ mcpHostJwt.MCP_HOST_WORKFLOW_AUDIENCE,
+ mcpHostJwt.MCP_HOST_HCC_AUDIENCE,
+ ])
+ expect(claims.host_uid).toBe('signed-host-uid')
+ expect(claims.mcpCapabilities).toEqual([mcpHostJwt.MCP_HOST_CREDENTIAL_CAPABILITY])
+ }
+ const control = jwt.decode(res.body.mcpHostControlToken) as Record<string, unknown>
+ expect(control.host_uid).toBeUndefined()
+ expect(control.mcpCapabilities).toBeUndefined()
+ })
+
it('rejects invalid refresh token', async () => {
vi.mocked(mcpHostJwt.consumeMcpHostRefreshJwt).mockResolvedValueOnce(null)
const res = await request(app)
diff --git a/deploy/base/control-plane/configmaps.yaml b/deploy/base/control-plane/configmaps.yaml
index 0559df810..74ac59f13 100644
--- a/deploy/base/control-plane/configmaps.yaml
+++ b/deploy/base/control-plane/configmaps.yaml
@@ -70,26 +70,26 @@ data:
# Hard ceiling for caller-provided ttlSeconds. Defaults to 48h so a client
# asking for ttlSeconds=604800 (code default) can't freeze a workflow step
# for a full week. Overlays may tighten further for stricter environments.
- WORKFLOW_APPROVAL_MAX_TTL_SEC: "172800"
- WORKFLOW_APPROVAL_EXPIRY_INTERVAL_MS: "60000"
+ WORKFLOW_APPROVAL_MAX_TTL_SEC: '172800'
+ WORKFLOW_APPROVAL_EXPIRY_INTERVAL_MS: '60000'
# Terminal approvals are retained in the live table for 180 days, then
# copied to workflow_approval_requests_archive by the daily archive cron.
- APPROVAL_RETENTION_DAYS: "180"
- APPROVAL_ARCHIVE_BATCH_SIZE: "500"
+ APPROVAL_RETENTION_DAYS: '180'
+ APPROVAL_ARCHIVE_BATCH_SIZE: '500'
# TTL for mcpHostJwt control tokens used by runtime mcp-host workflow triggers.
- MCP_HOST_JWT_CONTROL_TTL_SEC: "600"
- CLERUM_WORKFLOW_MAX_WORKLOADS_PER_RECIPE: "25"
- CLERUM_WORKFLOW_UI_EGRESS_INTERNAL_MAX_ITEMS: "25"
- CLERUM_WORKFLOW_MAX_STEPS: "100"
- CLERUM_WORKFLOW_STEP_DEPENDS_ON_MAX_ITEMS: "100"
- CLERUM_WORKFLOW_STEP_ALLOWED_TOOLS_MAX_ITEMS: "50"
- CLERUM_WORKFLOW_STEP_MCP_SERVERS_MAX_ITEMS: "20"
- CLERUM_ATTACHMENT_MAX_BYTES: "52428800"
+ MCP_HOST_JWT_CONTROL_TTL_SEC: '600'
+ CLERUM_WORKFLOW_MAX_WORKLOADS_PER_RECIPE: '25'
+ CLERUM_WORKFLOW_UI_EGRESS_INTERNAL_MAX_ITEMS: '25'
+ CLERUM_WORKFLOW_MAX_STEPS: '100'
+ CLERUM_WORKFLOW_STEP_DEPENDS_ON_MAX_ITEMS: '100'
+ CLERUM_WORKFLOW_STEP_ALLOWED_TOOLS_MAX_ITEMS: '50'
+ CLERUM_WORKFLOW_STEP_MCP_SERVERS_MAX_ITEMS: '20'
+ CLERUM_ATTACHMENT_MAX_BYTES: '52428800'
# Plugin image-host allowlist (Phase 2.3) — audit mode by default. Base ships a
# vendor-neutral default; environment overlays override this with the image
# prefixes for their own registry.
- CONTROL_API_ALLOWED_IMAGE_PREFIXES: "ghcr.io/evenfire-ai/,mongodb/,mcr.microsoft.com/,clerum/"
- CONTROL_API_ENFORCE_IMAGE_ALLOWLIST: "false"
+ CONTROL_API_ALLOWED_IMAGE_PREFIXES: 'ghcr.io/evenfire-ai/,mongodb/,mcr.microsoft.com/,clerum/'
+ CONTROL_API_ENFORCE_IMAGE_ALLOWLIST: 'false'
---
apiVersion: v1
kind: ConfigMap
@@ -802,7 +802,20 @@ data:
uwsgi_temp_path /tmp/uwsgi_temp;
scgi_temp_path /tmp/scgi_temp;
- access_log /dev/stdout;
+ map $uri $hcc_route_class {
+ default denied;
+ ~^/health$ health;
+ ~^/ready$ ready;
+ ~^/api/v2/hosts/self/mcpservers$ host_inventory;
+ ~^/api/v2/hosts/self/mcpservers/credential$ host_credential;
+ ~^/api/v1/mcpservers$ legacy_system_inventory;
+ ~^/api/v1/mcpservers/context/ legacy_host_tombstone;
+ ~^/api/v1/mcpservers/[^/]+/auth$ legacy_host_tombstone;
+ ~^/api/v1/desktop/ desktop;
+ }
+ log_format hcc_gateway_json escape=json
+ '{"gateway":"hcc","request_id":"$request_id","route_class":"$hcc_route_class","method":"$request_method","status":$status,"upstream_status":"$upstream_status","request_time":$request_time,"upstream_response_time":"$upstream_response_time"}';
+ access_log /dev/stdout hcc_gateway_json;
error_log /dev/stderr warn;
upstream host_context_controller_upstream {
@@ -812,6 +825,33 @@ data:
server {
listen 8081;
server_name _;
+ default_type application/json;
+
+ # Normalize errors generated by nginx itself. Upstream errors remain
+ # HCC-owned (`proxy_intercept_errors` is off), preserving HCC's generic
+ # WWW-Authenticate and authorization-unavailable semantics.
+ error_page 400 = @hcc_bad_request;
+ error_page 405 = @hcc_method_not_allowed;
+ error_page 413 = @hcc_payload_too_large;
+
+ location @hcc_bad_request {
+ add_header Cache-Control "no-store, private" always;
+ add_header Pragma "no-cache" always;
+ add_header X-Content-Type-Options "nosniff" always;
+ return 400 '{"error":"bad_request"}';
+ }
+ location @hcc_method_not_allowed {
+ add_header Cache-Control "no-store, private" always;
+ add_header Pragma "no-cache" always;
+ add_header X-Content-Type-Options "nosniff" always;
+ return 405 '{"error":"method_not_allowed"}';
+ }
+ location @hcc_payload_too_large {
+ add_header Cache-Control "no-store, private" always;
+ add_header Pragma "no-cache" always;
+ add_header X-Content-Type-Options "nosniff" always;
+ return 413 '{"error":"payload_too_large"}';
+ }
location = /health {
add_header Content-Type application/json;
@@ -820,34 +860,64 @@ data:
location = /ready {
proxy_pass http://host_context_controller_upstream;
+ proxy_pass_request_headers off;
proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header X-Request-ID $request_id;
}
location = /api/v1/mcpservers {
proxy_pass http://host_context_controller_upstream;
+ proxy_pass_request_headers off;
proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header X-Request-ID $request_id;
}
+ # The retained proxy poller is the only PR 1 compatibility exception
+ # above. Caller-selected legacy Context and credential routes are
+ # closed locally so a stale mcp-host cannot bypass the v2 Host binding.
location ~ ^/api/v1/mcpservers/context/[^/]+$ {
+ add_header Cache-Control "no-store, private" always;
+ add_header Pragma "no-cache" always;
+ add_header X-Content-Type-Options "nosniff" always;
+ return 410 '{"error":"gone"}';
+ }
+
+ location ~ ^/api/v1/mcpservers/[^/]+/auth$ {
+ add_header Cache-Control "no-store, private" always;
+ add_header Pragma "no-cache" always;
+ add_header X-Content-Type-Options "nosniff" always;
+ return 410 '{"error":"gone"}';
+ }
+
+ location = /api/v2/hosts/self/mcpservers {
+ if ($request_method != GET) { return 405; }
proxy_pass http://host_context_controller_upstream;
+ proxy_pass_request_headers off;
+ proxy_http_version 1.1;
proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header Authorization $http_authorization;
+ proxy_set_header X-Request-ID $request_id;
+ proxy_set_header Connection "";
+ add_header Cache-Control "no-store, private" always;
+ add_header Pragma "no-cache" always;
+ add_header X-Content-Type-Options "nosniff" always;
}
- location ~ ^/api/v1/mcpservers/[^/]+/auth$ {
+ location = /api/v2/hosts/self/mcpservers/credential {
+ if ($request_method != POST) { return 405; }
+ client_max_body_size 1k;
proxy_pass http://host_context_controller_upstream;
+ proxy_pass_request_headers off;
+ proxy_http_version 1.1;
proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header Authorization $http_authorization;
+ proxy_set_header Content-Type $http_content_type;
+ proxy_set_header Content-Length $content_length;
+ proxy_set_header X-Request-ID $request_id;
+ proxy_set_header Connection "";
+ add_header Cache-Control "no-store, private" always;
+ add_header Pragma "no-cache" always;
+ add_header X-Content-Type-Options "nosniff" always;
}
location ~ ^/api/v1/desktop/[^/]+$ {
diff --git a/deploy/base/control-plane/host-context-controller.yaml b/deploy/base/control-plane/host-context-controller.yaml
index df8126a53..5e9ea557a 100644
--- a/deploy/base/control-plane/host-context-controller.yaml
+++ b/deploy/base/control-plane/host-context-controller.yaml
@@ -116,6 +116,25 @@ spec:
value: CLERUM_AUTH_JWT_PUBLIC_KEY
- name: HCC_TARGET_NAMESPACE
value: mcp-host
+ # Existing Control API RS256 public key used to verify the first-party
+ # mcp-host access-token family on HCC v2 Host routes. The audience is a
+ # fixed HCC code contract; the issuer is read from the same ConfigMap
+ # key consumed by Control API so signer and verifier cannot drift.
+ - name: HCC_MCP_HOST_JWT_PUBLIC_KEY
+ valueFrom:
+ configMapKeyRef:
+ name: control-api-public-key
+ key: CONTROL_API_PUBLIC_KEY_PEM
+ - name: HCC_MCP_HOST_JWT_ISSUER
+ valueFrom:
+ configMapKeyRef:
+ name: control-api-config
+ key: CONTROL_API_ADMIN_JWT_ISSUER
+ - name: HCC_MCP_HOST_JWT_MAX_TTL_SECONDS
+ valueFrom:
+ configMapKeyRef:
+ name: control-api-config
+ key: WORKFLOW_APPROVAL_ACCESS_TTL_SEC
- name: CONTROL_API_BASE_URL
value: http://control-api.control-plane.svc.cluster.local:8090
# URL of the nginx gateway that mediates mcp-host → control-api
diff --git a/deploy/overlays/minikube/configmaps/mcp-host-config.yaml b/deploy/overlays/minikube/configmaps/mcp-host-config.yaml
index 18786ed96..e9f55075b 100644
--- a/deploy/overlays/minikube/configmaps/mcp-host-config.yaml
+++ b/deploy/overlays/minikube/configmaps/mcp-host-config.yaml
@@ -6,44 +6,45 @@ metadata:
labels:
app: mcp-host
data:
- CLERUM_HOST_NAME: "chatllm"
- CLERUM_SERVER_PORT: "8080"
- CLERUM_CONTEXT_MAPPER_URL: "http://host-context-controller-api-gateway.control-plane.svc.cluster.local:8081"
- CLERUM_CONTEXT_MAPPER_POLL_INTERVAL: "30000"
- MCP_PROXY_ENABLED: "false"
- MCP_PROXY_URL: "http://mcp-proxy.mcp-server.svc.cluster.local:8083"
- CLERUM_AGENT_TASK_DELAY: "3"
- CLERUM_AGENT_MAX_TASK_DURATION: "1800000"
- CLERUM_SHELL_TIMEOUT: "600000"
- CLERUM_TOOL_TIMEOUT: "660000"
- CLERUM_MCP_TOOL_TIMEOUT_MS: "3600000"
- CLERUM_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS: "3600000"
- CLERUM_TOOL_PROGRESS_INTERVAL_MS: "5000"
- CLERUM_AGENT_MAX_TOOL_CALLS: "100"
- CLERUM_AGENT_MAX_QUEUE_SIZE: "100"
- CLERUM_BUDGETS_ENABLED: "true"
- TRACING_APPROVAL_PROMPT_HISTORY_ENABLED: "false"
- TRACING_APPROVAL_PROMPT_HISTORY_MAX_BYTES: "16384"
- TRACING_APPROVAL_PROMPT_HISTORY_RETENTION_DAYS: "30"
- TRACING_APPROVAL_PROMPT_HISTORY_KEY_VERSION: "v1"
+ CLERUM_HOST_NAME: 'chatllm'
+ CLERUM_SERVER_PORT: '8080'
+ CLERUM_CONTEXT_MAPPER_URL: 'http://host-context-controller-api-gateway.control-plane.svc.cluster.local:8081'
+ CLERUM_CONTEXT_MAPPER_POLL_INTERVAL: '30000'
+ MCP_PROXY_ENABLED: 'false'
+ HCC_AUTHORITY_MAX_STALENESS_MS: '60000'
+ MCP_PROXY_URL: 'http://mcp-proxy.mcp-server.svc.cluster.local:8083'
+ CLERUM_AGENT_TASK_DELAY: '3'
+ CLERUM_AGENT_MAX_TASK_DURATION: '1800000'
+ CLERUM_SHELL_TIMEOUT: '600000'
+ CLERUM_TOOL_TIMEOUT: '660000'
+ CLERUM_MCP_TOOL_TIMEOUT_MS: '3600000'
+ CLERUM_MCP_TOOL_MAX_TOTAL_TIMEOUT_MS: '3600000'
+ CLERUM_TOOL_PROGRESS_INTERVAL_MS: '5000'
+ CLERUM_AGENT_MAX_TOOL_CALLS: '100'
+ CLERUM_AGENT_MAX_QUEUE_SIZE: '100'
+ CLERUM_BUDGETS_ENABLED: 'true'
+ TRACING_APPROVAL_PROMPT_HISTORY_ENABLED: 'false'
+ TRACING_APPROVAL_PROMPT_HISTORY_MAX_BYTES: '16384'
+ TRACING_APPROVAL_PROMPT_HISTORY_RETENTION_DAYS: '30'
+ TRACING_APPROVAL_PROMPT_HISTORY_KEY_VERSION: 'v1'
CLERUM_APPROVAL_CONFIG: '{"defaultPolicy":"channel_users","channels":{"telegram":{"enabled":true}}}'
- CLERUM_APPROVAL_TIMEOUT: "0"
- CLERUM_MEMORY_ENABLED: "true"
- CLERUM_SESSION_STORE: "sqlite"
- CLERUM_SESSION_SEARCH_ENABLED: "true"
- CLERUM_SESSION_TTL_DAYS: "90"
- CLERUM_SEARCH_RETENTION_DAYS: "90"
- CLERUM_CONTEXT_MAX_TOKENS: "100000"
- CLERUM_ENABLE_RESPONSE_ATTACHMENTS: "true"
- CLERUM_ATTACHMENT_MAX_COUNT: "3"
- CLERUM_ATTACHMENT_MAX_BYTES: "52428800"
- CLERUM_PERSONALIZATION_ENABLED: "false"
+ CLERUM_APPROVAL_TIMEOUT: '0'
+ CLERUM_MEMORY_ENABLED: 'true'
+ CLERUM_SESSION_STORE: 'sqlite'
+ CLERUM_SESSION_SEARCH_ENABLED: 'true'
+ CLERUM_SESSION_TTL_DAYS: '90'
+ CLERUM_SEARCH_RETENTION_DAYS: '90'
+ CLERUM_CONTEXT_MAX_TOKENS: '100000'
+ CLERUM_ENABLE_RESPONSE_ATTACHMENTS: 'true'
+ CLERUM_ATTACHMENT_MAX_COUNT: '3'
+ CLERUM_ATTACHMENT_MAX_BYTES: '52428800'
+ CLERUM_PERSONALIZATION_ENABLED: 'false'
# --- Auth configuration ---
# Enabled for defense in depth: runtimeEdgeGuard validates trusted edge caller
# headers, and HCC-managed NetworkPolicies restrict pod reachability.
- CLERUM_ENABLE_AUTH: "true"
- CLERUM_AUTH_JWT_ISSUER: "control-api"
- CLERUM_AUTH_JWT_AUDIENCE: "rpc-proxy"
+ CLERUM_ENABLE_AUTH: 'true'
+ CLERUM_AUTH_JWT_ISSUER: 'control-api'
+ CLERUM_AUTH_JWT_AUDIENCE: 'rpc-proxy'
# Public key must match CONTROL_API_RPC_JWT_PRIVATE_KEY pair (from jwt-signing-keys.yaml)
# and RPC_PROXY_JWT_PUBLIC_KEY (from rpc-proxy-secrets). All three must be the same key pair.
CLERUM_AUTH_JWT_PUBLIC_KEY: |
diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md
index 61acc0058..7df555478 100644
--- a/docs/architecture/overview.md
+++ b/docs/architecture/overview.md
@@ -749,13 +749,22 @@ Both support Bearer token authentication via `Authorization` header.
#### Server Discovery (Production)
-mcp-host polls host-context-controller REST API to discover MCP servers:
+mcp-host polls the host-context-controller REST API with its existing
+caller-bound access JWT. HCC resolves the live Host and its Context from that
+identity; the caller never supplies a Context selector:
```
-mcp-host ──GET /api/v1/mcpservers/context/{contextRef}──▶ host-context-controller
- ◀──── { servers: McpServerInfo[], timestamp }────
+mcp-host ──GET /api/v2/hosts/self/mcpservers + Bearer Host JWT──▶ HCC gateway
+ ◀──── Host-scoped { servers: McpServerInfo[], timestamp }────
```
+When an authenticated McpServer needs a credential, mcp-host posts the server
+name to `/api/v2/hosts/self/mcpservers/credential` with the same JWT. HCC
+checks the live Host → Context grant before reading the referenced Secret.
+The former caller-selected Context and global `/auth` routes are retired with
+HTTP 410; the remaining global v1 inventory is metadata-only transitional
+surface for the separately reviewed mcp-proxy PR2 and is not used by mcp-host.
+
Polling interval: 30 seconds (configurable via `CLERUM_CONTEXT_MAPPER_POLL_INTERVAL`)
On each poll, mcp-host compares new server list with previous state and:
@@ -1012,13 +1021,15 @@ One policy per (context, server) pair. Only allows traffic from the mcp-host nam
### REST API
-| Method | Path | Description |
-| ------ | ----------------------------------------- | ------------------------------------ |
-| `GET` | `/` | API information |
-| `GET` | `/health` | Health check |
-| `GET` | `/api/v1/mcpservers` | List ALL MCP servers |
-| `GET` | `/api/v1/mcpservers/context/{contextRef}` | List servers filtered by Context CRD |
-| `GET` | `/api/v1/mcpservers/{name}/auth` | Get auth token for a server |
+| Method | Path | Description |
+| ------ | ------------------------------------------ | ---------------------------------------------------------------------------------- |
+| `GET` | `/` | API information |
+| `GET` | `/health` | Health check |
+| `GET` | `/api/v2/hosts/self/mcpservers` | List MCP servers granted to the authenticated Host |
+| `POST` | `/api/v2/hosts/self/mcpservers/credential` | Return a credential only after the live Host → Context → McpServer check |
+| `GET` | `/api/v1/mcpservers` | Transitional metadata-only system inventory; no Secret fields; PR2 review required |
+| `GET` | `/api/v1/mcpservers/context/{contextRef}` | Retired caller-selected route; HTTP 410 |
+| `GET` | `/api/v1/mcpservers/{name}/auth` | Retired unbound credential route; HTTP 410 |
**Server info response**:
@@ -1028,23 +1039,25 @@ One policy per (context, server) pair. Only allows traffic from the mcp-host nam
{
"name": "mongodb-server",
"description": "MongoDB MCP server",
- "contextRef": "context1",
"transport": { "type": "streamableHttp", "url": "http://...:3000/mcp" },
- "auth": { "type": "bearer", "secretRef": "...", "secretKey": "..." },
"enabled": true,
+ "authRequired": true,
+ "credentialRevision": "opaque-revision",
"status": {
"deployed": true,
"ready": true,
- "message": "1/1 replicas ready"
+ "message": "ready"
}
}
],
- "contextRef": "context1",
"timestamp": "2024-01-15T10:30:00.000Z"
}
```
-**Context-based filtering**: Reads the Context CRD's `mcpServers` allowlist and only returns servers that appear in that list.
+**Host-based authorization**: HCC derives the current Host's Context from the
+verified JWT and live Host object, checks the Context's `mcpServers` allowlist,
+and returns only the sanitized v2 DTO. Context names, auth selectors, and
+Secret references never appear in the Host response.
**Deployment status**: The reconciler checks the actual Deployment status (`readyReplicas`) to populate the `deployed` and `ready` fields.
diff --git a/docs/architecture/platform-topology.md b/docs/architecture/platform-topology.md
index d120a5739..13af8a7e2 100644
--- a/docs/architecture/platform-topology.md
+++ b/docs/architecture/platform-topology.md
@@ -574,8 +574,8 @@ flowchart TD
| **2. Intent Decomposition** | WRC (watches WorkflowRecipe CRDs) | Validates recipe, decomposes into 3 intent classes: MCP Intent → McpServer CRDs, Sandbox Intent → non-MCP workloads, Access-Policy Intent → Context patches + binding annotations | control-plane → mcp-server, sandbox-recipes |
| **3. Sanitization Gate** | HCC: MCP Server Sync | **`managed: true` only** (stdio recipe servers, control-api servers). Coerces the McpServer CRD (imagePullPolicy, non-root gid/fsGroup, capability + env stripping, unit-naive resource clamping), then runs the two blocking checks — Secret validation and the image allowlist (audit-only unless enforce mode). Blocked → no Deployment, `status.conditions[Ready]=False`. `managed: false` servers (WRC's HTTP/SSE recipe workloads) skip the gate entirely — HCC only validates the Secret and marks them Ready. See §5.1 | control-plane → mcp-server |
| **4. NetworkPolicy Generation** | HCC + WRC + static deploy overlays | HCC watches Context/McpServer intent and generates Context/MCP policies; WRC generates policies only for WRC-owned workflow runtime pods; static deploy owns platform infrastructure policies such as GKE mcp-host API egress | control-plane → mcp-host, mcp-server, sandbox-recipes |
-| **5. Discovery** | HCC REST API | Internal cache updates when MCP server Deployment is running. mcp-host polls Discovery API (`GET /api/v1/mcpservers/context/{contextRef}`) | control-plane (8081) → mcp-host |
-| **6. Tool Availability** | mcp-host | Agent discovers new MCP server tools. L2 NetworkPolicy allows traffic. Auth token from Discovery API authenticates the agent to the MCP server | mcp-host → mcp-server |
+| **5. Discovery** | HCC REST API | Internal cache updates when MCP server Deployment is running. mcp-host polls `GET /api/v2/hosts/self/mcpservers` with its caller-bound access JWT; HCC derives the live Host and Context and returns only the granted set. | control-plane (8081) → mcp-host |
+| **6. Tool Availability** | mcp-host | Agent discovers new MCP server tools. L2 NetworkPolicy allows traffic. For an authenticated server, mcp-host posts the server name to the v2 credential route; HCC authorizes the live Host → Context grant before reading the Secret. | mcp-host → mcp-server |
### 7.4 Trust Behavior Properties
diff --git a/docs/crds/workflowrecipe.md b/docs/crds/workflowrecipe.md
index f421cec34..7d8fbdec8 100644
--- a/docs/crds/workflowrecipe.md
+++ b/docs/crds/workflowrecipe.md
@@ -222,7 +222,7 @@ Workloads with a `transport` field are automatically registered as MCP servers.
- Non-MCP workloads (StatefulSets, CronJobs, Jobs, PVCs, Secrets, ConfigMaps) → created directly with `ownerRef → WorkflowRecipe`
- MCP workloads (those with `transport` field) → creates McpServer CRDs with `ownerRef → WorkflowRecipe`. The `managed` flag is **transport-dependent**: `managed: true` only for `transport.type: stdio`; `streamableHttp` and `sse` workloads get `managed: false` and the WRC creates their Deployment + Service itself.
2. **MCP Server Sync** (within HCC) watches McpServer CRDs and creates Deployment + Service for each `managed: true` McpServer — i.e. for stdio recipe workloads (where it also injects the stdio-bridge sidecar) and for standalone managed servers. `managed: false` McpServer CRDs are registration/discovery records only; their runtime is owned by whoever created it (the WRC, for HTTP transport workloads).
-3. **Discovery**: mcp-host discovers ALL MCP servers (standalone, recipe-based, and infrastructure) through HCC's Discovery API
+3. **Discovery**: mcp-host discovers only the MCP servers granted to its authenticated Host through HCC's Host-scoped v2 Discovery API; the caller does not select a Context. The global v1 inventory is a metadata-only transitional system surface under separate PR2 review.
See [Architecture Reference §13](../architecture/platform-topology.md#13-deployment-responsibility-matrix) for the complete deployment responsibility matrix.
@@ -325,16 +325,16 @@ flowchart TB
| Red (security) | Security resources | NetworkPolicies |
| Gray (storage) | Supporting resources | PVCs, Secrets, ConfigMaps |
-| Node | Detail |
-| ---------------------- | -------------------------------------------------------------------------------------------------- |
-| **WRC** | WorkflowRecipe Reconciler — its own `workflow-recipes` Deployment in `control-plane` |
-| **MCP Server Sync** | McpServer Reconciler — watches McpServer CRDs, creates Deployments + Services |
-| **MCPAccessCtrl Sync** | Context Reconciler — manages access NetworkPolicies |
-| **MCP Host Sync** | Host CRD lifecycle management |
-| **Discovery API** | REST endpoint: `GET /api/v1/mcpservers/context/{ref}` |
-| **MCP Server Pool** | All MCP servers: recipe-created, standalone, and infrastructure |
-| **McpServer CRDs** | Created by the WRC for MCP workloads (`ownerRef → WorkflowRecipe`; `managed: true` only for stdio) |
-| **MCP Server A/B** | Standalone or recipe-created MCP servers (MongoDB, Airtable, etc.) |
+| Node | Detail |
+| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **WRC** | WorkflowRecipe Reconciler — its own `workflow-recipes` Deployment in `control-plane` |
+| **MCP Server Sync** | McpServer Reconciler — watches McpServer CRDs, creates Deployments + Services |
+| **MCPAccessCtrl Sync** | Context Reconciler — manages access NetworkPolicies |
+| **MCP Host Sync** | Host CRD lifecycle management |
+| **Discovery API** | Host-scoped REST endpoints: `GET /api/v2/hosts/self/mcpservers` and `POST /api/v2/hosts/self/mcpservers/credential`; v1 Context/auth routes are HTTP 410 tombstones |
+| **MCP Server Pool** | All MCP servers: recipe-created, standalone, and infrastructure |
+| **McpServer CRDs** | Created by the WRC for MCP workloads (`ownerRef → WorkflowRecipe`; `managed: true` only for stdio) |
+| **MCP Server A/B** | Standalone or recipe-created MCP servers (MongoDB, Airtable, etc.) |
> **WRC reconciliation model**: Recipes are deployed either by creating WorkflowRecipe CRDs (via control-api or `kubectl apply`) or through the WRC's MCP `deploy_recipe` tool. Either way, the WRC watches the resulting CRDs and reconciles them — it produces declarative intent (McpServer CRDs, workloads, Context patches), and the HCC's other synchronizers materialize them into runtime state.
diff --git a/host-context-controller/README.md b/host-context-controller/README.md
index 8ee40e981..e42a7cd5c 100644
--- a/host-context-controller/README.md
+++ b/host-context-controller/README.md
@@ -156,7 +156,10 @@ On startup, a full host reconciliation pass runs and deletes orphaned host runti
## REST API
-The host-context-controller returns curated `McpServerInfo` objects that strip deployment-specific fields and include operator-managed status.
+The Host-facing MCP contract is authenticated and Host-scoped. HCC verifies the
+runtime bearer, resolves the live Host and its live Context server-side, and
+checks the Context grant before it reads credential material. Callers do not
+supply a Context reference.
### Health Check
@@ -170,7 +173,7 @@ GET /health
The server also exposes `GET /` (API information), `GET /ready` (readiness; 503 until the controller has started), `GET /metrics` (Prometheus), and `GET /api/v1/desktop/:hostRef` (desktop status; requires the `CONTEXT_MAPPER_DESKTOP_API_TOKEN` bearer token — the check is skipped when that variable is empty).
-### List All McpServers
+### Temporary system inventory (PR 2 compatibility)
```
GET /api/v1/mcpservers
@@ -181,19 +184,13 @@ GET /api/v1/mcpservers
"servers": [
{
"name": "mongodb-server",
- "description": "MongoDB MCP Server",
"contextRef": "context1",
"transport": {
"type": "sse",
"url": "http://mongodb-server.mcp-server.svc.cluster.local:3000/sse"
},
- "auth": {
- "type": "bearer",
- "secretRef": "mcp-mongodb-credentials",
- "secretKey": "auth-token"
- },
"enabled": true,
- "status": { "deployed": true, "ready": true, "message": "Running" }
+ "status": { "deployed": true, "ready": true }
}
],
"contextRef": "*",
@@ -201,36 +198,85 @@ GET /api/v1/mcpservers
}
```
-### List McpServers by Context
+This anonymous, metadata-only route is retained temporarily for the existing
+`mcp-proxy` poller. It is not the mcp-host discovery contract and exposes no
+auth selector or Secret metadata. Its removal or authentication belongs to the
+separate PR 2 migration.
+
+### Authenticated Host inventory
```
-GET /api/v1/mcpservers/context/:contextRef
+GET /api/v2/hosts/self/mcpservers
+Authorization: Bearer <mcp-host-runtime-token>
```
-Returns only McpServers that are listed in the specified Context CRD's `spec.mcpServers` array and are enabled. If the Context CRD does not exist, returns an empty list.
+The response contains only enabled McpServers granted by the authenticated
+Host's live Context. It omits `contextRef`, auth selectors, and Secret metadata.
+An authenticated server includes an opaque `credentialRevision` so mcp-host can
+retire a credential before admitting a changed revision.
+
+The verifier accepts only RS256 tokens from the configured Control API issuer
+with an exact HCC audience set (HCC-only, or the bounded HCC + workflow
+migration pair), one `hostRefs` entry, the matching `host_uid`, and the single
+`mcp:credential:read` capability. The historical workflow scope/standalone
+recipe claims identify the reused runtime-token family; they do not grant a
+Context. HCC derives that authorization from the live Host and Context objects.
+
+```json
+{
+ "servers": [
+ {
+ "name": "mongodb-server",
+ "transport": {
+ "type": "sse",
+ "url": "http://mongodb-server.mcp-server.svc.cluster.local:3000/sse"
+ },
+ "enabled": true,
+ "status": { "deployed": true, "ready": true },
+ "authRequired": true,
+ "credentialRevision": "opaque-revision"
+ }
+ ],
+ "timestamp": "2026-02-14T15:11:12.000Z"
+}
+```
-### Get Auth Token
+### Authenticated Host credential
```
-GET /api/v1/mcpservers/:name/auth
+POST /api/v2/hosts/self/mcpservers/credential
+Authorization: Bearer <mcp-host-runtime-token>
+Content-Type: application/json
+
+{ "serverName": "mongodb-server" }
```
Response (with auth):
```json
-{ "token": "secret-token-value" }
+{ "token": "credential-value", "credentialRevision": "opaque-revision" }
```
Response (no auth configured):
```json
-{ "token": null, "message": "No auth configured for this server" }
+{ "token": null, "credentialRevision": "opaque-revision" }
```
+HCC returns the same opaque `404 {"error":"not_found"}` for an ungranted,
+missing, disabled, or cross-Context server name. It performs the grant check
+before any Secret value read and revalidates the live authority snapshot after
+the read. Protected responses are non-cacheable.
+
+The legacy caller-selected routes
+`GET /api/v1/mcpservers/context/:contextRef` and
+`GET /api/v1/mcpservers/:name/auth` are tombstoned with a generic HTTP 410 at
+both the gateway and HCC application layers; there is no v1 fallback.
+
## Environment Variables
-HCC reads **60** environment variables (`src/config.ts`, `src/gfsConfig.ts`,
-`src/logger.ts`, `src/k8sApiCidrs.ts`). Defaults below are the literal fallbacks
+HCC reads environment variables from `src/config.ts`, `src/gfsConfig.ts`,
+`src/logger.ts`, and `src/k8sApiCidrs.ts`. Defaults below are the literal fallbacks
in code; where the deploy manifest overrides one, that is noted.
**Parsing semantics.** `getEnv(key, default)` uses `process.env[key] ?? default`,
@@ -254,16 +300,16 @@ a permissive policy — see the NetworkPolicy and GFS tables:
### Namespaces
-| Variable | Default | Description |
-| ---------------------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `CONTEXT_MAPPER_NAMESPACE` | `mcp-server` | Where `McpServer` / `Context` CRDs live and managed server workloads are created. |
-| `CONTEXT_MAPPER_CONTROL_PLANE_NAMESPACE` | `control-plane` | Where control-plane gateway services live. |
-| `CONTEXT_MAPPER_HOST_NAMESPACE` | `mcp-host` | Where mcp-host pods run (drives NetworkPolicy generation). |
-| `CONTEXT_MAPPER_GFS_NAMESPACE` | `gfs` | Where the GlobalFileSystem controller (gfsc) runs. |
-| `CONTEXT_MAPPER_RPC_PROXY_NAMESPACE` | `rpc-proxy` | Where rpc-proxy runs (L2 egress policy generation). |
-| `CONTEXT_MAPPER_CHANNELS_NAMESPACE` | `channels` | Per-Host channel-reader Deployments/Services. |
-| `CONTEXT_MAPPER_SANDBOX_NAMESPACE` | `sandbox-recipes` | Workflow-recipe namespace. Read only by the GFS factory. |
-| `HCC_TARGET_NAMESPACE` | `mcp-host` | Namespace HCC names when asking control-api for shared 1st-party mcp-host credentials. **Exits 1** if it resolves empty; warns if outside mcp-host/sandbox-recipes. |
+| Variable | Default | Description |
+| ---------------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `CONTEXT_MAPPER_NAMESPACE` | `mcp-server` | Where `McpServer` / `Context` CRDs live and managed server workloads are created. |
+| `CONTEXT_MAPPER_CONTROL_PLANE_NAMESPACE` | `control-plane` | Where control-plane gateway services live. |
+| `CONTEXT_MAPPER_HOST_NAMESPACE` | `mcp-host` | Where mcp-host pods run (drives NetworkPolicy generation). |
+| `CONTEXT_MAPPER_GFS_NAMESPACE` | `gfs` | Where the GlobalFileSystem controller (gfsc) runs. |
+| `CONTEXT_MAPPER_RPC_PROXY_NAMESPACE` | `rpc-proxy` | Where rpc-proxy runs (L2 egress policy generation). |
+| `CONTEXT_MAPPER_CHANNELS_NAMESPACE` | `channels` | Per-Host channel-reader Deployments/Services. |
+| `CONTEXT_MAPPER_SANDBOX_NAMESPACE` | `sandbox-recipes` | Workflow-recipe namespace. Read only by the GFS factory. |
+| `HCC_TARGET_NAMESPACE` | `mcp-host` | Namespace HCC names when asking control-api for caller-bound 1st-party mcp-host credentials. It must exactly equal `CONTEXT_MAPPER_HOST_NAMESPACE`; HCC exits 1 otherwise. |
### MCP server provisioning
@@ -298,6 +344,15 @@ a permissive policy — see the NetworkPolicy and GFS tables:
| `CONTEXT_MAPPER_HOST_RESYNC_SEC` | `300` | Periodic Host `fullReconcile` (seconds); guards against dropped watch events and drives auth-degraded self-heal. `0` disables. |
| `HCC_MCP_HOST_RUNTIME_BOOTSTRAP_REFRESH_BEFORE_SEC` | `900` | How long before expiry HCC refreshes the mcp-host bootstrap credential Secret. |
+### mcp-host API authorization
+
+| Variable | Default | Description |
+| ---------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
+| `HCC_MCP_HOST_JWT_PUBLIC_KEY` | `` (empty) | RS256 public key used to verify protected v2 Host MCP requests. HCC fails startup when it is absent, malformed, private, or a placeholder. |
+| `HCC_MCP_HOST_JWT_ISSUER` | `control-api` | Exact issuer accepted for protected v2 Host MCP requests. |
+| `HCC_MCP_HOST_JWT_MAX_TTL_SECONDS` | `600` | Maximum accepted `exp - iat`; the deploy manifest sources this from Control API's access-token TTL contract. |
+| `HCC_MCP_HOST_API_RATE_LIMIT_PER_MINUTE` | `120` | Per verified Host UID and action fixed-window limit for inventory and credential requests. |
+
### Desktop (Host CRD `spec.desktop`)
| Variable | Default | Description |
@@ -393,11 +448,11 @@ Read by `src/gfsConfig.ts`. Invalid values **throw at startup** rather than sile
Parsed only when `CLERUM_DEV_MODE` is truthy. A JSON parse failure logs an error and yields an empty result rather than crashing.
-| Variable | Default | Description |
-| -------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `CLERUM_MCP_SERVERS` | `[]` | JSON array of McpServer objects. |
-| `CLERUM_CONTEXTS` | `[]` | JSON array of Context objects. When set, `GET /api/v1/mcpservers/context/:contextRef` filters by the Context's `mcpServers` allow-list; when unset it falls back to matching `spec.contextRef`. |
-| `CLERUM_MCP_AUTH` | `{}` | JSON object mapping MCP server name → auth token. |
+| Variable | Default | Description |
+| -------------------- | ------- | ----------------------------------------------------------------------------------------------------------------- |
+| `CLERUM_MCP_SERVERS` | `[]` | JSON array of McpServer objects. |
+| `CLERUM_CONTEXTS` | `[]` | JSON array of Context objects used by the development provider. Caller-selected Context discovery is not exposed. |
+| `CLERUM_MCP_AUTH` | `{}` | JSON object mapping MCP server name → auth token for development-provider fixtures. |
## Kubernetes RBAC
@@ -433,10 +488,18 @@ In `mcp-host` (`deploy/base/mcp-host/rbac.yaml`), the controller additionally ma
Run host-context-controller locally without Kubernetes by providing MCP servers via environment variables. In dev mode, no reconciliation occurs (no Deployments, Services, or NetworkPolicies are created).
+Startup still requires a real trusted Control API RS256 public key in
+`HCC_MCP_HOST_JWT_PUBLIC_KEY`, including in dev mode. Export it from the
+approved local public-key source before either command below. `.env.example`
+deliberately does not include a placeholder key, and HCC has no insecure
+verifier fallback.
+
```bash
# Install dependencies
npm install
+# Load HCC_MCP_HOST_JWT_PUBLIC_KEY from the trusted Control API public-key source.
+
# Option 1: Use .env file (recommended)
cp .env.example .env
# Edit .env with your servers
@@ -455,18 +518,21 @@ CLERUM_CONTEXTS='[{"name":"dev-context","namespace":"dev","spec":{"contextId":"d
CLERUM_MCP_AUTH='{"github":"ghp_your_token_here"}'
```
-In dev mode, `GET /api/v1/mcpservers/context/:contextRef` uses `CLERUM_CONTEXTS` when it is set: it returns the enabled servers named in the matching Context's `mcpServers` list, and returns an empty list if no Context with that name was loaded. When `CLERUM_CONTEXTS` is unset, it falls back to returning the enabled servers whose own `spec.contextRef` matches.
+Dev mode retains the metadata-only global v1 inventory for local `mcp-proxy`
+compatibility. It does not restore either caller-selected v1 Host route. The
+protected v2 contract requires live Kubernetes Host/Context authority and
+therefore fails closed when that authority is unavailable.
### Production Mode (with Kubernetes)
-Run against the cluster in your current kubeconfig (watches K8s for McpServer and Context CRDs) with `CLERUM_DEV_MODE` unset. Outside dev mode the process also requires `INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET` — without it, startup aborts with `[HCC] FATAL: INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET env var is required` and exit code 1:
+Run against the cluster in your current kubeconfig (watches K8s for McpServer and Context CRDs) with `CLERUM_DEV_MODE` unset. Production startup requires both the existing `INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET` signing material and the real Control API public key in `HCC_MCP_HOST_JWT_PUBLIC_KEY`. Load both from their approved sources before starting; missing or invalid verifier material fails startup closed.
```bash
make build
-INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET=<hmac-secret> npm start
+npm start
```
-`make dev` also works, but only if a `.env` file exists (see above) — it is the same target, so it aborts when `.env` is absent. Leave `CLERUM_DEV_MODE` out of that `.env` and set `INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET` in it to run against a real cluster.
+`make dev` also works, but only if a `.env` file exists (see above) — it is the same target, so it aborts when `.env` is absent. Leave `CLERUM_DEV_MODE` out of that `.env` and load both required values through the approved local configuration path to run against a real cluster.
## Deployment
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index e9b28c157..a30df3efb 100644
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@ -14,9 +14,11 @@
"@clerum/network-policy-core": "file:../packages/network-policy-core",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
"@kubernetes/client-node": "^1.0.0",
+ "jsonwebtoken": "^9.0.3",
"prom-client": "^15.1.3"
},
"devDependencies": {
+ "@types/jsonwebtoken": "^9.0.10",
"@types/node": "^20.10.0",
"ts-node": "^10.9.2",
"typescript": "^5.3.0",
@@ -580,6 +582,24 @@
"integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==",
"license": "MIT"
},
+ "node_modules/@types/jsonwebtoken": {
+ "version": "9.0.10",
+ "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz",
+ "integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/ms": "*",
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/ms": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/node": {
"version": "20.19.39",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.39.tgz",
@@ -896,6 +916,12 @@
"integrity": "sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==",
"license": "MIT"
},
+ "node_modules/buffer-equal-constant-time": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
+ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
+ "license": "BSD-3-Clause"
+ },
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
@@ -1005,6 +1031,15 @@
"node": ">= 0.4"
}
},
+ "node_modules/ecdsa-sig-formatter": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
+ "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "safe-buffer": "^5.0.1"
+ }
+ },
"node_modules/end-of-stream": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
@@ -1332,6 +1367,49 @@
"node": ">=18.0.0"
}
},
+ "node_modules/jsonwebtoken": {
+ "version": "9.0.3",
+ "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",
+ "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",
+ "license": "MIT",
+ "dependencies": {
+ "jws": "^4.0.1",
+ "lodash.includes": "^4.3.0",
+ "lodash.isboolean": "^3.0.3",
+ "lodash.isinteger": "^4.0.4",
+ "lodash.isnumber": "^3.0.3",
+ "lodash.isplainobject": "^4.0.6",
+ "lodash.isstring": "^4.0.1",
+ "lodash.once": "^4.0.0",
+ "ms": "^2.1.1",
+ "semver": "^7.5.4"
+ },
+ "engines": {
+ "node": ">=12",
+ "npm": ">=6"
+ }
+ },
+ "node_modules/jwa": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
+ "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer-equal-constant-time": "^1.0.1",
+ "ecdsa-sig-formatter": "1.0.11",
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "node_modules/jws": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
+ "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
+ "license": "MIT",
+ "dependencies": {
+ "jwa": "^2.0.1",
+ "safe-buffer": "^5.0.1"
+ }
+ },
"node_modules/lightningcss": {
"version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
@@ -1593,6 +1671,48 @@
"url": "https://opencollective.com/parcel"
}
},
+ "node_modules/lodash.includes": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
+ "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isboolean": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
+ "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isinteger": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
+ "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isnumber": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
+ "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isplainobject": {
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
+ "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isstring": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
+ "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.once": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
+ "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
+ "license": "MIT"
+ },
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
@@ -1846,6 +1966,38 @@
"@rolldown/binding-win32-x64-msvc": "1.1.5"
}
},
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/siginfo": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index 17c98b81a..63c6499b6 100644
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@ -27,9 +27,11 @@
"@clerum/network-policy-core": "file:../packages/network-policy-core",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
"@kubernetes/client-node": "^1.0.0",
+ "jsonwebtoken": "^9.0.3",
"prom-client": "^15.1.3"
},
"devDependencies": {
+ "@types/jsonwebtoken": "^9.0.10",
"@types/node": "^20.10.0",
"ts-node": "^10.9.2",
"typescript": "^5.3.0",
diff --git a/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts b/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts
index 8200f6c2e..83a9eba9c 100644
--- a/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts
+++ b/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts
@@ -58,6 +58,7 @@ function makeHost(): HostCRD {
return {
name: 'team-mission',
namespace: 'mcp-host',
+ uid: 'team-mission-uid',
spec: {
host: 'team-mission',
contextRef: 'team-mission-ctx',
@@ -178,10 +179,11 @@ function runtimeSecretAnnotations(host = makeHost(), refreshBefore = '2999-01-01
'clerum.io/runtime-token-host-binding-hash': helper.runtimeTokenHostBindingHash(host),
'clerum.io/runtime-token-scope-hash': helper.runtimeTokenScopeHash(host),
'clerum.io/runtime-token-issuer': 'control-api',
- 'clerum.io/runtime-token-audience': 'workflow-approvals',
- 'clerum.io/runtime-token-schema-version': '2',
+ 'clerum.io/runtime-token-audience': 'host-context-controller,workflow-approvals',
+ 'clerum.io/runtime-token-schema-version': '3',
'clerum.io/gfs-token-expected-subject': `host:1st:${host.namespace}/${host.name}`,
'clerum.io/gfs-token-capability-set-hash': helper.gfsCapabilitySetHash(),
+ 'clerum.io/gfs-token-host-uid': host.uid!,
'clerum.io/runtime-token-refresh-before': refreshBefore,
'clerum.io/gfs-token-refresh-before': '2999-01-01T00:00:00.000Z',
}
@@ -348,7 +350,7 @@ describe('HostReconciler runtime credential Secret revision', () => {
expect(coreApi.replaceNamespacedSecret).toHaveBeenCalledTimes(1)
expect(result.revision).not.toBe(legacyRevision)
expect(replacedRuntimeSecret(coreApi).metadata?.annotations).toMatchObject({
- 'clerum.io/runtime-token-schema-version': '2',
+ 'clerum.io/runtime-token-schema-version': '3',
'clerum.io/runtime-token-rollout-required': 'true',
})
})
@@ -690,8 +692,8 @@ describe('HostReconciler runtime credential Secret revision', () => {
const replaceBody = replacedRuntimeSecret(coreApi)
expect(replaceBody.metadata?.annotations).toMatchObject({
'clerum.io/runtime-token-issuer': 'control-api',
- 'clerum.io/runtime-token-audience': 'workflow-approvals',
- 'clerum.io/runtime-token-schema-version': '2',
+ 'clerum.io/runtime-token-audience': 'host-context-controller,workflow-approvals',
+ 'clerum.io/runtime-token-schema-version': '3',
})
})
diff --git a/host-context-controller/src/config.ts b/host-context-controller/src/config.ts
index 7b7632b75..f4869b291 100644
--- a/host-context-controller/src/config.ts
+++ b/host-context-controller/src/config.ts
@@ -147,6 +147,12 @@ export interface Config {
// 1st-party mcp-host credentials.
hccTargetNamespace: string
+ // Control API RS256 verifier contract for Host-scoped MCP API routes.
+ mcpHostJwtPublicKey: string
+ mcpHostJwtIssuer: string
+ mcpHostJwtMaxTtlSeconds: number
+ mcpHostApiRateLimitPerMinute: number
+
// URL of the nginx gateway that mediates mcp-host → control-api traffic.
// Injected into mcp-host pods as MCP_HOST_GATEWAY_URL. Per the architecture
// diagram this is the "nginx (only /mcp-host)" allowlist-proxy.
@@ -674,6 +680,14 @@ export const config: Config = {
// HCC provisions the shared 1st-party mcp-host credentials by default.
hccTargetNamespace: getEnv('HCC_TARGET_NAMESPACE')?.trim() || 'mcp-host',
+ mcpHostJwtPublicKey: getEnv('HCC_MCP_HOST_JWT_PUBLIC_KEY', '')!,
+ mcpHostJwtIssuer: getEnv('HCC_MCP_HOST_JWT_ISSUER', 'control-api')!,
+ mcpHostJwtMaxTtlSeconds: Math.max(1, getEnvInt('HCC_MCP_HOST_JWT_MAX_TTL_SECONDS', 600)),
+ mcpHostApiRateLimitPerMinute: Math.max(
+ 1,
+ getEnvInt('HCC_MCP_HOST_API_RATE_LIMIT_PER_MINUTE', 120)
+ ),
+
// URL of the nginx gateway that mediates mcp-host → control-api traffic.
// Injected into mcp-host pods as MCP_HOST_GATEWAY_URL. Per the architecture
// diagram this is the "nginx (only /mcp-host)" allowlist-proxy.
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index 5730e5553..f433685e4 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -212,11 +212,12 @@ const RUNTIME_TOKEN_SCHEMA_VERSION_ANNOTATION = 'clerum.io/runtime-token-schema-
const RUNTIME_TOKEN_BOOTSTRAP_STATE_ANNOTATION = 'clerum.io/runtime-token-bootstrap-state'
const RUNTIME_TOKEN_ROLLOUT_REQUIRED_ANNOTATION = 'clerum.io/runtime-token-rollout-required'
const RUNTIME_TOKEN_ISSUER = 'control-api'
-const RUNTIME_TOKEN_AUDIENCE = 'workflow-approvals'
-// v2 binds the GFS token to the concrete Host CRD instead of the historical
-// fleet-wide `mcp-host/standalone` sentinel. The version change makes existing
-// Secrets fail the contract check so HCC rotates them and rolls each Host.
-const RUNTIME_TOKEN_SCHEMA_VERSION = '2'
+const RUNTIME_TOKEN_AUDIENCE = 'host-context-controller,workflow-approvals'
+// v3 extends the existing first-party access/refresh token material with the
+// exact HCC audience, immutable MCP credential capability, and live Host UID.
+// Existing Secrets therefore fail the contract check and rotate onto the
+// caller-bound contract instead of remaining workflow-only.
+const RUNTIME_TOKEN_SCHEMA_VERSION = '3'
const RUNTIME_TOKEN_BOOTSTRAP_STATE_FRESH = 'fresh'
const RUNTIME_TOKEN_BOOTSTRAP_STATE_CONSUMED = 'consumed'
// Deployments affected by the historical stringData/data hashing bug can carry
@@ -1268,6 +1269,7 @@ export class HostReconciler {
const tokens = await issueMcpHostRuntimeTokens(
host.name,
+ host.uid ?? '',
this.resolveWorkflowControlScopesForHost(host, hasChannelIngress)
)
const gfs = await mintHostGfsToken({ name: host.name, namespace: host.namespace })
diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.ts
index 2aa0ccea4..c96d63ccd 100644
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@ -3,6 +3,9 @@ import { HostFleetReconcileError } from './hostReconciler'
import { HostK8sRequestTimeoutError } from './k8s/hostK8sApiClient'
import {
McpServerWatcher,
+ createMcpAuthorizationStore,
+ getContext,
+ isMcpAuthorizationNotFound,
externalEgressResyncDelayMs,
listAllCommunicationChannels,
listAllHosts,
@@ -25,6 +28,10 @@ function deferred<T = void>(): {
const mocks = vi.hoisted(() => {
const listNamespacedCustomObject = vi.fn()
+ const getNamespacedCustomObject = vi
+ .fn()
+ .mockRejectedValue(Object.assign(new Error('not found'), { code: 404 }))
+ const readNamespacedSecret = vi.fn()
const ensureDefaultPolicies = vi.fn().mockResolvedValue(undefined)
const netPolFullReconcile = vi.fn().mockResolvedValue(undefined)
const serverFullReconcile = vi.fn().mockResolvedValue(undefined)
@@ -36,6 +43,8 @@ const mocks = vi.hoisted(() => {
const createAdministrativeOutcomeReporter = vi.fn().mockReturnValue(undefined)
return {
listNamespacedCustomObject,
+ getNamespacedCustomObject,
+ readNamespacedSecret,
ensureDefaultPolicies,
netPolFullReconcile,
serverFullReconcile,
@@ -88,6 +97,7 @@ vi.mock('@kubernetes/client-node', () => {
makeApiClient(api: unknown): unknown {
if (api === CustomObjectsApi) {
return {
+ getNamespacedCustomObject: mocks.getNamespacedCustomObject,
listNamespacedCustomObject: async (request: { plural?: string }, options?: unknown) => {
if (request.plural === 'hosts') mocks.hostListCallOptions(options)
const response = await mocks.listNamespacedCustomObject(request)
@@ -109,6 +119,9 @@ vi.mock('@kubernetes/client-node', () => {
},
}
}
+ if (api === CoreV1Api) {
+ return { readNamespacedSecret: mocks.readNamespacedSecret }
+ }
return {}
}
}
@@ -207,6 +220,56 @@ beforeEach(() => {
mocks.hostReconcileHosts.mockReset().mockResolvedValue(undefined)
})
+describe('MCP authorization store Kubernetes 404 normalization', () => {
+ const provider = {
+ getAllServerInfos: () => [],
+ } as unknown as Parameters<typeof createMcpAuthorizationStore>[0]
+
+ beforeEach(() => {
+ mocks.getNamespacedCustomObject.mockReset()
+ mocks.readNamespacedSecret.mockReset()
+ })
+
+ it('treats ApiException.code=404 as absent for every CR authority read', async () => {
+ mocks.getNamespacedCustomObject.mockRejectedValue({ code: 404 })
+ const store = createMcpAuthorizationStore(provider)
+
+ await expect(store.readHost('host-a')).resolves.toBeNull()
+ await expect(store.readContext('context-a')).resolves.toBeNull()
+ await expect(store.readMcpServer('server-a')).resolves.toBeNull()
+ })
+
+ it('treats ApiException.code=404 as absent for metadata and full Secret reads', async () => {
+ mocks.readNamespacedSecret.mockRejectedValue({ code: 404 })
+ const store = createMcpAuthorizationStore(provider)
+
+ await expect(store.readSecretMetadata('server-token')).resolves.toBeNull()
+ await expect(store.readSecret('server-token')).resolves.toBeNull()
+ })
+
+ it('projects only Secret identity metadata for inventory even when Kubernetes returns data', async () => {
+ mocks.readNamespacedSecret.mockResolvedValue({
+ metadata: {
+ name: 'server-token',
+ namespace: 'mcp-server',
+ uid: 'secret-uid',
+ resourceVersion: '42',
+ },
+ data: { token: 'credential-bytes-must-not-cross-this-boundary' },
+ })
+ const store = createMcpAuthorizationStore(provider)
+
+ const metadata = await store.readSecretMetadata('server-token')
+ expect(metadata).toEqual({
+ name: 'server-token',
+ namespace: 'mcp-server',
+ metadata: { uid: 'secret-uid', resourceVersion: '42' },
+ })
+ expect(metadata).not.toHaveProperty('data')
+ expect(JSON.stringify(metadata)).not.toContain('credential-bytes-must-not-cross-this-boundary')
+ })
+})
+
describe('McpServerWatcher startup', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -448,6 +511,43 @@ describe('McpServerWatcher startup', () => {
})
})
+describe('getContext error semantics', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('preserves not-found semantics only for an authoritative 404', async () => {
+ mocks.getNamespacedCustomObject.mockRejectedValueOnce(
+ Object.assign(new Error('context absent'), { code: 404 })
+ )
+
+ await expect(getContext('missing-context')).resolves.toBeNull()
+ })
+
+ it('propagates non-404 API failures instead of converting discovery to an empty fleet', async () => {
+ const unavailable = Object.assign(new Error('apiserver unavailable'), {
+ response: { statusCode: 503 },
+ })
+ mocks.getNamespacedCustomObject.mockRejectedValueOnce(unavailable)
+
+ await expect(getContext('production-context')).rejects.toBe(unavailable)
+ })
+})
+
+describe('MCP authorization Kubernetes not-found classification', () => {
+ it.each([{ code: 404 }, { response: { statusCode: 404 } }])(
+ 'recognizes Kubernetes 404 shape %#',
+ error => {
+ expect(isMcpAuthorizationNotFound(error)).toBe(true)
+ }
+ )
+
+ it('does not classify authority failures as not-found', () => {
+ expect(isMcpAuthorizationNotFound({ code: 403 })).toBe(false)
+ expect(isMcpAuthorizationNotFound({ response: { statusCode: 503 } })).toBe(false)
+ })
+})
+
describe('McpServerWatcher external egress retries', () => {
const serverObject = {
metadata: { name: 'redis-tools', namespace: 'mcp-server' },
diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.ts
index 7fe7ceaec..c54215f07 100644
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@ -31,6 +31,14 @@ import { K8sGfsApi } from './k8s/gfsK8sApi'
import { makeHostK8sApiClient } from './k8s/hostK8sApiClient'
import { pvcName as sfsPvcName } from './k8s/sharedFileSystemFactory'
import { hostDeleteCleanupTotal, hostFleetRequestsTotal, hostWatchRecoverySeconds } from './metrics'
+import type {
+ AuthorityContext,
+ AuthorityHost,
+ AuthorityMcpServer,
+ AuthoritySecret,
+ AuthoritySecretMetadata,
+ McpAuthorizationStore,
+} from './mcpAuthorization'
import { NetworkPolicyReconciler } from './networkPolicyReconciler'
import { McpServerReconciler } from './reconciler'
import { SharedFileSystemReconciler } from './sharedFileSystemReconciler'
@@ -194,8 +202,6 @@ export interface McpServerProvider {
getAllServerInfos(): McpServerInfo[]
/** Get curated server info filtered by context (API consumers). Reads the Context CRD to determine allowed servers. */
getServerInfosByContext(contextRef: string): Promise<McpServerInfo[]>
- /** Get auth token for a server from K8s secret. */
- getAuthToken(serverName: string): Promise<string | undefined>
/** Set callback for when servers change. */
onChange(callback: () => void): void
start(): Promise<void>
@@ -350,50 +356,6 @@ export async function listAllHosts(): Promise<HostCRD[]> {
return (await listHostSnapshot()).hosts
}
-/**
- * Get auth token from a secret.
- */
-export async function getAuthToken(
- secretRef: string,
- secretKey?: string
-): Promise<string | undefined> {
- if (!coreApi) {
- throw new Error('K8s client not initialized - are you in dev mode?')
- }
-
- try {
- console.log(`[K8s] Getting auth token from secret: ${secretRef}`)
-
- const response = await coreApi.readNamespacedSecret({
- name: secretRef,
- namespace: config.namespace,
- })
-
- const data = response.data || {}
-
- // Try the specified key, or common key names
- const keys = secretKey ? [secretKey] : ['token', 'api-key', 'apiKey', 'password']
-
- for (const key of keys) {
- if (data[key]) {
- const token = Buffer.from(data[key], 'base64').toString('utf-8')
- console.log(`[K8s] Found auth token in secret (key: ${key})`)
- return token
- }
- }
-
- console.warn(`[K8s] No auth token found in secret ${secretRef}`)
- return undefined
- } catch (error) {
- if ((error as { response?: { statusCode?: number } }).response?.statusCode === 404) {
- console.warn(`[K8s] Secret not found: ${secretRef}`)
- return undefined
- }
- console.error(`[K8s] Failed to get auth token:`, error)
- return undefined
- }
-}
-
/**
* List all SharedFileSystem CRDs in the mcp-host namespace (the only namespace
* SharedFileSystems are allowed to live in, per CRD validation).
@@ -1636,17 +1598,6 @@ export class McpServerWatcher implements McpServerProvider {
.map(s => this.toServerInfo(s))
}
- /**
- * Get auth token for a server from K8s secret.
- */
- async getAuthToken(serverName: string): Promise<string | undefined> {
- const server = this.servers.get(serverName)
- if (!server?.spec.auth?.secretRef) {
- return undefined
- }
- return getAuthToken(server.spec.auth.secretRef, server.spec.auth.secretKey)
- }
-
/**
* Set callback for when servers change.
*/
@@ -2813,13 +2764,8 @@ export class McpServerWatcher implements McpServerProvider {
export class DevMcpServerProvider implements McpServerProvider {
private servers: Map<string, McpServerCRD> = new Map()
private contexts: Map<string, ContextCRD> = new Map()
- private authTokens: Map<string, string>
private changeCallback?: () => void
- constructor() {
- this.authTokens = config.devAuthTokens
- }
-
getAllServers(): McpServerCRD[] {
return [...this.servers.values()]
}
@@ -2873,10 +2819,6 @@ export class DevMcpServerProvider implements McpServerProvider {
.map(s => this.toServerInfo(s))
}
- async getAuthToken(serverName: string): Promise<string | undefined> {
- return this.authTokens.get(serverName)
- }
-
onChange(callback: () => void): void {
this.changeCallback = callback
}
@@ -2940,11 +2882,6 @@ export class DevMcpServerProvider implements McpServerProvider {
this.contexts.delete(contextId)
this.changeCallback?.()
}
-
- /** Set auth token for a server (useful for testing). */
- setAuthToken(serverName: string, token: string): void {
- this.authTokens.set(serverName, token)
- }
}
/**
@@ -2959,3 +2896,186 @@ export function createMcpServerProvider(): McpServerProvider {
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,
+ 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 --git a/host-context-controller/src/main.ts b/host-context-controller/src/main.ts
index 0e1502aa5..b898e0414 100644
--- a/host-context-controller/src/main.ts
+++ b/host-context-controller/src/main.ts
@@ -15,9 +15,12 @@ import { SecretInformer } from './informers/secretInformer'
import {
McpServerProvider,
McpServerWatcher,
+ createMcpAuthorizationStore,
createMcpServerProvider,
getKubeConfig,
} from './k8sClient'
+import { McpApiAuthenticator } from './mcpApiAuthentication'
+import { McpAuthorizationService } from './mcpAuthorization'
import { ContextMapperServer } from './server'
import { StatelessLifecycleTracker } from './statelessLifecycleTracker'
import {
@@ -88,12 +91,28 @@ async function main(): Promise<void> {
console.error('[HCC] FATAL: HCC_TARGET_NAMESPACE must not be empty')
process.exit(1)
}
- if (!['mcp-host', 'sandbox-recipes'].includes(config.hccTargetNamespace)) {
- console.warn(
- `[HCC] WARNING: HCC_TARGET_NAMESPACE=${config.hccTargetNamespace} is outside the default issuance namespaces`
+ if (config.hccTargetNamespace !== config.hostNamespace) {
+ console.error(
+ '[HCC] FATAL: HCC_TARGET_NAMESPACE must equal CONTEXT_MAPPER_HOST_NAMESPACE for caller-bound Host credentials'
)
+ process.exit(1)
}
+ let mcpAuthenticator: McpApiAuthenticator
+ try {
+ mcpAuthenticator = new McpApiAuthenticator({
+ publicKey: config.mcpHostJwtPublicKey,
+ issuer: config.mcpHostJwtIssuer,
+ hostNamespace: config.hostNamespace,
+ maxTokenLifetimeSeconds: config.mcpHostJwtMaxTtlSeconds,
+ })
+ } catch (err) {
+ console.error(
+ `[HCC] FATAL: ${err instanceof Error ? err.message : 'MCP JWT verifier configuration failed'}`
+ )
+ process.exit(1)
+ return
+ }
if (!config.devMode) {
console.log(`[Main] Namespace: ${config.namespace}`)
console.log(`[Main] Reconciler: ENABLED (will manage Deployments + Services)`)
@@ -145,7 +164,15 @@ async function main(): Promise<void> {
`target=${config.controlApiBaseUrl})`
)
}
- server = new ContextMapperServer(provider, config.port, hostReconciler, hasDesktopFn)
+ const mcpAuthorization = new McpAuthorizationService(createMcpAuthorizationStore(provider))
+ server = new ContextMapperServer(
+ provider,
+ config.port,
+ hostReconciler,
+ hasDesktopFn,
+ mcpAuthenticator,
+ mcpAuthorization
+ )
await server.start()
// One-shot legacy sweep: delete the static `clerum-channel-reader`
diff --git a/host-context-controller/src/mcpApiAuthentication.test.ts b/host-context-controller/src/mcpApiAuthentication.test.ts
new file mode 100644
index 000000000..290e954e2
--- /dev/null
+++ b/host-context-controller/src/mcpApiAuthentication.test.ts
@@ -0,0 +1,179 @@
+import { describe, expect, it } from 'vitest'
+import jwt from 'jsonwebtoken'
+import { generateKeyPairSync } from 'node:crypto'
+import {
+ HCC_MCP_AUDIENCE,
+ MCP_CREDENTIAL_READ_CAPABILITY,
+ McpApiAuthenticationError,
+ McpApiAuthenticator,
+ McpApiVerifierConfigurationError,
+ WORKFLOW_APPROVAL_AUDIENCE,
+} from './mcpApiAuthentication'
+
+const pair = generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+})
+
+const authenticator = new McpApiAuthenticator({
+ publicKey: pair.publicKey,
+ issuer: 'control-api',
+ hostNamespace: 'mcp-host',
+})
+
+function tokenClaims(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ sub: 'mcp-host/standalone',
+ recipeNamespace: 'mcp-host',
+ recipeName: 'standalone',
+ hostRefs: ['host-a'],
+ host_uid: 'uid-a',
+ scope: 'workflow:approval:request',
+ workflowControlScopes: [],
+ mcpCapabilities: [MCP_CREDENTIAL_READ_CAPABILITY],
+ ...overrides,
+ }
+}
+
+function sign(
+ overrides: Record<string, unknown> = {},
+ audience: string | string[] = [WORKFLOW_APPROVAL_AUDIENCE, HCC_MCP_AUDIENCE]
+): string {
+ return jwt.sign(tokenClaims(overrides), pair.privateKey, {
+ algorithm: 'RS256',
+ issuer: 'control-api',
+ audience,
+ expiresIn: 300,
+ jwtid: `test-${Math.random()}`,
+ })
+}
+
+function authenticate(token: string) {
+ return authenticator.authenticate({ authorization: `Bearer ${token}` }, [
+ 'Authorization',
+ `Bearer ${token}`,
+ ])
+}
+
+describe('McpApiAuthenticator', () => {
+ it('accepts the exact migration audience pair and returns only the Host principal', () => {
+ expect(authenticate(sign())).toMatchObject({
+ subject: 'mcp-host/standalone',
+ hostName: 'host-a',
+ hostUid: 'uid-a',
+ namespace: 'mcp-host',
+ audiences: [WORKFLOW_APPROVAL_AUDIENCE, HCC_MCP_AUDIENCE],
+ })
+ })
+
+ it('accepts the exact HCC-only audience', () => {
+ expect(authenticate(sign({}, HCC_MCP_AUDIENCE)).audiences).toEqual([HCC_MCP_AUDIENCE])
+ })
+
+ it.each([
+ [WORKFLOW_APPROVAL_AUDIENCE],
+ [[HCC_MCP_AUDIENCE, WORKFLOW_APPROVAL_AUDIENCE, 'third-resource']],
+ [[HCC_MCP_AUDIENCE, HCC_MCP_AUDIENCE]],
+ ])('rejects a non-exact audience set', audience => {
+ expect(() => authenticate(sign({}, audience as string | string[]))).toThrow(
+ McpApiAuthenticationError
+ )
+ })
+
+ it.each([
+ { mcpCapabilities: [] },
+ { mcpCapabilities: [MCP_CREDENTIAL_READ_CAPABILITY, 'extra'] },
+ { host_uid: undefined },
+ { hostRefs: ['host-a', 'host-b'] },
+ { recipeName: 'recipe-a', hostRefs: ['sandbox-recipes/recipe-a'] },
+ { scope: 'workflow:approval:refresh' },
+ ])('rejects a malformed or non-Host access contract', overrides => {
+ expect(() => authenticate(sign(overrides))).toThrow(McpApiAuthenticationError)
+ })
+
+ it('rejects duplicate Authorization fields before verification', () => {
+ const token = sign()
+ expect(() =>
+ authenticator.authenticate({ authorization: `Bearer ${token}` }, [
+ 'Authorization',
+ `Bearer ${token}`,
+ 'authorization',
+ `Bearer ${token}`,
+ ])
+ ).toThrow(McpApiAuthenticationError)
+ })
+
+ it('rejects wrong algorithm, issuer, expiration, and excessive lifetime', () => {
+ const invalidTokens = [
+ jwt.sign(tokenClaims(), 'attacker-secret', {
+ algorithm: 'HS256',
+ issuer: 'control-api',
+ audience: HCC_MCP_AUDIENCE,
+ expiresIn: 300,
+ jwtid: 'wrong-algorithm',
+ }),
+ jwt.sign(tokenClaims(), pair.privateKey, {
+ algorithm: 'RS256',
+ issuer: 'other-issuer',
+ audience: HCC_MCP_AUDIENCE,
+ expiresIn: 300,
+ jwtid: 'wrong-issuer',
+ }),
+ jwt.sign(tokenClaims(), pair.privateKey, {
+ algorithm: 'RS256',
+ issuer: 'control-api',
+ audience: HCC_MCP_AUDIENCE,
+ expiresIn: -10,
+ jwtid: 'expired',
+ }),
+ jwt.sign(tokenClaims(), pair.privateKey, {
+ algorithm: 'RS256',
+ issuer: 'control-api',
+ audience: HCC_MCP_AUDIENCE,
+ expiresIn: 601,
+ jwtid: 'excessive-lifetime',
+ }),
+ jwt.sign(tokenClaims({ iat: Math.floor(Date.now() / 1000) + 60 }), pair.privateKey, {
+ algorithm: 'RS256',
+ issuer: 'control-api',
+ audience: HCC_MCP_AUDIENCE,
+ expiresIn: 300,
+ jwtid: 'future-issued-at',
+ }),
+ jwt.sign(tokenClaims(), pair.privateKey, {
+ algorithm: 'RS256',
+ issuer: 'control-api',
+ audience: HCC_MCP_AUDIENCE,
+ expiresIn: 300,
+ jwtid: ' non-canonical-jti ',
+ }),
+ ]
+ for (const token of invalidTokens) {
+ expect(() => authenticate(token)).toThrow(McpApiAuthenticationError)
+ }
+ })
+
+ it('fails closed on absent, malformed, or placeholder public keys', () => {
+ expect(
+ () =>
+ new McpApiAuthenticator({ publicKey: '', issuer: 'control-api', hostNamespace: 'mcp-host' })
+ ).toThrow(McpApiVerifierConfigurationError)
+ expect(
+ () =>
+ new McpApiAuthenticator({
+ publicKey: 'not-a-pem',
+ issuer: 'control-api',
+ hostNamespace: 'mcp-host',
+ })
+ ).toThrow(McpApiVerifierConfigurationError)
+ expect(
+ () =>
+ new McpApiAuthenticator({
+ publicKey: pair.privateKey,
+ issuer: 'control-api',
+ hostNamespace: 'mcp-host',
+ })
+ ).toThrow(McpApiVerifierConfigurationError)
+ })
+})
diff --git a/host-context-controller/src/mcpApiAuthentication.ts b/host-context-controller/src/mcpApiAuthentication.ts
new file mode 100644
index 000000000..d069b5f67
--- /dev/null
+++ b/host-context-controller/src/mcpApiAuthentication.ts
@@ -0,0 +1,191 @@
+import jwt from 'jsonwebtoken'
+import { createPublicKey } from 'node:crypto'
+import type { IncomingHttpHeaders } from 'node:http'
+
+export const HCC_MCP_AUDIENCE = 'host-context-controller'
+export const WORKFLOW_APPROVAL_AUDIENCE = 'workflow-approvals'
+export const MCP_CREDENTIAL_READ_CAPABILITY = 'mcp:credential:read'
+
+const HOST_NAME_RE = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/
+
+export interface VerifiedMcpHostPrincipal {
+ subject: string
+ hostName: string
+ hostUid: string
+ namespace: string
+ jti: string
+ issuedAt: number
+ expiresAt: number
+ audiences: readonly string[]
+}
+
+export class McpApiAuthenticationError extends Error {
+ readonly code = 'unauthorized'
+
+ constructor() {
+ super('unauthorized')
+ this.name = 'McpApiAuthenticationError'
+ }
+}
+
+export class McpApiVerifierConfigurationError extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = 'McpApiVerifierConfigurationError'
+ }
+}
+
+export interface McpApiAuthenticatorOptions {
+ publicKey: string
+ issuer: string
+ hostNamespace: string
+ clockToleranceSeconds?: number
+ maxTokenLifetimeSeconds?: number
+}
+
+function exactAudiences(value: unknown): string[] | null {
+ const audiences = typeof value === 'string' ? [value] : Array.isArray(value) ? value : null
+ if (
+ !audiences ||
+ audiences.length === 0 ||
+ audiences.some(item => typeof item !== 'string') ||
+ new Set(audiences).size !== audiences.length
+ ) {
+ return null
+ }
+ const values = new Set(audiences as string[])
+ const hccOnly = values.size === 1 && values.has(HCC_MCP_AUDIENCE)
+ const migrationPair =
+ values.size === 2 && values.has(HCC_MCP_AUDIENCE) && values.has(WORKFLOW_APPROVAL_AUDIENCE)
+ return hccOnly || migrationPair ? (audiences as string[]) : null
+}
+
+function canonicalHostUid(value: unknown): string | null {
+ if (typeof value !== 'string') return null
+ const normalized = value.trim()
+ if (!normalized || normalized !== value || normalized.length > 128) return null
+ return /[^A-Za-z0-9._:-]/.test(normalized) ? null : normalized
+}
+
+function bearerFromHeaders(headers: IncomingHttpHeaders, rawHeaders: readonly string[]): string {
+ let authorizationCount = 0
+ for (let index = 0; index < rawHeaders.length; index += 2) {
+ if (rawHeaders[index]?.toLowerCase() === 'authorization') authorizationCount += 1
+ }
+ if (authorizationCount > 1 || Array.isArray(headers.authorization)) {
+ throw new McpApiAuthenticationError()
+ }
+ const header = headers.authorization
+ if (typeof header !== 'string') throw new McpApiAuthenticationError()
+ const match = /^Bearer ([^\s,]+)$/.exec(header)
+ if (!match) throw new McpApiAuthenticationError()
+ return match[1]
+}
+
+export class McpApiAuthenticator {
+ private readonly publicKey: string
+ private readonly issuer: string
+ private readonly hostNamespace: string
+ private readonly clockToleranceSeconds: number
+ private readonly maxTokenLifetimeSeconds: number
+
+ constructor(options: McpApiAuthenticatorOptions) {
+ const key = options.publicKey.trim()
+ if (!key) throw new McpApiVerifierConfigurationError('HCC MCP JWT public key is required')
+ if (/placeholder|replace[-_ ]?me|your[-_ ]?key/i.test(key)) {
+ throw new McpApiVerifierConfigurationError('HCC MCP JWT public key contains a placeholder')
+ }
+ if (/PRIVATE KEY/.test(key)) {
+ throw new McpApiVerifierConfigurationError('HCC MCP JWT verifier requires a public key')
+ }
+ try {
+ const publicKey = createPublicKey(key)
+ if (
+ publicKey.asymmetricKeyType !== 'rsa' ||
+ (publicKey.asymmetricKeyDetails?.modulusLength ?? 0) < 2048
+ ) {
+ throw new Error('unsupported RSA key')
+ }
+ } catch {
+ throw new McpApiVerifierConfigurationError('HCC MCP JWT public key is malformed')
+ }
+ if (!options.issuer.trim()) {
+ throw new McpApiVerifierConfigurationError('HCC MCP JWT issuer is required')
+ }
+ if (!options.hostNamespace.trim()) {
+ throw new McpApiVerifierConfigurationError('HCC Host namespace is required')
+ }
+ this.publicKey = key
+ this.issuer = options.issuer.trim()
+ this.hostNamespace = options.hostNamespace.trim()
+ this.clockToleranceSeconds = options.clockToleranceSeconds ?? 5
+ this.maxTokenLifetimeSeconds = options.maxTokenLifetimeSeconds ?? 600
+ if (!Number.isSafeInteger(this.maxTokenLifetimeSeconds) || this.maxTokenLifetimeSeconds <= 0) {
+ throw new McpApiVerifierConfigurationError('HCC MCP JWT maximum lifetime is invalid')
+ }
+ }
+
+ authenticate(
+ headers: IncomingHttpHeaders,
+ rawHeaders: readonly string[] = []
+ ): VerifiedMcpHostPrincipal {
+ const token = bearerFromHeaders(headers, rawHeaders)
+ let payload: jwt.JwtPayload
+ try {
+ const verified = jwt.verify(token, this.publicKey, {
+ algorithms: ['RS256'],
+ issuer: this.issuer,
+ clockTolerance: this.clockToleranceSeconds,
+ })
+ if (typeof verified === 'string') throw new McpApiAuthenticationError()
+ payload = verified
+ } catch {
+ throw new McpApiAuthenticationError()
+ }
+
+ const audiences = exactAudiences(payload.aud)
+ const hostRefs = payload.hostRefs
+ const capabilities = payload.mcpCapabilities
+ const hostUid = canonicalHostUid(payload.host_uid)
+ const now = Math.floor(Date.now() / 1000)
+ if (
+ !audiences ||
+ payload.scope !== 'workflow:approval:request' ||
+ payload.recipeNamespace !== this.hostNamespace ||
+ payload.recipeName !== 'standalone' ||
+ payload.sub !== `${this.hostNamespace}/standalone` ||
+ !Array.isArray(hostRefs) ||
+ hostRefs.length !== 1 ||
+ typeof hostRefs[0] !== 'string' ||
+ hostRefs[0].length > 63 ||
+ !HOST_NAME_RE.test(hostRefs[0]) ||
+ !hostUid ||
+ !Array.isArray(capabilities) ||
+ capabilities.length !== 1 ||
+ capabilities[0] !== MCP_CREDENTIAL_READ_CAPABILITY ||
+ typeof payload.jti !== 'string' ||
+ !payload.jti.trim() ||
+ payload.jti.trim() !== payload.jti ||
+ payload.jti.length > 128 ||
+ /[^A-Za-z0-9._:-]/.test(payload.jti) ||
+ !Number.isSafeInteger(payload.iat) ||
+ !Number.isSafeInteger(payload.exp) ||
+ (payload.iat as number) > now + this.clockToleranceSeconds ||
+ (payload.exp as number) <= (payload.iat as number) ||
+ (payload.exp as number) - (payload.iat as number) > this.maxTokenLifetimeSeconds
+ ) {
+ throw new McpApiAuthenticationError()
+ }
+
+ return {
+ subject: payload.sub,
+ hostName: hostRefs[0],
+ hostUid,
+ namespace: payload.recipeNamespace,
+ jti: payload.jti,
+ issuedAt: payload.iat as number,
+ expiresAt: payload.exp as number,
+ audiences,
+ }
+ }
+}
diff --git a/host-context-controller/src/mcpAuthorization.test.ts b/host-context-controller/src/mcpAuthorization.test.ts
new file mode 100644
index 000000000..009fb1b83
--- /dev/null
+++ b/host-context-controller/src/mcpAuthorization.test.ts
@@ -0,0 +1,377 @@
+import { describe, expect, it } from 'vitest'
+import type { VerifiedMcpHostPrincipal } from './mcpApiAuthentication'
+import {
+ type AuthorityContext,
+ type AuthorityHost,
+ type AuthorityMcpServer,
+ type AuthoritySecret,
+ McpAuthorizationService,
+ type McpAuthorizationStore,
+ toPublicMcpTransport,
+} from './mcpAuthorization'
+
+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 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 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 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<AuthoritySecret | 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
+ hostReads = 0
+ contextReads = 0
+ serverReads = 0
+ hostObject: AuthorityHost | null = host
+ contextObject: AuthorityContext | null = context
+ serverObject: AuthorityMcpServer | null = server
+
+ async readHost() {
+ this.hostReads += 1
+ return this.hostSequence
+ ? this.hostSequence[Math.min(this.hostReads - 1, this.hostSequence.length - 1)]
+ : this.hostObject
+ }
+ async readContext() {
+ this.contextReads += 1
+ return this.contextSequence
+ ? this.contextSequence[Math.min(this.contextReads - 1, this.contextSequence.length - 1)]
+ : this.contextObject
+ }
+ async readMcpServer() {
+ this.serverReads += 1
+ return this.serverSequence
+ ? this.serverSequence[Math.min(this.serverReads - 1, this.serverSequence.length - 1)]
+ : this.serverObject
+ }
+ async readSecretMetadata() {
+ this.secretMetadataReads += 1
+ 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() {
+ this.secretValueReads += 1
+ return this.secretSequence[Math.min(this.secretValueReads - 1, this.secretSequence.length - 1)]
+ }
+}
+
+describe('McpAuthorizationService', () => {
+ 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('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('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)
+ })
+})
diff --git a/host-context-controller/src/mcpAuthorization.ts b/host-context-controller/src/mcpAuthorization.ts
new file mode 100644
index 000000000..1d19d53d6
--- /dev/null
+++ b/host-context-controller/src/mcpAuthorization.ts
@@ -0,0 +1,371 @@
+import { createHash } from 'node:crypto'
+import type { VerifiedMcpHostPrincipal } from './mcpApiAuthentication'
+import type { McpServerAuth, 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
+ 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
+}
+
+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')
+ 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 } : {}),
+ })
+ }
+ 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 --git a/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts b/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts
index 219d928db..9037ec36d 100644
--- a/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts
+++ b/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts
@@ -1,10 +1,11 @@
/**
- * HCC provisions the shared 1st-party mcp-host credentials.
- * All 1st-party hosts share the sentinel binding `<target namespace>`/`standalone`;
- * per-host authorization is still enforced by Host/User bindings elsewhere.
+ * HCC provisions first-party mcp-host credentials through the existing
+ * `<target namespace>`/`standalone` token family. Each credential is additionally
+ * bound to the canonical live Host name and UID.
*/
import { config } from './config'
import { hccLogger } from './logger'
+import { McpApiAuthenticator } from './mcpApiAuthentication'
import type { HostWorkflowControlScope } from './types'
import { signInternalControlJwt } from './utils/internalControlSigner'
@@ -19,6 +20,7 @@ export interface McpHostRuntimeTokenResponse {
const REQUEST_TIMEOUT_MS = 10_000
const SENTINEL_RECIPE_NAME = 'standalone'
+const HOST_NAME_RE = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/
const log = hccLogger.child({ module: 'mcp-host-runtime-token-issuer' })
type CanonicalMcpHostTokenResponse = {
@@ -32,16 +34,53 @@ type CanonicalMcpHostTokenResponse = {
}
}
+function isBoundedCompactJwt(value: unknown): value is string {
+ return (
+ typeof value === 'string' &&
+ value.length <= 16_384 &&
+ /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value)
+ )
+}
+
+function positiveInteger(value: unknown): number | null {
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : null
+}
+
/**
* `hostName` is sent as `host` in the body so control-api can populate
* the JWT's `hostRefs[0]` with the actual Host CRD name (not the sentinel
- * recipe pair). Per-event identity binding (e.g. usage ingest) uses this
- * to verify the bearer pod is acting on its own behalf.
+ * recipe pair). The sentinel recipe pair is only the internal issuance
+ * transport contract; the returned access JWT is cryptographically verified
+ * below for the actual Host name, UID, HCC audience, and MCP capability before
+ * any credential is persisted.
*/
export async function issueMcpHostRuntimeTokens(
hostName: string,
+ hostUid: string,
workflowControlScopes: HostWorkflowControlScope[] = []
): 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`
@@ -58,39 +97,55 @@ export async function issueMcpHostRuntimeTokens(
body: JSON.stringify({
includeMcpHostControlToken: true,
host: hostName,
+ hostUid,
workflowControlScopes,
}),
signal: controller.signal,
})
if (!response.ok) {
- throw new Error(
- `mcpHost runtime token issuance failed: HTTP ${response.status} for host "${hostName}"`
- )
+ throw new Error(`mcpHost runtime token issuance failed: HTTP ${response.status}`)
}
const data = (await response.json()) as CanonicalMcpHostTokenResponse
if (
- typeof data.mcpHostAccessToken !== 'string' ||
- typeof data.mcpHostRefreshToken !== 'string' ||
- typeof data.mcpHostControlToken !== 'string'
+ !isBoundedCompactJwt(data.mcpHostAccessToken) ||
+ !isBoundedCompactJwt(data.mcpHostRefreshToken) ||
+ !isBoundedCompactJwt(data.mcpHostControlToken)
) {
- throw new Error(`mcpHost credential response missing required fields for host "${hostName}"`)
+ throw new Error('mcpHost credential response missing required fields')
+ }
+ const accessTtl = positiveInteger(data.expiresInSeconds?.access)
+ const refreshTtl = positiveInteger(data.expiresInSeconds?.refresh)
+ const controlTtl = positiveInteger(data.expiresInSeconds?.control)
+ if (accessTtl === null || refreshTtl === null || controlTtl === null) {
+ throw new Error('mcpHost credential response has invalid expiry fields')
+ }
+
+ // The issuer response is an authorization boundary, not merely a shape
+ // check. A stale/old Control API during a rolling update could otherwise
+ // return workflow-only credentials which the reconciler would persist and
+ // later mount. Verify the access token with the same strict HCC verifier
+ // used by the request routes before accepting the response.
+ const issuedPrincipal = new McpApiAuthenticator({
+ publicKey: config.mcpHostJwtPublicKey,
+ issuer: config.mcpHostJwtIssuer,
+ hostNamespace: config.hostNamespace,
+ maxTokenLifetimeSeconds: config.mcpHostJwtMaxTtlSeconds,
+ }).authenticate({ authorization: `Bearer ${data.mcpHostAccessToken}` }, [
+ 'Authorization',
+ `Bearer ${data.mcpHostAccessToken}`,
+ ])
+ if (issuedPrincipal.hostName !== hostName || issuedPrincipal.hostUid !== hostUid) {
+ throw new Error('mcpHost credential response identity does not match the live Host')
}
- const accessTtl =
- typeof data.expiresInSeconds?.access === 'number' ? data.expiresInSeconds.access : 0
- const refreshTtl =
- typeof data.expiresInSeconds?.refresh === 'number' ? data.expiresInSeconds.refresh : 0
- const controlTtl =
- typeof data.expiresInSeconds?.control === 'number' ? data.expiresInSeconds.control : 0
- log.info('Issued mcpHost credentials for host', {
- hostName,
+ log.info('Issued mcpHost credentials', {
accessTtlSeconds: accessTtl,
refreshTtlSeconds: refreshTtl,
controlTtlSeconds: controlTtl,
- workflowControlScopes,
+ workflowControlScopeCount: workflowControlScopes.length,
})
return {
@@ -103,9 +158,7 @@ export async function issueMcpHostRuntimeTokens(
}
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') {
- throw new Error(
- `mcpHost runtime token issuance timed out after ${REQUEST_TIMEOUT_MS}ms for host "${hostName}"`
- )
+ throw new Error(`mcpHost runtime token issuance timed out after ${REQUEST_TIMEOUT_MS}ms`)
}
throw err
} finally {
diff --git a/host-context-controller/src/metrics.ts b/host-context-controller/src/metrics.ts
index 75b8cc5f0..bb2a839fe 100644
--- a/host-context-controller/src/metrics.ts
+++ b/host-context-controller/src/metrics.ts
@@ -149,6 +149,14 @@ export const administrativeOutcomeReporterTotal = counter({
labelNames: ['result'] as const,
})
+// Low-cardinality Host-scoped MCP API decisions. Resource names, JWT IDs,
+// Contexts, and Secret selectors must never become metric labels.
+export const mcpHostApiRequestsTotal = counter({
+ name: 'clerum_hcc_mcp_host_api_requests_total',
+ help: 'Host-scoped MCP API requests by route class, outcome, and bounded reason.',
+ labelNames: ['action', 'outcome', 'reason'] as const,
+})
+
// ── Host reconciliation scheduler telemetry (issue #791 follow-up) ──
// Low-cardinality labels only — never host names, users, teams, or session IDs.
diff --git a/host-context-controller/src/server.test.ts b/host-context-controller/src/server.test.ts
index 633a48992..d8227f713 100644
--- a/host-context-controller/src/server.test.ts
+++ b/host-context-controller/src/server.test.ts
@@ -1,24 +1,34 @@
-import { afterEach, describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { Readable } from 'node:stream'
import { McpServerProvider } from './k8sClient'
-import { ContextMapperServer } from './server'
+import { McpApiAuthenticator, type VerifiedMcpHostPrincipal } from './mcpApiAuthentication'
+import {
+ type AuthorityContext,
+ type AuthorityHost,
+ type AuthorityMcpServer,
+ type AuthoritySecret,
+ McpAuthorizationError,
+ McpAuthorizationService,
+ type McpAuthorizationStore,
+} from './mcpAuthorization'
+import { ContextMapperServer, McpHostApiRateLimiter } from './server'
+import type { McpServerInfo } from './types'
class FakeProvider implements McpServerProvider {
+ constructor(private readonly infos: McpServerInfo[] = []) {}
+
getAllServers() {
return []
}
getAllServerInfos() {
- return []
+ return this.infos
}
async getServerInfosByContext() {
return []
}
- async getAuthToken() {
- return undefined
- }
-
onChange() {}
async start() {}
@@ -39,37 +49,121 @@ class MockResponse {
writeHead(status: number, headers?: Record<string, string>): void {
this.statusCode = status
this.headersSent = true
- if (headers) {
- Object.assign(this.headers, headers)
- }
+ if (headers) Object.assign(this.headers, headers)
}
end(chunk?: string): void {
- if (chunk) {
- this.body += chunk
- }
+ if (chunk) this.body += chunk
}
}
-async function invoke(server: ContextMapperServer, path: string) {
- const req = {
- method: 'GET',
+async function invoke(
+ server: ContextMapperServer,
+ path: string,
+ options: { method?: string; headers?: Record<string, string>; body?: string } = {}
+) {
+ const headers = options.headers ?? {}
+ const req = Readable.from(options.body === undefined ? [] : [options.body])
+ Object.assign(req, {
+ method: options.method ?? 'GET',
url: path,
- headers: {},
- }
+ headers,
+ rawHeaders: Object.entries(headers).flatMap(([name, value]) => [name, value]),
+ })
const res = new MockResponse()
await (
server as unknown as {
- handleRequest: (
- req: { method: string; url: string; headers: Record<string, string> },
- res: MockResponse
- ) => Promise<void>
+ handleRequest: (req: Readable, res: MockResponse) => Promise<void>
}
).handleRequest(req, res)
return res
}
-describe('ContextMapperServer readiness', () => {
+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'],
+}
+
+class FakeAuthorityStore implements McpAuthorizationStore {
+ secretValueReads = 0
+ private readonly host: AuthorityHost = {
+ name: 'host-a',
+ namespace: 'mcp-host',
+ metadata: { uid: 'host-uid-a', resourceVersion: '1' },
+ contextRef: 'context-a',
+ }
+ private readonly context: AuthorityContext = {
+ name: 'context-a',
+ namespace: 'mcp-server',
+ metadata: { uid: 'context-uid-a', resourceVersion: '2' },
+ mcpServers: ['server-a'],
+ }
+ private readonly mcpServer: AuthorityMcpServer = {
+ name: 'server-a',
+ namespace: 'mcp-server',
+ metadata: { uid: 'server-uid-a', resourceVersion: '3' },
+ transport: { type: 'streamableHttp', url: 'http://server-a/mcp' },
+ auth: { type: 'bearer', secretRef: 'server-a-auth', secretKey: 'token' },
+ enabled: true,
+ status: { deployed: true, ready: true },
+ }
+ private readonly secret: AuthoritySecret = {
+ name: 'server-a-auth',
+ namespace: 'mcp-server',
+ metadata: { uid: 'secret-uid-a', resourceVersion: '4' },
+ data: { token: Buffer.from('credential-value').toString('base64') },
+ }
+
+ async readHost() {
+ return this.host
+ }
+
+ async readContext() {
+ return this.context
+ }
+
+ async readMcpServer() {
+ return this.mcpServer
+ }
+
+ async readSecretMetadata() {
+ return {
+ name: this.secret.name,
+ namespace: this.secret.namespace,
+ metadata: this.secret.metadata,
+ }
+ }
+
+ async readSecret() {
+ this.secretValueReads += 1
+ return this.secret
+ }
+}
+
+function protectedServer(store = new FakeAuthorityStore()): {
+ server: ContextMapperServer
+ store: FakeAuthorityStore
+} {
+ const authenticator = { authenticate: () => principal } as unknown as McpApiAuthenticator
+ const server = new ContextMapperServer(
+ new FakeProvider(),
+ 0,
+ undefined,
+ undefined,
+ authenticator,
+ new McpAuthorizationService(store)
+ )
+ server.setReady(true)
+ return { server, store }
+}
+
+describe('ContextMapperServer', () => {
let server: ContextMapperServer | null = null
afterEach(async () => {
@@ -86,26 +180,207 @@ describe('ContextMapperServer readiness', () => {
response = await invoke(server, '/ready')
expect(response.statusCode).toBe(503)
- expect(JSON.parse(response.body)).toEqual({ status: 'starting', ready: false })
response = await invoke(server, '/api/v1/mcpservers')
expect(response.statusCode).toBe(503)
- expect(JSON.parse(response.body)).toEqual({
- error: 'Service Unavailable',
- message: 'Context mapper is still starting',
- })
server.setReady(true)
+ response = await invoke(server, '/api/v1/mcpservers')
+ expect(response.statusCode).toBe(200)
+ expect(JSON.parse(response.body)).toMatchObject({ servers: [], contextRef: '*' })
+ })
- response = await invoke(server, '/ready')
+ it('keeps the temporary global v1 inventory metadata-only and non-cacheable', async () => {
+ server = new ContextMapperServer(
+ new FakeProvider([
+ {
+ name: 'server-a',
+ description: 'must not be exposed by the legacy system inventory',
+ contextRef: 'context-a',
+ transport: {
+ type: 'streamableHttp',
+ url: 'http://server-a/mcp',
+ secretRef: 'nested-secret-must-not-leak',
+ } as McpServerInfo['transport'],
+ auth: { type: 'bearer', secretRef: 'server-a-auth', secretKey: 'token' },
+ enabled: true,
+ status: { deployed: true, ready: true, message: 'internal status detail' },
+ },
+ ]),
+ 0
+ )
+ server.setReady(true)
+
+ const response = await invoke(server, '/api/v1/mcpservers')
expect(response.statusCode).toBe(200)
- expect(JSON.parse(response.body)).toEqual({ status: 'ready', ready: true })
+ expect(response.headers['Cache-Control']).toBe('no-store, private')
+ expect(JSON.parse(response.body).servers[0]).not.toHaveProperty('auth')
+ expect(JSON.parse(response.body).servers[0]).not.toHaveProperty('description')
+ expect(response.body).not.toContain('secretRef')
+ expect(response.body).not.toContain('secretKey')
+ expect(response.body).not.toContain('nested-secret-must-not-leak')
+ expect(response.body).not.toContain('internal status detail')
+ })
- response = await invoke(server, '/api/v1/mcpservers')
+ it.each(['/api/v1/mcpservers/context/context-a', '/api/v1/mcpservers/server-a/auth'])(
+ 'returns an application-level 410 tombstone for legacy route %s',
+ async path => {
+ server = new ContextMapperServer(new FakeProvider(), 0)
+ server.setReady(true)
+ const response = await invoke(server, path)
+ expect(response.statusCode).toBe(410)
+ expect(JSON.parse(response.body)).toEqual({ error: 'gone' })
+ expect(response.headers['Cache-Control']).toBe('no-store, private')
+ }
+ )
+
+ it('tombstones legacy Host-selected routes for every method before readiness and CORS', async () => {
+ server = new ContextMapperServer(new FakeProvider(), 0)
+
+ for (const [path, method] of [
+ ['/api/v1/mcpservers/context/context-a', 'OPTIONS'],
+ ['/api/v1/mcpservers/server-a/auth', 'POST'],
+ ] as const) {
+ const response = await invoke(server, path, { method })
+ expect(response.statusCode).toBe(410)
+ expect(JSON.parse(response.body)).toEqual({ error: 'gone' })
+ expect(response.headers['Access-Control-Allow-Origin']).toBeUndefined()
+ expect(response.headers['Cache-Control']).toBe('no-store, private')
+ }
+ })
+
+ it('serves scoped v2 inventory without wildcard browser CORS or Secret values', async () => {
+ const protectedRoute = protectedServer()
+ server = protectedRoute.server
+ const response = await invoke(server, '/api/v2/hosts/self/mcpservers')
+ expect(response.statusCode).toBe(200)
+ expect(response.headers['Access-Control-Allow-Origin']).toBeUndefined()
+ expect(response.headers['Cache-Control']).toBe('no-store, private')
+ const body = JSON.parse(response.body)
+ expect(body.servers).toEqual([
+ expect.objectContaining({ name: 'server-a', authRequired: true }),
+ ])
+ expect(response.body).not.toContain('context-a')
+ expect(response.body).not.toContain('server-a-auth')
+ expect(response.body).not.toContain('credential-value')
+ expect(protectedRoute.store.secretValueReads).toBe(0)
+ })
+
+ it('keeps direct protected-route startup and not-found errors generic and non-cacheable', async () => {
+ server = new ContextMapperServer(new FakeProvider(), 0)
+
+ let response = await invoke(server, '/api/v2/hosts/self/mcpservers')
+ expect(response.statusCode).toBe(503)
+ expect(JSON.parse(response.body)).toEqual({ error: 'authorization_unavailable' })
+ expect(response.headers['Cache-Control']).toBe('no-store, private')
+
+ server.setReady(true)
+ response = await invoke(server, '/api/v2/hosts/self/mcpservers/unknown')
+ expect(response.statusCode).toBe(404)
+ expect(JSON.parse(response.body)).toEqual({ error: 'not_found' })
+ expect(response.headers['Cache-Control']).toBe('no-store, private')
+ })
+
+ it('accepts only the exact credential body and returns the fenced token DTO', async () => {
+ const protectedRoute = protectedServer()
+ server = protectedRoute.server
+ const response = await invoke(server, '/api/v2/hosts/self/mcpservers/credential', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ serverName: 'server-a' }),
+ })
expect(response.statusCode).toBe(200)
- expect(JSON.parse(response.body)).toMatchObject({
- servers: [],
- contextRef: '*',
+ expect(JSON.parse(response.body)).toEqual({
+ token: 'credential-value',
+ credentialRevision: expect.any(String),
+ })
+ expect(protectedRoute.store.secretValueReads).toBe(1)
+
+ const invalid = await invoke(server, '/api/v2/hosts/self/mcpservers/credential', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ serverName: 'server-a', contextRef: 'context-b' }),
+ })
+ expect(invalid.statusCode).toBe(400)
+ expect(protectedRoute.store.secretValueReads).toBe(1)
+ })
+
+ it('normalizes protected route method, media-type, and body-limit failures without a Secret read', async () => {
+ const protectedRoute = protectedServer()
+ server = protectedRoute.server
+
+ let response = await invoke(server, '/api/v2/hosts/self/mcpservers', { method: 'POST' })
+ expect(response.statusCode).toBe(405)
+ expect(JSON.parse(response.body)).toEqual({ error: 'method_not_allowed' })
+ expect(response.headers.Allow).toBe('GET')
+
+ response = await invoke(server, '/api/v2/hosts/self/mcpservers/credential', {
+ method: 'POST',
+ headers: { 'content-type': 'text/plain' },
+ body: '{}',
+ })
+ expect(response.statusCode).toBe(415)
+ expect(JSON.parse(response.body)).toEqual({ error: 'unsupported_media_type' })
+
+ response = await invoke(server, '/api/v2/hosts/self/mcpservers/credential', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ serverName: 'a'.repeat(1_025) }),
+ })
+ expect(response.statusCode).toBe(413)
+ expect(JSON.parse(response.body)).toEqual({ error: 'payload_too_large' })
+ expect(response.headers['Cache-Control']).toBe('no-store, private')
+ expect(protectedRoute.store.secretValueReads).toBe(0)
+ })
+
+ it('fails closed when the protected Host verifier is not configured', async () => {
+ server = new ContextMapperServer(new FakeProvider(), 0)
+ server.setReady(true)
+
+ const response = await invoke(server, '/api/v2/hosts/self/mcpservers')
+ expect(response.statusCode).toBe(503)
+ expect(JSON.parse(response.body)).toEqual({ error: 'authorization_unavailable' })
+ expect(response.headers['Cache-Control']).toBe('no-store, private')
+ })
+
+ it('maps a rebound Host identity to a generic non-cacheable 401', async () => {
+ const authenticator = { authenticate: () => principal } as unknown as McpApiAuthenticator
+ const authorization = {
+ listServers: async () => {
+ throw new McpAuthorizationError('unauthorized')
+ },
+ } as unknown as McpAuthorizationService
+ server = new ContextMapperServer(
+ new FakeProvider(),
+ 0,
+ undefined,
+ undefined,
+ authenticator,
+ authorization
+ )
+ server.setReady(true)
+
+ const response = await invoke(server, '/api/v2/hosts/self/mcpservers')
+ expect(response.statusCode).toBe(401)
+ expect(JSON.parse(response.body)).toEqual({ error: 'unauthorized' })
+ expect(response.headers['WWW-Authenticate']).toBe('Bearer realm="host-context-controller"')
+ expect(response.headers['Cache-Control']).toBe('no-store, private')
+ expect(response.headers.Pragma).toBe('no-cache')
+ })
+})
+
+describe('McpHostApiRateLimiter', () => {
+ it('limits each signed Host identity/action independently and resets after one minute', () => {
+ let now = 1_000
+ const limiter = new McpHostApiRateLimiter(1, () => now)
+ expect(limiter.consume('host-uid-a', 'credential')).toEqual({ allowed: true })
+ expect(limiter.consume('host-uid-a', 'inventory')).toEqual({ allowed: true })
+ expect(limiter.consume('host-uid-b', 'credential')).toEqual({ allowed: true })
+ expect(limiter.consume('host-uid-a', 'credential')).toEqual({
+ allowed: false,
+ retryAfterSeconds: 60,
})
+ now += 60_000
+ expect(limiter.consume('host-uid-a', 'credential')).toEqual({ allowed: true })
})
})
diff --git a/host-context-controller/src/server.ts b/host-context-controller/src/server.ts
index 7be800a8e..6fa2393d7 100644
--- a/host-context-controller/src/server.ts
+++ b/host-context-controller/src/server.ts
@@ -5,8 +5,73 @@ import * as http from 'http'
import { config } from './config'
import { HostReconciler } from './hostReconciler'
import { McpServerProvider } from './k8sClient'
-import { registry } from './metrics'
-import { ErrorResponse, McpServersResponse } from './types'
+import { hccLogger } from './logger'
+import {
+ McpApiAuthenticationError,
+ McpApiAuthenticator,
+ type VerifiedMcpHostPrincipal,
+} from './mcpApiAuthentication'
+import {
+ McpAuthorizationError,
+ McpAuthorizationService,
+ toPublicMcpTransport,
+} from './mcpAuthorization'
+import { mcpHostApiRequestsTotal, registry } from './metrics'
+import { McpServersResponse } from './types'
+
+const MCP_SELECTOR_RE = /^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$/
+const MCP_REQUEST_BODY_LIMIT = 1024
+const mcpApiLog = hccLogger.child({ module: 'mcp-host-api' })
+type McpHostApiAction = 'inventory' | 'credential'
+
+type RateLimitEntry = { windowStartMs: number; count: number }
+
+/** Per-Host, per-action fixed-window limiter applied only after JWT validation. */
+export class McpHostApiRateLimiter {
+ private readonly entries = new Map<string, RateLimitEntry>()
+
+ constructor(
+ private readonly maxPerMinute: number,
+ private readonly now: () => number = Date.now
+ ) {}
+
+ consume(
+ hostUid: string,
+ action: McpHostApiAction
+ ): { allowed: true } | { allowed: false; retryAfterSeconds: number } {
+ const nowMs = this.now()
+ const key = `${hostUid}\u0000${action}`
+ const existing = this.entries.get(key)
+ if (!existing || nowMs - existing.windowStartMs >= 60_000) {
+ this.entries.set(key, { windowStartMs: nowMs, count: 1 })
+ this.prune(nowMs)
+ return { allowed: true }
+ }
+ if (existing.count >= this.maxPerMinute) {
+ return {
+ allowed: false,
+ retryAfterSeconds: Math.max(
+ 1,
+ Math.ceil((60_000 - (nowMs - existing.windowStartMs)) / 1000)
+ ),
+ }
+ }
+ existing.count += 1
+ return { allowed: true }
+ }
+
+ private prune(nowMs: number): void {
+ if (this.entries.size <= 10_000) return
+ for (const [key, entry] of this.entries) {
+ if (nowMs - entry.windowStartMs >= 60_000) this.entries.delete(key)
+ }
+ while (this.entries.size > 10_000) {
+ const oldest = this.entries.keys().next()
+ if (oldest.done) break
+ this.entries.delete(oldest.value)
+ }
+ }
+}
export class ContextMapperServer {
private server: http.Server | null = null
@@ -14,18 +79,26 @@ export class ContextMapperServer {
private port: number
private hostReconciler: HostReconciler | null
private hasDesktopFn: ((hostRef: string) => boolean) | null
+ private mcpAuthenticator: McpApiAuthenticator | null
+ private mcpAuthorization: McpAuthorizationService | null
+ private mcpRateLimiter: McpHostApiRateLimiter
private ready = false
constructor(
provider: McpServerProvider,
port: number = config.port,
hostReconciler?: HostReconciler,
- hasDesktopFn?: (hostRef: string) => boolean
+ hasDesktopFn?: (hostRef: string) => boolean,
+ mcpAuthenticator?: McpApiAuthenticator,
+ mcpAuthorization?: McpAuthorizationService
) {
this.provider = provider
this.port = port
this.hostReconciler = hostReconciler ?? null
this.hasDesktopFn = hasDesktopFn ?? null
+ this.mcpAuthenticator = mcpAuthenticator ?? null
+ this.mcpAuthorization = mcpAuthorization ?? null
+ this.mcpRateLimiter = new McpHostApiRateLimiter(config.mcpHostApiRateLimitPerMinute)
}
/**
@@ -36,10 +109,29 @@ export class ContextMapperServer {
}
private async handleRequest(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
- // CORS headers
- res.setHeader('Access-Control-Allow-Origin', '*')
- res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS')
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
+ const url = new URL(req.url || '/', `http://localhost:${this.port}`)
+ const isLegacyHostSelectedMcpRoute =
+ url.pathname.startsWith('/api/v1/mcpservers/context/') ||
+ (url.pathname.startsWith('/api/v1/mcpservers/') && url.pathname.endsWith('/auth'))
+ const isProtectedMcpRoute =
+ url.pathname.startsWith('/api/v2/hosts/self/mcpservers') || isLegacyHostSelectedMcpRoute
+
+ // The Host credential surface is service-to-service and deliberately has
+ // no browser wildcard CORS grant. Preserve the historical public CORS
+ // behavior only for unrelated/legacy endpoints.
+ if (!isProtectedMcpRoute) {
+ res.setHeader('Access-Control-Allow-Origin', '*')
+ res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS')
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
+ }
+
+ // Retire caller-selected Context/credential routes at the application
+ // boundary for every method, including preflight, and independently of
+ // readiness. This remains a defense if a caller bypasses the gateway.
+ if (isLegacyHostSelectedMcpRoute) {
+ this.sendProtectedJson(res, 410, { error: 'gone' })
+ return
+ }
if (req.method === 'OPTIONS') {
res.writeHead(204)
@@ -47,8 +139,6 @@ export class ContextMapperServer {
return
}
- const url = new URL(req.url || '/', `http://localhost:${this.port}`)
-
// Root path - API information
if (req.method === 'GET' && url.pathname === '/') {
this.handleRoot(res)
@@ -79,6 +169,10 @@ export class ContextMapperServer {
}
if (!this.ready) {
+ if (isProtectedMcpRoute) {
+ this.sendProtectedJson(res, 503, { error: 'authorization_unavailable' })
+ return
+ }
this.sendJson(res, 503, {
error: 'Service Unavailable',
message: 'Context mapper is still starting',
@@ -86,27 +180,27 @@ export class ContextMapperServer {
return
}
- // List all McpServers
- if (req.method === 'GET' && url.pathname === '/api/v1/mcpservers') {
- await this.handleListAll(req, res, url)
+ if (url.pathname === '/api/v2/hosts/self/mcpservers') {
+ if (req.method === 'GET') {
+ await this.handleHostMcpServers(req, res)
+ } else {
+ this.sendProtectedJson(res, 405, { error: 'method_not_allowed' }, { Allow: 'GET' })
+ }
return
}
- // List McpServers by context
- if (req.method === 'GET' && url.pathname.startsWith('/api/v1/mcpservers/context/')) {
- const contextRef = url.pathname.replace('/api/v1/mcpservers/context/', '')
- await this.handleListByContext(req, res, contextRef)
+ if (url.pathname === '/api/v2/hosts/self/mcpservers/credential') {
+ if (req.method === 'POST') {
+ await this.handleHostMcpCredential(req, res)
+ } else {
+ this.sendProtectedJson(res, 405, { error: 'method_not_allowed' }, { Allow: 'POST' })
+ }
return
}
- // Get auth token for a server
- if (
- req.method === 'GET' &&
- url.pathname.startsWith('/api/v1/mcpservers/') &&
- url.pathname.endsWith('/auth')
- ) {
- const serverName = url.pathname.replace('/api/v1/mcpservers/', '').replace('/auth', '')
- await this.handleGetAuth(req, res, serverName)
+ // List all McpServers (temporary PR 2 compatibility residual).
+ if (req.method === 'GET' && url.pathname === '/api/v1/mcpservers') {
+ await this.handleListAll(req, res, url)
return
}
@@ -119,6 +213,10 @@ export class ContextMapperServer {
}
// 404
+ if (isProtectedMcpRoute) {
+ this.sendProtectedJson(res, 404, { error: 'not_found' })
+ return
+ }
this.sendJson(res, 404, { error: 'Not Found', message: 'Endpoint not found' })
}
@@ -140,6 +238,181 @@ export class ContextMapperServer {
return true
}
+ private authenticateMcpHost(
+ req: http.IncomingMessage,
+ res: http.ServerResponse,
+ action: McpHostApiAction
+ ): VerifiedMcpHostPrincipal | null {
+ if (!this.mcpAuthenticator || !this.mcpAuthorization) {
+ mcpApiLog.error('MCP authorization authority unavailable', {
+ reason: 'verifier_not_configured',
+ })
+ mcpHostApiRequestsTotal.inc({ action, outcome: 'error', reason: 'unconfigured' }, 1)
+ this.sendProtectedJson(res, 503, { error: 'authorization_unavailable' })
+ return null
+ }
+ try {
+ return this.mcpAuthenticator.authenticate(req.headers, req.rawHeaders)
+ } catch (error) {
+ const reason =
+ error instanceof McpApiAuthenticationError ? 'invalid_bearer' : 'verifier_error'
+ mcpApiLog.info('MCP request denied', { reason })
+ mcpHostApiRequestsTotal.inc({ action, outcome: 'denied', reason }, 1)
+ this.sendProtectedJson(
+ res,
+ 401,
+ { error: 'unauthorized' },
+ { 'WWW-Authenticate': 'Bearer realm="host-context-controller"' }
+ )
+ return null
+ }
+ }
+
+ private async handleHostMcpServers(
+ req: http.IncomingMessage,
+ res: http.ServerResponse
+ ): Promise<void> {
+ const principal = this.authenticateMcpHost(req, res, 'inventory')
+ if (!principal || !this.mcpAuthorization) return
+ if (!this.enforceMcpRateLimit(principal, 'inventory', res)) return
+ try {
+ const servers = await this.mcpAuthorization.listServers(principal)
+ mcpHostApiRequestsTotal.inc({ action: 'inventory', outcome: 'success', reason: 'ok' }, 1)
+ this.sendProtectedJson(res, 200, { servers, timestamp: new Date().toISOString() })
+ } catch (error) {
+ this.sendMcpAuthorizationError(res, error, 'inventory')
+ }
+ }
+
+ private async handleHostMcpCredential(
+ req: http.IncomingMessage,
+ res: http.ServerResponse
+ ): Promise<void> {
+ const principal = this.authenticateMcpHost(req, res, 'credential')
+ if (!principal || !this.mcpAuthorization) return
+ if (!this.enforceMcpRateLimit(principal, 'credential', res)) return
+ const contentType = String(req.headers['content-type'] ?? '')
+ .split(';', 1)[0]
+ .trim()
+ if (contentType !== 'application/json') {
+ this.sendProtectedJson(res, 415, { error: 'unsupported_media_type' })
+ return
+ }
+
+ let body: unknown
+ try {
+ body = await this.readBoundedJsonBody(req)
+ } catch (error) {
+ const status = error instanceof Error && error.message === 'body_too_large' ? 413 : 400
+ this.sendProtectedJson(res, status, {
+ error: status === 413 ? 'payload_too_large' : 'bad_request',
+ })
+ return
+ }
+ const bodyKeys =
+ body && typeof body === 'object' && !Array.isArray(body) ? Object.keys(body) : []
+ const serverName =
+ bodyKeys.length === 1 && bodyKeys[0] === 'serverName'
+ ? (body as { serverName?: unknown }).serverName
+ : undefined
+ if (
+ typeof serverName !== 'string' ||
+ serverName.length > 253 ||
+ serverName.trim() !== serverName ||
+ !MCP_SELECTOR_RE.test(serverName)
+ ) {
+ this.sendProtectedJson(res, 400, { error: 'bad_request' })
+ return
+ }
+
+ try {
+ const credential = await this.mcpAuthorization.getCredential(principal, serverName)
+ mcpHostApiRequestsTotal.inc({ action: 'credential', outcome: 'success', reason: 'ok' }, 1)
+ this.sendProtectedJson(res, 200, credential)
+ } catch (error) {
+ this.sendMcpAuthorizationError(res, error, 'credential')
+ }
+ }
+
+ private async readBoundedJsonBody(req: http.IncomingMessage): Promise<unknown> {
+ const declared = Number(req.headers['content-length'] ?? 0)
+ if (Number.isFinite(declared) && declared > MCP_REQUEST_BODY_LIMIT) {
+ throw new Error('body_too_large')
+ }
+ const chunks: Buffer[] = []
+ let size = 0
+ for await (const chunk of req) {
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
+ size += buffer.length
+ if (size > MCP_REQUEST_BODY_LIMIT) throw new Error('body_too_large')
+ chunks.push(buffer)
+ }
+ if (size === 0) throw new Error('invalid_json')
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
+ }
+
+ private sendMcpAuthorizationError(
+ res: http.ServerResponse,
+ error: unknown,
+ action: McpHostApiAction
+ ): void {
+ const code = error instanceof McpAuthorizationError ? error.code : 'authorization_unavailable'
+ mcpApiLog.info('MCP request denied', { action, reason: code })
+ mcpHostApiRequestsTotal.inc({ action, outcome: 'denied', reason: code }, 1)
+ if (code === 'unauthorized') {
+ this.sendProtectedJson(
+ res,
+ 401,
+ { error: 'unauthorized' },
+ { 'WWW-Authenticate': 'Bearer realm="host-context-controller"' }
+ )
+ return
+ }
+ if (code === 'not_found') {
+ this.sendProtectedJson(res, 404, { error: 'not_found' })
+ return
+ }
+ if (code === 'credential_unavailable') {
+ this.sendProtectedJson(res, 503, { error: 'credential_unavailable' })
+ return
+ }
+ this.sendProtectedJson(res, 503, { error: 'authorization_unavailable' })
+ }
+
+ private enforceMcpRateLimit(
+ principal: VerifiedMcpHostPrincipal,
+ action: McpHostApiAction,
+ res: http.ServerResponse
+ ): boolean {
+ const result = this.mcpRateLimiter.consume(principal.hostUid, action)
+ if (result.allowed) return true
+ mcpApiLog.info('MCP request denied', { action, reason: 'rate_limited' })
+ mcpHostApiRequestsTotal.inc({ action, outcome: 'denied', reason: 'rate_limited' }, 1)
+ this.sendProtectedJson(
+ res,
+ 429,
+ { error: 'rate_limited' },
+ { 'Retry-After': String(result.retryAfterSeconds) }
+ )
+ return false
+ }
+
+ private sendProtectedJson(
+ res: http.ServerResponse,
+ status: number,
+ data: unknown,
+ headers: Record<string, string> = {}
+ ): void {
+ res.writeHead(status, {
+ 'Content-Type': 'application/json',
+ 'Cache-Control': 'no-store, private',
+ Pragma: 'no-cache',
+ 'X-Content-Type-Options': 'nosniff',
+ ...headers,
+ })
+ res.end(JSON.stringify(data))
+ }
+
/**
* Start the server.
*/
@@ -171,10 +444,10 @@ export class ContextMapperServer {
console.log(`[Server] GET /health - Health check`)
console.log(`[Server] GET /ready - Readiness check`)
console.log(`[Server] GET /api/v1/mcpservers - List all McpServers`)
+ console.log(`[Server] GET /api/v2/hosts/self/mcpservers - Host-scoped MCP inventory`)
console.log(
- `[Server] GET /api/v1/mcpservers/context/:contextRef - List McpServers by context`
+ `[Server] POST /api/v2/hosts/self/mcpservers/credential - Host-scoped MCP credential`
)
- console.log(`[Server] GET /api/v1/mcpservers/:name/auth - Get auth token for McpServer`)
console.log(`[Server] GET /api/v1/desktop/:hostRef - Desktop status`)
resolve()
})
@@ -200,14 +473,12 @@ export class ContextMapperServer {
'GET /health': "Health check endpoint - returns { status: 'ok', ready: boolean }",
'GET /ready': 'Readiness endpoint - returns 200 only after warm-up completes',
'GET /api/v1/mcpservers': 'List all McpServer resources',
- 'GET /api/v1/mcpservers/context/:contextRef':
- 'List McpServers filtered by contextRef (only enabled servers)',
- 'GET /api/v1/mcpservers/:name/auth': 'Get authentication token for a specific McpServer',
+ 'GET /api/v2/hosts/self/mcpservers': 'List MCP servers for the authenticated Host',
+ 'POST /api/v2/hosts/self/mcpservers/credential':
+ 'Get an authorized credential for the authenticated Host',
},
examples: {
listAll: `curl http://localhost:${this.port}/api/v1/mcpservers`,
- listByContext: `curl http://localhost:${this.port}/api/v1/mcpservers/context/dev-context`,
- getAuth: `curl http://localhost:${this.port}/api/v1/mcpservers/github/auth`,
},
stats: {
totalServers: this.provider.getAllServerInfos().length,
@@ -227,82 +498,23 @@ export class ContextMapperServer {
): Promise<void> {
console.log(`[Server] GET /api/v1/mcpservers`)
- const servers = this.provider.getAllServerInfos()
+ const servers = this.provider.getAllServerInfos().map(server => ({
+ name: server.name,
+ contextRef: server.contextRef,
+ transport: toPublicMcpTransport(server.transport),
+ enabled: server.enabled,
+ status: {
+ deployed: server.status.deployed,
+ ready: server.status.ready,
+ },
+ }))
const response: McpServersResponse = {
servers,
contextRef: '*',
timestamp: new Date().toISOString(),
}
- this.sendJson(res, 200, response)
- }
-
- /**
- * Handle GET /api/v1/mcpservers/context/:contextRef
- */
- private async handleListByContext(
- req: http.IncomingMessage,
- res: http.ServerResponse,
- contextRef: string
- ): Promise<void> {
- console.log(`[Server] GET /api/v1/mcpservers/context/${contextRef}`)
-
- if (!contextRef) {
- this.sendJson(res, 400, { error: 'Bad Request', message: 'contextRef is required' })
- return
- }
-
- const servers = await this.provider.getServerInfosByContext(contextRef)
- const response: McpServersResponse = {
- servers,
- contextRef,
- timestamp: new Date().toISOString(),
- }
-
- this.sendJson(res, 200, response)
- }
-
- /**
- * Handle GET /api/v1/mcpservers/:name/auth
- */
- private async handleGetAuth(
- req: http.IncomingMessage,
- res: http.ServerResponse,
- serverName: string
- ): Promise<void> {
- console.log(`[Server] GET /api/v1/mcpservers/${serverName}/auth`)
-
- if (!serverName) {
- this.sendJson(res, 400, { error: 'Bad Request', message: 'serverName is required' })
- return
- }
-
- // Find the server
- const servers = this.provider.getAllServerInfos()
- const server = servers.find(s => s.name === serverName)
-
- if (!server) {
- this.sendJson(res, 404, { error: 'Not Found', message: `McpServer ${serverName} not found` })
- return
- }
-
- // Get the auth token via provider
- const token = await this.provider.getAuthToken(serverName)
-
- if (!token) {
- // Check if auth was configured but not found vs not configured at all
- if (server.auth?.secretRef) {
- this.sendJson(res, 404, {
- error: 'Not Found',
- message: `Auth token for ${serverName} not found`,
- })
- } else {
- this.sendJson(res, 200, { token: null, message: 'No auth configured for this server' })
- }
- return
- }
-
- this.sendJson(res, 200, { token })
+ this.sendProtectedJson(res, 200, response)
}
/**
diff --git a/host-context-controller/src/types.ts b/host-context-controller/src/types.ts
index a7488dc7d..d71de8eb0 100644
--- a/host-context-controller/src/types.ts
+++ b/host-context-controller/src/types.ts
@@ -507,6 +507,11 @@ export interface McpServerStatus {
deployed: boolean
/** Whether the Deployment has at least one ready replica. */
ready: boolean
+ /**
+ * Whether this readiness observation is current and authoritative. Omitted
+ * when the status source cannot make that guarantee.
+ */
+ authoritative?: boolean
/** Human-readable status message. */
message?: string
}
diff --git a/host-context-controller/test/hostReconciler.lifecycle.test.ts b/host-context-controller/test/hostReconciler.lifecycle.test.ts
index d624bf4e2..e47108673 100644
--- a/host-context-controller/test/hostReconciler.lifecycle.test.ts
+++ b/host-context-controller/test/hostReconciler.lifecycle.test.ts
@@ -101,6 +101,7 @@ function makeHost(overrides?: Partial<HostCRD>): HostCRD {
return {
name: 'alpha-host',
namespace: 'mcp-host',
+ uid: 'alpha-host-uid',
spec: {
host: 'alpha-host',
contextRef: 'context-a',
@@ -117,6 +118,7 @@ function makeStatelessHost(
return {
name,
namespace: 'mcp-host',
+ uid: `${name}-uid`,
spec: {
host: name,
contextRef: 'context-a',
@@ -145,6 +147,7 @@ function hostApiObject(host: HostCRD) {
metadata: {
name: host.name,
namespace: host.namespace,
+ uid: host.uid,
resourceVersion: host.resourceVersion ?? '42',
annotations: host.annotations,
},
@@ -827,6 +830,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
expect(mintGfs).toHaveBeenCalledWith({ name: host.name, namespace: host.namespace })
expect(issueTokens).toHaveBeenCalledWith(
host.name,
+ host.uid,
expect.arrayContaining([
'workflow:list',
'workflow:read',
@@ -852,8 +856,8 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
const issueTokens = vi.mocked(issueMcpHostRuntimeTokens)
const defaultIssueTokens = issueTokens.getMockImplementation()
issueTokens.mockClear()
- issueTokens.mockImplementationOnce(async (hostName, scopes) => {
- const tokens = await defaultIssueTokens!(hostName, scopes)
+ issueTokens.mockImplementationOnce(async (hostName, hostUid, scopes) => {
+ const tokens = await defaultIssueTokens!(hostName, hostUid, scopes)
channelCount = 1
return tokens
})
@@ -861,8 +865,9 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
await reconciler.reconcile(host)
expect(issueTokens).toHaveBeenCalledTimes(2)
- expect(issueTokens.mock.calls[0][1]).not.toContain('workflow:trigger')
- expect(issueTokens.mock.calls[1][1]).toContain('workflow:trigger')
+ expect(issueTokens.mock.calls[0][1]).toBe(host.uid)
+ expect(issueTokens.mock.calls[0][2]).not.toContain('workflow:trigger')
+ expect(issueTokens.mock.calls[1][2]).toContain('workflow:trigger')
const deployment = hostDeploymentBody(appsApi, host.name)
expect(deployment.spec?.replicas).toBe(1)
expect(containerEnv(deployment).map(entry => entry.name)).not.toContain(
@@ -887,8 +892,8 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
const issueTokens = vi.mocked(issueMcpHostRuntimeTokens)
const defaultIssueTokens = issueTokens.getMockImplementation()
issueTokens.mockClear()
- issueTokens.mockImplementationOnce(async (hostName, scopes) => {
- const tokens = await defaultIssueTokens!(hostName, scopes)
+ issueTokens.mockImplementationOnce(async (hostName, hostUid, scopes) => {
+ const tokens = await defaultIssueTokens!(hostName, hostUid, scopes)
channelCount = 1
return tokens
})
@@ -896,8 +901,9 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
await reconciler.reconcile(host)
expect(issueTokens).toHaveBeenCalledTimes(2)
- expect(issueTokens.mock.calls[0][1]).not.toContain('workflow:trigger')
- expect(issueTokens.mock.calls[1][1]).toContain('workflow:trigger')
+ expect(issueTokens.mock.calls[0][1]).toBe(host.uid)
+ expect(issueTokens.mock.calls[0][2]).not.toContain('workflow:trigger')
+ expect(issueTokens.mock.calls[1][2]).toContain('workflow:trigger')
expect(
containerEnv(hostDeploymentBody(appsApi, host.name)).map(entry => entry.name)
).not.toContain('CLERUM_STATELESS_LIFECYCLE')
@@ -979,8 +985,9 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
await reconciler.reconcile(host)
expect(issueTokens).toHaveBeenCalledTimes(2)
- expect(issueTokens.mock.calls[0][1]).not.toContain('workflow:trigger')
- expect(issueTokens.mock.calls[1][1]).toContain('workflow:trigger')
+ expect(issueTokens.mock.calls[0][1]).toBe(host.uid)
+ expect(issueTokens.mock.calls[0][2]).not.toContain('workflow:trigger')
+ expect(issueTokens.mock.calls[1][2]).toContain('workflow:trigger')
const hostReplace = appsApi.replaceNamespacedDeployment.mock.calls.find(
([request]) => request.name === host.name
)?.[0].body as k8s.V1Deployment | undefined
diff --git a/host-context-controller/test/hostReconciler.test.ts b/host-context-controller/test/hostReconciler.test.ts
index ccb55d3a8..b8347b82e 100644
--- a/host-context-controller/test/hostReconciler.test.ts
+++ b/host-context-controller/test/hostReconciler.test.ts
@@ -104,6 +104,7 @@ function makeHost(overrides?: Partial<HostCRD>): HostCRD {
return {
name: 'alpha-host',
namespace: 'mcp-host',
+ uid: 'host-uid-1',
spec: {
host: 'alpha-host',
contextRef: 'context-a',
@@ -316,6 +317,7 @@ describe('HostReconciler', () => {
expect(reconciler.getStatus('alpha-host')).toMatchObject({ deployed: true, ready: true })
expect(issueMcpHostRuntimeTokens).toHaveBeenCalledWith(
'alpha-host',
+ 'host-uid-1',
DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES
)
})
@@ -430,6 +432,7 @@ describe('HostReconciler', () => {
expect(issueMcpHostRuntimeTokens).toHaveBeenCalledWith(
'alpha-host',
+ 'host-uid-1',
DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES
)
})
diff --git a/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts b/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts
index 33e81b51f..afc11f380 100644
--- a/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts
+++ b/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts
@@ -1,9 +1,18 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import jwt from 'jsonwebtoken'
+import { generateKeyPairSync } from 'node:crypto'
const ORIGINAL_FETCH = globalThis.fetch
const ORIGINAL_SECRET = process.env.INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET
const ORIGINAL_BASE_URL = process.env.CONTROL_API_BASE_URL
const ORIGINAL_TARGET_NAMESPACE = process.env.HCC_TARGET_NAMESPACE
+const ORIGINAL_PUBLIC_KEY = process.env.HCC_MCP_HOST_JWT_PUBLIC_KEY
+
+const keyPair = generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
+})
interface JwtClaims {
iss: string
@@ -19,7 +28,30 @@ async function loadIssuer() {
return mod.issueMcpHostRuntimeTokens
}
-function canonicalIssueResponse(access = 'a.b.c', refresh = 'd.e.f', control = 'g.h.i') {
+function validAccessToken(hostName = 'chatllm', hostUid = 'host-uid'): string {
+ return jwt.sign(
+ {
+ sub: 'mcp-host/standalone',
+ recipeNamespace: 'mcp-host',
+ recipeName: 'standalone',
+ hostRefs: [hostName],
+ host_uid: hostUid,
+ scope: 'workflow:approval:request',
+ workflowControlScopes: [],
+ mcpCapabilities: ['mcp:credential:read'],
+ },
+ keyPair.privateKey,
+ {
+ algorithm: 'RS256',
+ issuer: 'control-api',
+ audience: ['workflow-approvals', 'host-context-controller'],
+ expiresIn: 300,
+ jwtid: 'issuer-test-access',
+ }
+ )
+}
+
+function canonicalIssueResponse(access = validAccessToken(), refresh = 'd.e.f', control = 'g.h.i') {
return {
mcpHostAccessToken: access,
mcpHostRefreshToken: refresh,
@@ -53,6 +85,7 @@ describe('mcpHostRuntimeTokenIssuerClient (HCC)', () => {
vi.resetModules()
process.env.INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET = 'test-hcc-internal-control-secret'
process.env.CONTROL_API_BASE_URL = 'http://control-api.test:8090'
+ process.env.HCC_MCP_HOST_JWT_PUBLIC_KEY = keyPair.publicKey
delete process.env.HCC_TARGET_NAMESPACE
})
@@ -62,13 +95,14 @@ describe('mcpHostRuntimeTokenIssuerClient (HCC)', () => {
restoreEnv('INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET', ORIGINAL_SECRET)
restoreEnv('CONTROL_API_BASE_URL', ORIGINAL_BASE_URL)
restoreEnv('HCC_TARGET_NAMESPACE', ORIGINAL_TARGET_NAMESPACE)
+ restoreEnv('HCC_MCP_HOST_JWT_PUBLIC_KEY', ORIGINAL_PUBLIC_KEY)
})
it('throws when INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET is empty', async () => {
vi.resetModules()
process.env.INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET = ''
const issueMcpHostRuntimeTokens = await loadIssuer()
- await expect(issueMcpHostRuntimeTokens('chatllm')).rejects.toThrow(
+ await expect(issueMcpHostRuntimeTokens('chatllm', 'host-uid')).rejects.toThrow(
/INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET/
)
})
@@ -77,7 +111,23 @@ describe('mcpHostRuntimeTokenIssuerClient (HCC)', () => {
vi.resetModules()
process.env.INTERNAL_CONTROL_JWT_HCC_HMAC_SECRET = 'replace-with-real-internal-control-secret'
const issueMcpHostRuntimeTokens = await loadIssuer()
- await expect(issueMcpHostRuntimeTokens('chatllm')).rejects.toThrow(/placeholder value/)
+ await expect(issueMcpHostRuntimeTokens('chatllm', 'host-uid')).rejects.toThrow(
+ /placeholder value/
+ )
+ })
+
+ it('rejects non-canonical Host identity before making an issuance request', async () => {
+ const fetchMock = vi.fn()
+ globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch
+ const issueMcpHostRuntimeTokens = await loadIssuer()
+
+ await expect(issueMcpHostRuntimeTokens(' chatllm ', 'host-uid')).rejects.toThrow(
+ /canonical Host name/
+ )
+ await expect(issueMcpHostRuntimeTokens('chatllm', ' host-uid ')).rejects.toThrow(
+ /live Host UID/
+ )
+ expect(fetchMock).not.toHaveBeenCalled()
})
it('posts to the default sentinel issuance path with bearer InternalControl JWT', async () => {
@@ -88,20 +138,20 @@ describe('mcpHostRuntimeTokenIssuerClient (HCC)', () => {
globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch
const issueMcpHostRuntimeTokens = await loadIssuer()
- const result = await issueMcpHostRuntimeTokens('chatllm', [
+ const result = await issueMcpHostRuntimeTokens('chatllm', 'host-uid', [
'workflow:list',
'workflow:read',
'workflow:trigger',
])
- expect(result.accessToken).toBe('a.b.c')
+ expect(result.accessToken).toMatch(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/)
expect(result.refreshToken).toBe('d.e.f')
expect(result.mcpHostControlToken).toBe('g.h.i')
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('http://control-api.test:8090/api/v1/auth/mcp-host/mcp-host/standalone/tokens')
expect((init as RequestInit).body).toBe(
- '{"includeMcpHostControlToken":true,"host":"chatllm","workflowControlScopes":["workflow:list","workflow:read","workflow:trigger"]}'
+ '{"includeMcpHostControlToken":true,"host":"chatllm","hostUid":"host-uid","workflowControlScopes":["workflow:list","workflow:read","workflow:trigger"]}'
)
const headers = (init as RequestInit).headers as Record<string, string>
expect(headers['x-service-token']).toBeUndefined()
@@ -116,21 +166,17 @@ describe('mcpHostRuntimeTokenIssuerClient (HCC)', () => {
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('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 () => {
@@ -141,7 +187,7 @@ describe('mcpHostRuntimeTokenIssuerClient (HCC)', () => {
} as Response) as unknown as typeof globalThis.fetch
const issueMcpHostRuntimeTokens = await loadIssuer()
- await expect(issueMcpHostRuntimeTokens('chatllm')).rejects.toThrow(/HTTP 401/)
+ await expect(issueMcpHostRuntimeTokens('chatllm', 'host-uid')).rejects.toThrow(/HTTP 401/)
})
it('surfaces non-2xx responses without a response body', async () => {
@@ -152,8 +198,8 @@ describe('mcpHostRuntimeTokenIssuerClient (HCC)', () => {
} as Response) as unknown as typeof globalThis.fetch
const issueMcpHostRuntimeTokens = await loadIssuer()
- await expect(issueMcpHostRuntimeTokens('chatllm')).rejects.toThrow(
- 'mcpHost runtime token issuance failed: HTTP 403 for host "chatllm"'
+ await expect(issueMcpHostRuntimeTokens('chatllm', 'host-uid')).rejects.toThrow(
+ 'mcpHost runtime token issuance failed: HTTP 403'
)
})
@@ -167,8 +213,8 @@ describe('mcpHostRuntimeTokenIssuerClient (HCC)', () => {
} as unknown as Response) as unknown as typeof globalThis.fetch
const issueMcpHostRuntimeTokens = await loadIssuer()
- await expect(issueMcpHostRuntimeTokens('chatllm')).rejects.toThrow(
- 'mcpHost runtime token issuance failed: HTTP 500 for host "chatllm"'
+ await expect(issueMcpHostRuntimeTokens('chatllm', 'host-uid')).rejects.toThrow(
+ 'mcpHost runtime token issuance failed: HTTP 500'
)
})
@@ -176,7 +222,7 @@ describe('mcpHostRuntimeTokenIssuerClient (HCC)', () => {
globalThis.fetch = vi.fn().mockRejectedValue(new DOMException('Aborted', 'AbortError'))
const issueMcpHostRuntimeTokens = await loadIssuer()
- await expect(issueMcpHostRuntimeTokens('chatllm')).rejects.toThrow(/timed out/)
+ await expect(issueMcpHostRuntimeTokens('chatllm', 'host-uid')).rejects.toThrow(/timed out/)
})
it('aborts hung issuance requests after the request timeout', async () => {
@@ -189,20 +235,79 @@ describe('mcpHostRuntimeTokenIssuerClient (HCC)', () => {
}) as unknown as typeof globalThis.fetch
const issueMcpHostRuntimeTokens = await loadIssuer()
- const result = issueMcpHostRuntimeTokens('chatllm')
+ const result = issueMcpHostRuntimeTokens('chatllm', 'host-uid')
const expectation = expect(result).rejects.toThrow(/timed out/)
await vi.advanceTimersByTimeAsync(10_000)
await expectation
})
- it('rejects empty access/refresh in response body', async () => {
+ it('rejects empty access/refresh/control JWTs in the response body', async () => {
+ globalThis.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => canonicalIssueResponse('', '', ''),
+ } as Response) as unknown as typeof globalThis.fetch
+
+ const issueMcpHostRuntimeTokens = await loadIssuer()
+ await expect(issueMcpHostRuntimeTokens('chatllm', 'host-uid')).rejects.toThrow(
+ /missing required fields/
+ )
+ })
+
+ it('rejects non-positive or non-integer credential expiry fields', async () => {
+ globalThis.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ ...canonicalIssueResponse(),
+ expiresInSeconds: { access: 0, refresh: 3600, control: 600 },
+ }),
+ } as Response) as unknown as typeof globalThis.fetch
+
+ const issueMcpHostRuntimeTokens = await loadIssuer()
+ await expect(issueMcpHostRuntimeTokens('chatllm', 'host-uid')).rejects.toThrow(
+ /invalid expiry fields/
+ )
+ })
+
+ it('rejects a cryptographically valid but differently bound access token', async () => {
+ const mismatchedToken = validAccessToken('other-host', 'other-uid')
+ globalThis.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => canonicalIssueResponse(mismatchedToken),
+ } as Response) as unknown as typeof globalThis.fetch
+
+ const issueMcpHostRuntimeTokens = await loadIssuer()
+ await expect(issueMcpHostRuntimeTokens('chatllm', 'host-uid')).rejects.toThrow(
+ /identity does not match/
+ )
+ })
+
+ it('rejects a workflow-only access token from an incompatible issuer rollout', async () => {
+ const workflowOnlyToken = jwt.sign(
+ {
+ sub: 'mcp-host/standalone',
+ recipeNamespace: 'mcp-host',
+ recipeName: 'standalone',
+ hostRefs: ['chatllm'],
+ host_uid: 'host-uid',
+ scope: 'workflow:approval:request',
+ workflowControlScopes: [],
+ },
+ keyPair.privateKey,
+ {
+ algorithm: 'RS256',
+ issuer: 'control-api',
+ audience: 'workflow-approvals',
+ expiresIn: 300,
+ jwtid: 'issuer-test-workflow-only',
+ }
+ )
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
- json: async () => ({ mcpHostAccessToken: '', mcpHostRefreshToken: '' }),
+ json: async () => canonicalIssueResponse(workflowOnlyToken),
} as Response) as unknown as typeof globalThis.fetch
const issueMcpHostRuntimeTokens = await loadIssuer()
- await expect(issueMcpHostRuntimeTokens('chatllm')).rejects.toThrow(/missing required fields/)
+ await expect(issueMcpHostRuntimeTokens('chatllm', 'host-uid')).rejects.toThrow(/unauthorized/)
})
})
diff --git a/mcp-host/src/__tests__/main.mcpInitialization.test.ts b/mcp-host/src/__tests__/main.mcpInitialization.test.ts
index c90bad869..f2c3af1cf 100644
--- a/mcp-host/src/__tests__/main.mcpInitialization.test.ts
+++ b/mcp-host/src/__tests__/main.mcpInitialization.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, it, vi } from 'vitest'
import {
admitDevelopmentMcpServers,
createCoalescedPollRunner,
+ createMcpAuthorityStalenessDeadline,
+ isMcpAuthorityStale,
startContextMapperPolling,
stopContextMapperPolling,
} from '../main'
@@ -88,14 +90,13 @@ describe('runAuthoritativeMcpInitialization', () => {
effects.push('ready')
return true
}),
- listServersByContext: vi.fn(async () => {
+ listServersForHost: vi.fn(async () => {
effects.push('snapshot')
return []
}),
}
await runAuthoritativeMcpInitialization({
- contextRef: 'production',
client,
replaceFleet: async servers => {
effects.push('replace')
@@ -121,10 +122,9 @@ describe('runAuthoritativeMcpInitialization', () => {
await expect(
runAuthoritativeMcpInitialization({
- contextRef: 'production',
client: {
healthCheck: vi.fn().mockResolvedValue(true),
- listServersByContext: vi.fn().mockRejectedValue(discoveryError),
+ listServersForHost: vi.fn().mockRejectedValue(discoveryError),
},
replaceFleet,
sleep: vi.fn(),
@@ -170,10 +170,9 @@ describe('runAuthoritativeMcpInitialization', () => {
)
const initialization = runAuthoritativeMcpInitialization({
- contextRef: 'production',
client: {
healthCheck: vi.fn().mockResolvedValue(true),
- listServersByContext: vi.fn(async () => {
+ listServersForHost: vi.fn(async () => {
discoveryStarted.resolve()
return delayedDiscovery.promise
}),
@@ -203,12 +202,11 @@ describe('runAuthoritativeMcpInitialization', () => {
const replaceFleet = vi.fn()
const sleep = vi.fn().mockResolvedValue(undefined)
const healthCheck = vi.fn().mockResolvedValue(false)
- const listServersByContext = vi.fn()
+ const listServersForHost = vi.fn()
await expect(
runAuthoritativeMcpInitialization({
- contextRef: 'production',
- client: { healthCheck, listServersByContext },
+ client: { healthCheck, listServersForHost },
replaceFleet,
sleep,
maxRetries: 2,
@@ -217,7 +215,7 @@ describe('runAuthoritativeMcpInitialization', () => {
expect(healthCheck).toHaveBeenCalledTimes(2)
expect(sleep).toHaveBeenCalledTimes(1)
- expect(listServersByContext).not.toHaveBeenCalled()
+ expect(listServersForHost).not.toHaveBeenCalled()
expect(replaceFleet).not.toHaveBeenCalled()
})
})
@@ -525,16 +523,80 @@ describe('context-mapper polling lifecycle', () => {
it('keeps exactly one interval producer when polling is started again', () => {
vi.useFakeTimers()
try {
- startContextMapperPolling('first-context')
+ startContextMapperPolling()
expect(vi.getTimerCount()).toBe(1)
- startContextMapperPolling('replacement-context')
+ startContextMapperPolling()
expect(vi.getTimerCount()).toBe(1)
} finally {
stopContextMapperPolling()
vi.useRealTimers()
}
})
+
+ it('bounds transient authority preservation to the configured staleness window', () => {
+ expect(isMcpAuthorityStale(1_000, 60_999, 60_000)).toBe(false)
+ expect(isMcpAuthorityStale(1_000, 61_000, 60_000)).toBe(true)
+ expect(isMcpAuthorityStale(0, 1_000_000, 60_000)).toBe(false)
+ expect(isMcpAuthorityStale(1_000, 61_000, 0)).toBe(false)
+ })
+
+ it('revokes at the absolute staleness deadline without waiting for another poll', () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-08-16T00:00:00.000Z'))
+ try {
+ const expired = vi.fn()
+ const deadline = createMcpAuthorityStalenessDeadline(60_000, expired)
+
+ deadline.recordSuccess()
+ vi.advanceTimersByTime(59_999)
+ expect(expired).not.toHaveBeenCalled()
+
+ vi.advanceTimersByTime(1)
+ expect(expired).toHaveBeenCalledTimes(1)
+ } finally {
+ vi.clearAllTimers()
+ vi.useRealTimers()
+ }
+ })
+
+ it('moves the absolute deadline forward only after a newer authoritative success', () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-08-16T00:00:00.000Z'))
+ try {
+ const expired = vi.fn()
+ const deadline = createMcpAuthorityStalenessDeadline(60_000, expired)
+
+ deadline.recordSuccess()
+ vi.advanceTimersByTime(50_000)
+ deadline.recordSuccess()
+ vi.advanceTimersByTime(10_000)
+ expect(expired).not.toHaveBeenCalled()
+
+ vi.advanceTimersByTime(50_000)
+ expect(expired).toHaveBeenCalledTimes(1)
+ } finally {
+ vi.clearAllTimers()
+ vi.useRealTimers()
+ }
+ })
+
+ it('cancels the absolute deadline when authority is withdrawn explicitly', () => {
+ vi.useFakeTimers()
+ try {
+ const expired = vi.fn()
+ const deadline = createMcpAuthorityStalenessDeadline(60_000, expired)
+
+ deadline.recordSuccess()
+ deadline.clear()
+ vi.advanceTimersByTime(60_000)
+
+ expect(expired).not.toHaveBeenCalled()
+ } finally {
+ vi.clearAllTimers()
+ vi.useRealTimers()
+ }
+ })
})
describe('replaceAuthoritativeMcpFleet', () => {
@@ -1530,6 +1592,54 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
expect(serverState.get(modified.name)).toBe(JSON.stringify(modified))
})
+ it('revokes the old bearer before admitting a changed credential revision', async () => {
+ const previous = readyServer({
+ auth: undefined,
+ authRequired: true,
+ credentialRevision: 'credential-revision-1',
+ })
+ const rotated = readyServer({
+ auth: undefined,
+ authRequired: true,
+ credentialRevision: 'credential-revision-2',
+ })
+ const connected = new Set([previous.name])
+ const effects: string[] = []
+ const manager = {
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(async (_server, authToken) => {
+ effects.push(`replace:${authToken}`)
+ connected.add(rotated.name)
+ }),
+ removeServer: vi.fn(),
+ detachServer: vi.fn((name: string) => {
+ effects.push('detach')
+ connected.delete(name)
+ return vi.fn().mockResolvedValue(undefined)
+ }),
+ getConnectedServers: vi.fn(() => [...connected]),
+ getKnownServers: vi.fn(() => [previous.name]),
+ recordAdmissionFailure: vi.fn(),
+ }
+ const getAuthToken = vi.fn(async () => {
+ effects.push('credential')
+ return 'rotated-token'
+ })
+ const serverState = new Map([[previous.name, JSON.stringify(previous)]])
+
+ await reconcileAuthoritativeMcpSnapshot({
+ servers: [rotated],
+ manager,
+ serverState,
+ getAuthToken,
+ })
+
+ expect(effects[0]).toBe('detach')
+ expect(getAuthToken).toHaveBeenCalledWith(rotated.name, 'credential-revision-2')
+ expect(effects).toEqual(['detach', 'credential', 'replace:rotated-token'])
+ expect(serverState.get(rotated.name)).toBe(JSON.stringify(rotated))
+ })
+
it('does not tear down a healthy connection for a status-only readiness degradation', async () => {
const previous = readyServer()
const degraded = readyServer({
diff --git a/mcp-host/src/config.hccAuthority.test.ts b/mcp-host/src/config.hccAuthority.test.ts
new file mode 100644
index 000000000..6b512225b
--- /dev/null
+++ b/mcp-host/src/config.hccAuthority.test.ts
@@ -0,0 +1,37 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+const originalEnv = process.env
+
+async function loadAuthorityMaxStaleness(value: string | undefined): Promise<number> {
+ vi.resetModules()
+ process.env = { ...originalEnv }
+ if (value === undefined) {
+ delete process.env.HCC_AUTHORITY_MAX_STALENESS_MS
+ } else {
+ process.env.HCC_AUTHORITY_MAX_STALENESS_MS = value
+ }
+ return (await import('./config')).config.hccAuthorityMaxStalenessMs
+}
+
+afterEach(() => {
+ process.env = originalEnv
+ vi.resetModules()
+})
+
+describe('HCC_AUTHORITY_MAX_STALENESS_MS', () => {
+ it('defaults to the 60-second authority ceiling', async () => {
+ await expect(loadAuthorityMaxStaleness(undefined)).resolves.toBe(60_000)
+ })
+
+ it('allows an operator to fail closed sooner', async () => {
+ await expect(loadAuthorityMaxStaleness('15000')).resolves.toBe(15_000)
+ })
+
+ it('cannot be configured beyond the 60-second authority ceiling', async () => {
+ await expect(loadAuthorityMaxStaleness('120000')).resolves.toBe(60_000)
+ })
+
+ it('uses the safe ceiling for an invalid value', async () => {
+ await expect(loadAuthorityMaxStaleness('not-a-duration')).resolves.toBe(60_000)
+ })
+})
diff --git a/mcp-host/src/config.ts b/mcp-host/src/config.ts
index d918e2148..a597ed40f 100644
--- a/mcp-host/src/config.ts
+++ b/mcp-host/src/config.ts
@@ -73,6 +73,10 @@ export interface Config {
// Context Mapper poll interval in ms (for production mode)
contextMapperPollInterval: number
+ // Maximum time an already-published MCP fleet may survive without a fresh,
+ // authenticated HCC inventory snapshot.
+ hccAuthorityMaxStalenessMs: number
+
// MCP server health heartbeat interval in ms. mcp-host periodically
// tools/list's each connected server to keep observedAt fresh and detect
// silent failures. Must stay well under the desktop's 120s stale threshold.
@@ -552,6 +556,14 @@ export const config: Config = {
// Context Mapper poll interval (default 30 seconds)
contextMapperPollInterval: parseInt(getEnv('CLERUM_CONTEXT_MAPPER_POLL_INTERVAL', '30000')!, 10),
+ // Bound transient HCC/Kubernetes authority outages. Identity failures revoke
+ // immediately; 5xx/transport failures may preserve the last good fleet only
+ // within this finite window.
+ hccAuthorityMaxStalenessMs: Math.min(
+ getEnvNumber('HCC_AUTHORITY_MAX_STALENESS_MS', 60_000),
+ 60_000
+ ),
+
// MCP status heartbeat. Defaults to 30 seconds so a single missed tick does
// not trip desktop staleness.
mcpStatusHeartbeatInterval: parseInt(
diff --git a/mcp-host/src/contextMapperClient.test.ts b/mcp-host/src/contextMapperClient.test.ts
index 61c78e97c..5f1077044 100644
--- a/mcp-host/src/contextMapperClient.test.ts
+++ b/mcp-host/src/contextMapperClient.test.ts
@@ -1,13 +1,56 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { ContextMapperClient } from './contextMapperClient'
+import {
+ type ContextMapperAuthentication,
+ ContextMapperClient,
+ ContextMapperCredentialRevisionError,
+ ContextMapperRequestError,
+ isContextMapperAuthorityRevocation,
+ isContextMapperInventoryAuthorityRevocation,
+} from './contextMapperClient'
-describe('ContextMapperClient readiness and discovery', () => {
+function authentication(overrides: Partial<ContextMapperAuthentication> = {}) {
+ let accessToken = 'access-v1'
+ const auth: ContextMapperAuthentication & { setAccessToken(token: string): void } = {
+ getAccessToken: () => accessToken,
+ refreshOnUnauthorized: vi.fn(async () => {
+ accessToken = 'access-v2'
+ }),
+ onCallerAuthorizationFailure: vi.fn(),
+ setAccessToken: token => {
+ accessToken = token
+ },
+ ...overrides,
+ }
+ return auth
+}
+
+function authorizedServer(overrides: Record<string, unknown> = {}) {
+ return {
+ name: 'secured-server',
+ description: 'Scoped server',
+ transport: { type: 'streamableHttp', url: 'http://secured-server.test/mcp' },
+ enabled: true,
+ status: { deployed: true, ready: true },
+ authRequired: true,
+ credentialRevision: 'revision-1',
+ ...overrides,
+ }
+}
+
+function inventory(servers: unknown[] = [authorizedServer()]) {
+ return {
+ servers,
+ timestamp: '2026-08-16T10:00:00.000Z',
+ }
+}
+
+describe('ContextMapperClient Host-scoped v2 inventory', () => {
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
- it('uses the readiness endpoint before treating inventory as authoritative', async () => {
+ it('keeps readiness anonymous', async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
const client = new ContextMapperClient('http://context-mapper.test')
@@ -19,199 +62,338 @@ describe('ContextMapperClient readiness and discovery', () => {
)
})
- it('rejects an HTTP 503 during initial discovery instead of returning an empty fleet', 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' }
- )
- )
+ it('uses the live Host bearer and v2 self route without a caller Context', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(inventory()), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ })
)
- const client = new ContextMapperClient('http://context-mapper.test')
+ vi.stubGlobal('fetch', fetchMock)
+ const client = new ContextMapperClient('http://context-mapper.test/', {
+ authentication: authentication(),
+ })
- await expect(client.listServersByContext('production')).rejects.toThrow(
- 'HTTP 503: Service Unavailable'
- )
- })
+ await expect(client.listServersForHost()).resolves.toEqual([authorizedServer()])
- it('rejects a network failure during initial discovery instead of returning an empty fleet', async () => {
- const networkError = new Error('connection reset')
- vi.stubGlobal('fetch', vi.fn().mockRejectedValue(networkError))
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.listServersByContext('production')).rejects.toBe(networkError)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]
+ expect(url).toBe('http://context-mapper.test/api/v2/hosts/self/mcpservers')
+ expect(url).not.toContain('/api/v1/')
+ expect(url).not.toContain('/context/')
+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer access-v1')
})
- it('accepts an HTTP 200 empty initial inventory as authoritative', async () => {
+ it('preserves an optional bounded transport port from the v2 inventory', async () => {
+ const server = authorizedServer({
+ transport: {
+ type: 'streamableHttp',
+ url: 'http://secured-server.test/mcp',
+ port: 3443,
+ },
+ })
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
- new Response(
- JSON.stringify({
- servers: [],
- contextRef: 'production',
- timestamp: '2026-07-29T10:00:00.000Z',
- }),
- { status: 200 }
- )
+ new Response(JSON.stringify(inventory([server])), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ })
)
)
- 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.listServersForHost()).resolves.toEqual([server])
})
- 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.each([0, -1, 1.5, 65_536, '3443', null])(
+ 'rejects malformed v2 transport port %j',
+ async port => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify(
+ inventory([
+ authorizedServer({
+ transport: { type: 'streamableHttp', port },
+ }),
+ ])
+ ),
+ { status: 200, headers: { 'Content-Type': 'application/json' } }
+ )
+ )
+ )
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: authentication(),
+ })
+
+ await expect(client.listServersForHost()).rejects.toThrow(
+ 'HCC inventory response contains an invalid transport port'
+ )
+ }
+ )
- await expect(client.listAllServers()).rejects.toBe(networkError)
+ it('refreshes once on 401 and retries with the current shared access token', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ error: 'unauthorized' }), { status: 401 })
+ )
+ .mockResolvedValueOnce(new Response(JSON.stringify(inventory()), { status: 200 }))
+ vi.stubGlobal('fetch', fetchMock)
+ const auth = authentication()
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: auth,
+ })
+
+ await expect(client.pollServers()).resolves.toEqual(inventory())
+
+ expect(auth.refreshOnUnauthorized).toHaveBeenCalledTimes(1)
+ expect((fetchMock.mock.calls[0]![1]!.headers as Record<string, string>).Authorization).toBe(
+ 'Bearer access-v1'
+ )
+ expect((fetchMock.mock.calls[1]![1]!.headers as Record<string, string>).Authorization).toBe(
+ 'Bearer access-v2'
+ )
})
- 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('revokes caller authority after a persistent 401', async () => {
vi.stubGlobal(
'fetch',
vi
.fn()
- .mockResolvedValue(new Response('', { status: 503, statusText: 'Service Unavailable' }))
+ .mockResolvedValue(new Response(JSON.stringify({ error: 'unauthorized' }), { status: 401 }))
)
+ const auth = authentication()
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: auth,
+ })
+
+ await expect(client.pollServers()).rejects.toMatchObject({
+ status: 401,
+ authorizationFailure: true,
+ })
+ expect(auth.refreshOnUnauthorized).toHaveBeenCalledTimes(1)
+ expect(auth.onCallerAuthorizationFailure).toHaveBeenCalledWith(401)
+ })
+
+ it('revokes immediately on 403 without trying token refresh', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 403 })))
+ const auth = authentication()
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: auth,
+ })
+
+ await expect(client.pollServers()).rejects.toBeInstanceOf(ContextMapperRequestError)
+ expect(auth.refreshOnUnauthorized).not.toHaveBeenCalled()
+ expect(auth.onCallerAuthorizationFailure).toHaveBeenCalledWith(403)
+ })
+
+ it('fails closed before transport when no Host bearer is configured', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
const client = new ContextMapperClient('http://context-mapper.test')
- await expect(client.listAllServers()).rejects.toThrow(/503/)
+ await expect(client.pollServers()).rejects.toMatchObject({
+ status: 401,
+ authorizationFailure: true,
+ })
+ expect(fetchMock).not.toHaveBeenCalled()
})
-})
-describe('ContextMapperClient.pollServers', () => {
- afterEach(() => {
- vi.restoreAllMocks()
- vi.unstubAllGlobals()
+ it('revokes locally before transport when the live Host bearer is unavailable', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ const auth = authentication({ getAccessToken: () => '' })
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: auth,
+ })
+
+ await expect(client.getAuthToken('secured-server', 'revision-1')).rejects.toMatchObject({
+ status: 401,
+ kind: 'credential',
+ authorizationFailure: true,
+ })
+ expect(auth.onCallerAuthorizationFailure).toHaveBeenCalledWith(401)
+ expect(fetchMock).not.toHaveBeenCalled()
})
- it('rejects an HTTP 503 instead of fabricating an authoritative empty fleet', async () => {
+ it('preserves an unavailable controller as a typed non-authoritative failure', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 503 })))
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: authentication(),
+ })
+
+ await expect(client.pollServers()).rejects.toMatchObject({
+ status: 503,
+ kind: 'inventory',
+ authorizationFailure: false,
+ })
+ })
+
+ it('classifies an opaque inventory 404 as complete Host authority revocation', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 404 })))
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: authentication(),
+ })
+
+ const error = await client.pollServers().catch(cause => cause)
+
+ expect(error).toMatchObject({ status: 404, kind: 'inventory' })
+ expect(isContextMapperInventoryAuthorityRevocation(error)).toBe(true)
+ expect(isContextMapperAuthorityRevocation(error)).toBe(false)
+ })
+
+ it('rejects forbidden Context or Secret metadata in a successful inventory', 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({
+ contextRef: 'foreign-context',
+ auth: { type: 'bearer', secretRef: 'foreign-secret' },
+ }),
+ ])
+ ),
+ { 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) => {
return new Promise((_resolve, reject) => {
const signal = init?.signal
- if (!signal) return
- signal.addEventListener(
+ signal?.addEventListener(
'abort',
- () =>
- reject(signal.reason ?? new DOMException('The operation was aborted', 'AbortError')),
+ () => reject(signal.reason ?? new DOMException('aborted', 'AbortError')),
{ once: true }
)
})
})
)
- const client = new ContextMapperClient('http://context-mapper.test', 10)
-
- await expect(client.pollServers('production')).rejects.toMatchObject({ name: 'TimeoutError' })
- })
-
- it('accepts an HTTP 200 empty fleet as an authoritative deletion snapshot', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue(
- new Response(
- JSON.stringify({
- servers: [],
- contextRef: 'production',
- timestamp: '2026-07-29T10:00:00.000Z',
- }),
- { status: 200 }
- )
- )
- )
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.pollServers('production')).resolves.toEqual({
- servers: [],
- timestamp: '2026-07-29T10:00:00.000Z',
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ requestTimeoutMs: 10,
+ authentication: authentication(),
})
+
+ await expect(client.pollServers()).rejects.toMatchObject({ name: 'TimeoutError' })
})
})
-describe('ContextMapperClient.getAuthToken', () => {
+describe('ContextMapperClient scoped credential retrieval', () => {
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
- it('rejects an HTTP failure instead of treating it as an unauthenticated server', async () => {
- vi.stubGlobal(
- 'fetch',
- vi
- .fn()
- .mockResolvedValue(new Response(null, { status: 503, statusText: 'Service Unavailable' }))
+ it('posts only the server selector and validates the inventory revision', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ token: 'upstream-token', credentialRevision: 'revision-1' }), {
+ status: 200,
+ })
)
- const client = new ContextMapperClient('http://context-mapper.test')
+ vi.stubGlobal('fetch', fetchMock)
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: authentication(),
+ })
- await expect(client.getAuthToken('secured-server')).rejects.toThrow(
- 'HTTP 503: Service Unavailable'
+ await expect(client.getAuthToken('secured-server', 'revision-1')).resolves.toBe(
+ 'upstream-token'
)
- })
- it('rejects a network failure instead of treating it as an unauthenticated server', async () => {
- const networkError = new Error('connection reset')
- vi.stubGlobal('fetch', vi.fn().mockRejectedValue(networkError))
- const client = new ContextMapperClient('http://context-mapper.test')
-
- await expect(client.getAuthToken('secured-server')).rejects.toBe(networkError)
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]
+ expect(url).toBe('http://context-mapper.test/api/v2/hosts/self/mcpservers/credential')
+ expect(init.method).toBe('POST')
+ expect(JSON.parse(String(init.body))).toEqual({ serverName: 'secured-server' })
+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer access-v1')
})
- it('rejects an authoritative missing token for a server that requested auth', async () => {
+ it('rejects a credential read whose post-read authority revision changed', async () => {
vi.stubGlobal(
'fetch',
- vi.fn().mockResolvedValue(new Response(null, { status: 404, statusText: 'Not Found' }))
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ token: 'discard-me', credentialRevision: 'revision-2' }), {
+ status: 200,
+ })
+ )
)
- const client = new ContextMapperClient('http://context-mapper.test')
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: authentication(),
+ })
- await expect(client.getAuthToken('secured-server')).rejects.toThrow('HTTP 404: Not Found')
+ const result = client.getAuthToken('secured-server', 'revision-1')
+ const error = await result.catch(value => value)
+ expect(error).toBeInstanceOf(ContextMapperCredentialRevisionError)
+ expect(isContextMapperAuthorityRevocation(error)).toBe(true)
})
- it('retains HTTP 200 token:null as the explicit no-auth response', async () => {
+ it('rejects a credential read without an inventory authority revision before transport', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: authentication(),
+ })
+
+ const error = await client.getAuthToken('secured-server').catch(cause => cause)
+
+ expect(error).toBeInstanceOf(ContextMapperCredentialRevisionError)
+ expect(isContextMapperAuthorityRevocation(error)).toBe(true)
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('retains token:null as the explicit allowed no-auth response', async () => {
vi.stubGlobal(
'fetch',
- vi.fn().mockResolvedValue(new Response(JSON.stringify({ token: null }), { status: 200 }))
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ token: null, credentialRevision: 'revision-1' }), {
+ status: 200,
+ })
+ )
)
- const client = new ContextMapperClient('http://context-mapper.test')
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: authentication(),
+ })
+
+ await expect(client.getAuthToken('open-server', 'revision-1')).resolves.toBeUndefined()
+ })
+
+ it('classifies an opaque credential 404 as target authority revocation', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 404 })))
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: authentication(),
+ })
- await expect(client.getAuthToken('open-server')).resolves.toBeUndefined()
+ const error = await client.getAuthToken('foreign-server', 'revision-1').catch(value => value)
+ expect(error).toMatchObject({ status: 404, kind: 'credential' })
+ expect(isContextMapperAuthorityRevocation(error)).toBe(true)
+ expect(String(error)).not.toContain('foreign-server')
})
})
diff --git a/mcp-host/src/contextMapperClient.ts b/mcp-host/src/contextMapperClient.ts
index 6aeefb5d0..9173dcafc 100644
--- a/mcp-host/src/contextMapperClient.ts
+++ b/mcp-host/src/contextMapperClient.ts
@@ -9,16 +9,163 @@ import { McpServerInfo } from './types'
export interface McpServersResponse {
servers: McpServerInfo[]
- contextRef: string
timestamp: string
}
export interface AuthTokenResponse {
token: string | null
- message?: string
+ credentialRevision: string
}
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>
+ 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')
+ }
+
+ 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 }
+ : {}),
+ 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.
@@ -26,97 +173,132 @@ const DEFAULT_CONTEXT_MAPPER_REQUEST_TIMEOUT_MS = 10_000
export class ContextMapperClient {
private baseUrl: string
private requestTimeoutMs: number
+ private authentication?: ContextMapperAuthentication
- constructor(baseUrl: string, requestTimeoutMs = DEFAULT_CONTEXT_MAPPER_REQUEST_TIMEOUT_MS) {
+ constructor(
+ baseUrl: string,
+ options: number | ContextMapperClientOptions = DEFAULT_CONTEXT_MAPPER_REQUEST_TIMEOUT_MS
+ ) {
this.baseUrl = baseUrl.replace(/\/$/, '') // Remove trailing slash
- this.requestTimeoutMs = requestTimeoutMs
+ this.requestTimeoutMs =
+ typeof options === 'number'
+ ? options
+ : (options.requestTimeoutMs ?? DEFAULT_CONTEXT_MAPPER_REQUEST_TIMEOUT_MS)
+ this.authentication = typeof options === 'number' ? undefined : options.authentication
}
- private fetch(input: string): Promise<Response> {
+ private fetch(input: string, init: RequestInit = {}): Promise<Response> {
return fetch(input, {
+ ...init,
signal: AbortSignal.timeout(this.requestTimeoutMs),
})
}
- /**
- * Health check.
- */
- async healthCheck(): Promise<boolean> {
+ private accessToken(kind: ContextMapperRequestKind): string {
+ let token = ''
try {
- const response = await this.fetch(`${this.baseUrl}/ready`)
- return response.ok
- } catch (error) {
- console.error('[ContextMapper] Health check failed:', error)
- return false
+ token = this.authentication?.getAccessToken().trim() ?? ''
+ } catch {
+ // Treat an unreadable local credential exactly like an HCC rejection:
+ // revoke any already-published fleet before returning to the caller.
}
+ if (!token) {
+ this.authentication?.onCallerAuthorizationFailure?.(401)
+ throw new ContextMapperRequestError(401, kind, true)
+ }
+ return token
}
- /**
- * List all McpServers.
- * Rejects transport and HTTP failures so a future caller cannot confuse an
- * unavailable controller with an authoritative empty fleet.
- */
- async listAllServers(): Promise<McpServerInfo[]> {
- console.log('[ContextMapper] Fetching all McpServers')
+ private async protectedFetch(
+ path: string,
+ kind: ContextMapperRequestKind,
+ init: RequestInit = {}
+ ): Promise<Response> {
+ let retriedAfterRefresh = false
+ for (;;) {
+ const response = await this.fetch(`${this.baseUrl}${path}`, {
+ ...init,
+ headers: {
+ Accept: 'application/json',
+ ...init.headers,
+ Authorization: `Bearer ${this.accessToken(kind)}`,
+ },
+ })
- const response = await this.fetch(`${this.baseUrl}/api/v1/mcpservers`)
+ if (response.status === 401 && !retriedAfterRefresh && this.authentication) {
+ retriedAfterRefresh = true
+ try {
+ await this.authentication.refreshOnUnauthorized()
+ } catch {
+ this.authentication.onCallerAuthorizationFailure?.(401)
+ throw new ContextMapperRequestError(401, kind, true)
+ }
+ continue
+ }
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}: ${response.statusText}`)
+ if (response.status === 401 || response.status === 403) {
+ this.authentication?.onCallerAuthorizationFailure?.(response.status)
+ throw new ContextMapperRequestError(response.status, kind, true)
+ }
+ if (!response.ok) {
+ throw new ContextMapperRequestError(response.status, kind, false)
+ }
+ return response
}
-
- const data = (await response.json()) as McpServersResponse
- console.log(`[ContextMapper] Found ${data.servers.length} McpServer(s)`)
- return data.servers
}
/**
- * List McpServers by contextRef.
- * Rejects unavailable or invalid responses so callers cannot confuse a
- * failed discovery request with an authoritative empty inventory.
+ * Health check.
*/
- async listServersByContext(contextRef: string): Promise<McpServerInfo[]> {
- console.log(`[ContextMapper] Fetching McpServers for context: ${contextRef}`)
-
- const response = await this.fetch(
- `${this.baseUrl}/api/v1/mcpservers/context/${encodeURIComponent(contextRef)}`
- )
-
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}: ${response.statusText}`)
+ async healthCheck(): Promise<boolean> {
+ try {
+ const response = await this.fetch(`${this.baseUrl}/ready`)
+ return response.ok
+ } catch {
+ console.error('[ContextMapper] Health check failed (reason=transport)')
+ return false
}
+ }
- const data = (await response.json()) as McpServersResponse
- console.log(
- `[ContextMapper] Found ${data.servers.length} McpServer(s) for context ${contextRef}`
- )
- console.log(`[ContextMapper] Response:`, JSON.stringify(data, null, 2))
+ /**
+ * List only the McpServers authorized for the authenticated Host. The old
+ * global/context-selecting v1 routes are intentionally not represented by
+ * this client.
+ */
+ async listServersForHost(): Promise<McpServerInfo[]> {
+ const response = await this.protectedFetch('/api/v2/hosts/self/mcpservers', 'inventory')
+ const data = decodeInventoryResponse(await response.json())
+ console.log(`[ContextMapper] Received ${data.servers.length} authorized MCP server(s)`)
return data.servers
}
/**
* Get auth token for an McpServer.
*/
- async getAuthToken(serverName: string): Promise<string | undefined> {
- console.log(`[ContextMapper] Fetching auth token for server: ${serverName}`)
-
- const response = await this.fetch(
- `${this.baseUrl}/api/v1/mcpservers/${encodeURIComponent(serverName)}/auth`
- )
-
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}: ${response.statusText}`)
+ async getAuthToken(
+ serverName: string,
+ expectedCredentialRevision?: string
+ ): Promise<string | undefined> {
+ if (!expectedCredentialRevision) {
+ throw new ContextMapperCredentialRevisionError()
}
-
- const data = (await response.json()) as AuthTokenResponse
-
- if (data.token) {
- console.log(`[ContextMapper] Found auth token for server: ${serverName}`)
- return data.token
+ const response = await this.protectedFetch(
+ '/api/v2/hosts/self/mcpservers/credential',
+ 'credential',
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ serverName }),
+ }
+ )
+ const data = decodeCredentialResponse(await response.json())
+ if (
+ expectedCredentialRevision !== undefined &&
+ data.credentialRevision !== expectedCredentialRevision
+ ) {
+ throw new ContextMapperCredentialRevisionError()
}
-
- console.log(`[ContextMapper] No auth token for server: ${serverName}`)
- return undefined
+ return data.token ?? undefined
}
/**
@@ -125,16 +307,9 @@ export class ContextMapperClient {
* so callers preserve their last known fleet instead of treating an
* unavailable controller as an authoritative empty inventory.
*/
- async pollServers(contextRef: string): Promise<{ servers: McpServerInfo[]; timestamp: string }> {
- const response = await this.fetch(
- `${this.baseUrl}/api/v1/mcpservers/context/${encodeURIComponent(contextRef)}`
- )
-
- if (!response.ok) {
- throw new Error(`HTTP ${response.status}: ${response.statusText}`)
- }
-
- const data = (await response.json()) as McpServersResponse
+ async pollServers(): Promise<{ servers: McpServerInfo[]; timestamp: string }> {
+ const response = await this.protectedFetch('/api/v2/hosts/self/mcpservers', 'inventory')
+ const data = decodeInventoryResponse(await response.json())
return { servers: data.servers, timestamp: data.timestamp }
}
}
@@ -142,9 +317,11 @@ export class ContextMapperClient {
// Default client instance (configured from environment)
let defaultClient: ContextMapperClient | null = null
-export function getContextMapperClient(): ContextMapperClient {
+export function getContextMapperClient(
+ authentication: ContextMapperAuthentication
+): ContextMapperClient {
if (!defaultClient) {
- defaultClient = new ContextMapperClient(config.contextMapperUrl)
+ defaultClient = new ContextMapperClient(config.contextMapperUrl, { authentication })
}
return defaultClient
}
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index da9e3a5ed..8fa84d964 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -32,7 +32,12 @@ import {
projectModels,
resolveSessionModel,
} from './config/modelResolution'
-import { ContextMapperClient, getContextMapperClient } from './contextMapperClient'
+import {
+ ContextMapperClient,
+ ContextMapperRequestError,
+ getContextMapperClient,
+ isContextMapperInventoryAuthorityRevocation,
+} from './contextMapperClient'
import {
type ConversationStoreHandle,
SqliteColdStartLoader,
@@ -171,6 +176,7 @@ let lastServerState: Map<string, string> = new Map()
let rpcServer: RPCServer | null = null
let mcpManager: McpManager | null = null
let contextMapperClient: ContextMapperClient | null = null
+let mcpAuthorityLastSuccessAt = 0
let activityHub: HostActivityHub | null = null
let workspaceProvider: ScopedWorkspaceProvider | null = null
let spilloverStorage: SpilloverStorage | null = null
@@ -777,8 +783,126 @@ export async function admitDevelopmentMcpServers(
}
}
-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 function isMcpAuthorityStale(
+ lastSuccessAt: number,
+ now: number,
+ maxStalenessMs: number
+): boolean {
+ return (
+ lastSuccessAt > 0 &&
+ Number.isFinite(now) &&
+ Number.isFinite(maxStalenessMs) &&
+ maxStalenessMs > 0 &&
+ now - lastSuccessAt >= maxStalenessMs
+ )
+}
+
+/**
+ * Arm an absolute authority deadline from the last successful HCC snapshot.
+ * The independent timeout prevents a slow or failed polling cadence from
+ * extending retained authority beyond the configured staleness ceiling.
+ */
+export function createMcpAuthorityStalenessDeadline(
+ maxStalenessMs: number,
+ onExpired: () => void,
+ now: () => number = Date.now
+): { recordSuccess(successAt?: number): void; clear(): void } {
+ let timer: ReturnType<typeof setTimeout> | null = null
+ let deadlineAt = 0
+
+ const clear = (): void => {
+ if (timer !== null) clearTimeout(timer)
+ timer = null
+ deadlineAt = 0
+ }
+
+ const schedule = (): void => {
+ const remaining = deadlineAt - now()
+ timer = setTimeout(
+ () => {
+ timer = null
+ if (now() < deadlineAt) {
+ schedule()
+ return
+ }
+ deadlineAt = 0
+ onExpired()
+ },
+ Math.max(0, remaining)
+ )
+ }
+
+ return {
+ recordSuccess: (successAt = now()) => {
+ clear()
+ if (!Number.isFinite(successAt) || !Number.isFinite(maxStalenessMs) || maxStalenessMs <= 0) {
+ return
+ }
+ deadlineAt = successAt + maxStalenessMs
+ schedule()
+ },
+ clear,
+ }
+}
+
+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 {
+ mcpInitializationGeneration += 1
+ stopContextMapperPolling()
+ mcpAuthorityStalenessDeadline.clear()
+ const closingManager = mcpManager
+ mcpManager = null
+ lastServerState = new Map()
+ mcpAuthorityLastSuccessAt = 0
+
+ if (closingManager) {
+ mcpFleetCoordinator.closeManager(closingManager)
+ void closingManager
+ .close(cleanup => mcpFleetCoordinator.scheduleCleanup(cleanup))
+ .catch(() => console.error(`[Main] MCP authority cleanup failed (reason=${reason})`))
+ }
+ console.warn(`[Main] MCP authority revoked (reason=${reason})`)
+
+ if (restartPolling && !isShuttingDown && !config.devMode) {
+ startContextMapperPolling()
+ }
+}
+
+async function initializeMcpServers(): Promise<void> {
+ console.log('[Main] Initializing authenticated MCP server inventory')
const initializationGeneration = ++mcpInitializationGeneration
const isInitializationCurrent = (): boolean =>
!isShuttingDown && mcpInitializationGeneration === initializationGeneration
@@ -789,19 +913,17 @@ async function initializeMcpServers(contextRef: string): Promise<void> {
servers,
previousManager,
createManager: () => new McpManager(config.mcpProxyEnabled ? config.mcpProxyUrl : undefined),
- 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
lastServerState = nextServerState
+ recordMcpAuthoritySuccess()
agent?.setMcpManager(nextManager)
},
coordinator: mcpFleetCoordinator,
- onColdStartPublished: () => ensureContextMapperPolling(contextRef),
+ onColdStartPublished: () => ensureContextMapperPolling(),
isPreviousManagerCurrent: () => mcpManager === previousManager,
isFleetLifecycleCurrent: isInitializationCurrent,
})
@@ -810,13 +932,10 @@ async function initializeMcpServers(contextRef: string): Promise<void> {
// In production mode, fetch an authoritative snapshot before replacing the
// current fleet. An unavailable Context Mapper leaves the prior state intact.
if (!config.devMode) {
- if (!contextMapperClient) {
- contextMapperClient = getContextMapperClient()
- }
+ const client = ensureAuthenticatedContextMapperClient()
await runAuthoritativeMcpInitialization({
- contextRef,
- client: contextMapperClient,
+ client,
replaceFleet,
isCurrent: isInitializationCurrent,
})
@@ -850,7 +969,7 @@ async function initializeMcpServers(contextRef: string): Promise<void> {
/**
* Poll context-mapper for McpServer changes.
*/
-async function pollContextMapper(contextRef: string): Promise<void> {
+async function pollContextMapper(): Promise<void> {
if (!contextMapperClient) return
try {
@@ -858,13 +977,13 @@ async function pollContextMapper(contextRef: string): Promise<void> {
// Retry the authoritative initialization instead of declaring an empty
// fleet or permanently no-oping every reconciliation tick.
if (!mcpManager) {
- await initializeMcpServers(contextRef)
+ await initializeMcpServers()
return
}
const manager = mcpManager
await pollAuthoritativeMcpSnapshotIfCurrent({
- poll: () => contextMapperClient!.pollServers(contextRef),
+ poll: () => contextMapperClient!.pollServers(),
// A delayed fetch may resolve after shutdown or after a manager swap.
// Never publish that stale snapshot into a closed/retired manager.
isCurrent: () => !isShuttingDown && mcpManager === manager,
@@ -873,12 +992,32 @@ async function pollContextMapper(contextRef: string): Promise<void> {
servers,
manager,
serverState: lastServerState,
- getAuthToken: serverName => contextMapperClient!.getAuthToken(serverName),
+ getAuthToken: (serverName, expectedRevision) =>
+ contextMapperClient!.getAuthToken(serverName, expectedRevision),
coordinator: mcpFleetCoordinator,
}),
})
+ if (!isShuttingDown && mcpManager === manager) {
+ recordMcpAuthoritySuccess()
+ }
} catch (error) {
- console.error('[Main] Error polling skill-mapper:', error)
+ if (error instanceof ContextMapperRequestError && error.authorizationFailure) {
+ // ContextMapperClient already revoked synchronously through its callback.
+ console.warn('[Main] HCC poll rejected caller authority')
+ return
+ }
+ if (isContextMapperInventoryAuthorityRevocation(error)) {
+ revokeMcpAuthority('inventory_not_found', true)
+ console.warn('[Main] HCC inventory no longer resolves live Host authority')
+ return
+ }
+ console.error('[Main] HCC authority poll failed (reason=unavailable)')
+ if (
+ mcpManager &&
+ isMcpAuthorityStale(mcpAuthorityLastSuccessAt, Date.now(), config.hccAuthorityMaxStalenessMs)
+ ) {
+ revokeMcpAuthority('authority_stale', true)
+ }
}
}
@@ -928,7 +1067,7 @@ export function createCoalescedPollRunner(poll: () => Promise<void>): {
/**
* Start polling context-mapper for McpServer changes.
*/
-export function startContextMapperPolling(contextRef: string): void {
+export function startContextMapperPolling(): void {
if (isShuttingDown) return
// Re-entry replaces the complete producer/runner pair. Stopping only the
// runner would leave the previous interval dispatching into the new runner.
@@ -938,15 +1077,15 @@ export function startContextMapperPolling(contextRef: string): void {
`[Main] Starting context-mapper polling (interval: ${config.contextMapperPollInterval}ms)`
)
- contextMapperPollRunner = createCoalescedPollRunner(() => pollContextMapper(contextRef))
+ contextMapperPollRunner = createCoalescedPollRunner(() => pollContextMapper())
contextMapperPollTimer = setInterval(() => {
contextMapperPollRunner?.trigger()
}, config.contextMapperPollInterval)
}
-export function ensureContextMapperPolling(contextRef: string): void {
+export function ensureContextMapperPolling(): void {
if (isShuttingDown || (contextMapperPollTimer && contextMapperPollRunner)) return
- startContextMapperPolling(contextRef)
+ startContextMapperPolling()
}
/**
@@ -993,9 +1132,23 @@ function stopMcpStatusHeartbeat(): void {
async function onHostChange(host: HostCRD): Promise<void> {
console.log(`[Main] Host configuration changed: ${host.name}`)
+ const contextChanged =
+ currentHost !== null && currentHost.spec.contextRef !== host.spec.contextRef
const providerChanged = currentHost?.spec.model?.provider !== host.spec.model?.provider
const secretRefChanged = currentHost?.spec.secretRef !== host.spec.secretRef
const modelChanged = currentHost?.spec.model?.name !== host.spec.model?.name
+
+ if (contextChanged) {
+ // The old Context's authority must disappear before any asynchronous Host
+ // reconciliation. HCC derives the new Context from the authenticated Host,
+ // so discovery can restart independently while provider state catches up.
+ revokeMcpAuthority('context_changed', false)
+ startMcpInitializationInBackground({
+ initialize: () => initializeMcpServers(),
+ afterInitialAttempt: () => ensureContextMapperPolling(),
+ })
+ }
+
// R5 — refresh the failover policy BEFORE (re)building the ConfigStore so the
// fallback credential slots are loaded. A policy change that alters which
// Secret slots are needed forces a ConfigStore rebuild even if provider/
@@ -1050,6 +1203,7 @@ async function onHostChange(host: HostCRD): Promise<void> {
*/
function onHostDelete(): void {
console.log('[Main] Host CRD deleted, shutting down')
+ revokeMcpAuthority('host_deleted', false)
currentHost = null
currentProvider = null
process.exit(1)
@@ -2516,6 +2670,7 @@ async function shutdown(signal: string): Promise<void> {
hostWatcher?.stop()
configStore?.stop()
stopContextMapperPolling()
+ mcpAuthorityStalenessDeadline.clear()
stopMcpStatusHeartbeat()
statelessHeartbeat?.stop()
@@ -2668,8 +2823,6 @@ async function startProductionMode(): Promise<void> {
console.log(`[Main] Namespace: ${config.namespace}`)
console.log(`[Main] Context Mapper URL: ${config.contextMapperUrl}`)
- contextMapperClient = getContextMapperClient()
-
const host = await getHost(config.hostName)
if (!host) {
@@ -2710,8 +2863,8 @@ async function startProductionMode(): Promise<void> {
// A failed initial attempt is logged loudly; the context-mapper poll then
// reconciles the catalog (the platform tolerates the 'connecting' sweep).
startMcpInitializationInBackground({
- initialize: () => initializeMcpServers(host.spec.contextRef),
- afterInitialAttempt: () => ensureContextMapperPolling(host.spec.contextRef),
+ initialize: () => initializeMcpServers(),
+ afterInitialAttempt: () => ensureContextMapperPolling(),
})
console.log(`[Main] Approval system: ${config.enableApproval ? 'ENABLED' : 'DISABLED'}`)
diff --git a/mcp-host/src/mcp/__tests__/authorizationRevocation.test.ts b/mcp-host/src/mcp/__tests__/authorizationRevocation.test.ts
new file mode 100644
index 000000000..77e52e830
--- /dev/null
+++ b/mcp-host/src/mcp/__tests__/authorizationRevocation.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest'
+import type { McpServerInfo } from '../../types'
+import { McpClient } 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 cleanup = client.retire()
+
+ expect((client as unknown as { authToken?: string }).authToken).toBeUndefined()
+ await expect(cleanup()).resolves.toBeUndefined()
+ })
+})
diff --git a/mcp-host/src/mcp/authoritativeFleet.ts b/mcp-host/src/mcp/authoritativeFleet.ts
index 523fc60d5..cbb351a8f 100644
--- a/mcp-host/src/mcp/authoritativeFleet.ts
+++ b/mcp-host/src/mcp/authoritativeFleet.ts
@@ -1,4 +1,7 @@
-import type { ContextMapperClient } from '../contextMapperClient'
+import {
+ type ContextMapperClient,
+ isContextMapperAuthorityRevocation,
+} from '../contextMapperClient'
import type { McpServerInfo } from '../types'
import type { McpAdmissionControl, McpAdmissionOutcome } from './manager'
@@ -6,8 +9,7 @@ import type { McpAdmissionControl, McpAdmissionOutcome } from './manager'
* Initialize MCP servers for the host's context using skill-mapper.
*/
export async function runAuthoritativeMcpInitialization(options: {
- contextRef: string
- client: Pick<ContextMapperClient, 'healthCheck' | 'listServersByContext'>
+ client: Pick<ContextMapperClient, 'healthCheck' | 'listServersForHost'>
replaceFleet: (servers: McpServerInfo[]) => Promise<void>
isCurrent?: () => boolean
sleep?: (milliseconds: number) => Promise<void>
@@ -22,7 +24,7 @@ export async function runAuthoritativeMcpInitialization(options: {
const ready = await options.client.healthCheck()
if (options.isCurrent?.() === false) return
if (ready) {
- const servers = await options.client.listServersByContext(options.contextRef)
+ const servers = await options.client.listServersForHost()
if (options.isCurrent?.() === false) return
await options.replaceFleet(servers)
return
@@ -461,20 +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> {
if (
!server.enabled ||
!server.status?.ready ||
server.status.authoritative === false ||
- !server.auth?.secretRef
+ (server.authRequired !== true && !server.auth?.secretRef)
) {
return undefined
}
- const authToken = await getAuthToken(server.name)
+ const authToken = await getAuthToken(server.name, server.credentialRevision)
if (!authToken) {
- throw new Error(`Required auth token is unavailable for MCP server ${server.name}`)
+ throw new Error('Required MCP credential is unavailable')
}
return authToken
}
@@ -493,7 +498,10 @@ export async function replaceAuthoritativeMcpFleet<
servers: McpServerInfo[]
previousManager: { disconnectAll(): Promise<void> } | null
createManager: () => TManager
- getAuthToken: (serverName: string) => Promise<string | undefined>
+ getAuthToken: (
+ serverName: string,
+ expectedCredentialRevision?: string
+ ) => Promise<string | undefined>
installFleet: (manager: TManager, serverState: Map<string, string>) => void
maxConcurrency?: number
coordinator?: AuthoritativeMcpFleetCoordinator
@@ -542,7 +550,11 @@ export async function replaceAuthoritativeMcpFleet<
// Auth discovery fails before addServer can own the status transition.
nextManager.recordAdmissionFailure(server, error)
admissionFailures.push(error)
- console.error(`[Main] MCP server admission failed; will retry: ${server.name}`, error)
+ if (isContextMapperAuthorityRevocation(error)) {
+ console.error('[Main] MCP credential admission rejected (reason=authority_revoked)')
+ } else {
+ console.error(`[Main] MCP server admission failed; will retry: ${server.name}`, error)
+ }
return
}
@@ -670,7 +682,10 @@ export async function reconcileAuthoritativeMcpSnapshot(options: {
servers: McpServerInfo[]
manager: AuthoritativeMcpSnapshotManager
serverState: Map<string, string>
- getAuthToken: (serverName: string) => Promise<string | undefined>
+ getAuthToken: (
+ serverName: string,
+ expectedCredentialRevision?: string
+ ) => Promise<string | undefined>
maxConcurrency?: number
coordinator?: AuthoritativeMcpFleetCoordinator
}): Promise<void> {
@@ -708,9 +723,18 @@ export async function reconcileAuthoritativeMcpSnapshot(options: {
previousState !== undefined &&
mcpServerDesiredRevision(JSON.parse(previousState) as McpServerInfo) !==
mcpServerDesiredRevision(server)
+ const previousCredentialRevision =
+ previousState !== undefined
+ ? (JSON.parse(previousState) as McpServerInfo).credentialRevision
+ : undefined
+ const credentialAuthorityChanged =
+ previousState !== undefined &&
+ previousCredentialRevision !== server.credentialRevision &&
+ (previousCredentialRevision !== undefined || server.credentialRevision !== undefined)
const revokesLiveConnection =
connectedNames.has(server.name) &&
(!server.enabled ||
+ credentialAuthorityChanged ||
(server.status?.authoritative !== false && server.status?.ready === false) ||
(server.status?.authoritative === false && desiredChanged))
if (revokesLiveConnection && lease.isCurrent(server.name)) {
@@ -726,6 +750,14 @@ export async function reconcileAuthoritativeMcpSnapshot(options: {
try {
return await resolveRequiredMcpAuthToken(server, options.getAuthToken)
} catch (error) {
+ if (isCurrent() && isContextMapperAuthorityRevocation(error)) {
+ if (options.manager.detachServer) {
+ coordinator.scheduleCleanup(options.manager.detachServer(server.name))
+ } else if (connectedNames.has(server.name)) {
+ await options.manager.removeServer(server.name)
+ }
+ options.serverState.delete(server.name)
+ }
// Auth discovery fails before manager admission. Preserve a live
// connection's status during replacement; otherwise publish the
// admission failure exactly once.
diff --git a/mcp-host/src/mcp/client.ts b/mcp-host/src/mcp/client.ts
index febe8b8e4..8b5be15f8 100644
--- a/mcp-host/src/mcp/client.ts
+++ b/mcp-host/src/mcp/client.ts
@@ -361,6 +361,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.retirementController.abort(this.lifecycleError('closed'))
return this.detachConnection()
}
diff --git a/mcp-host/src/types.ts b/mcp-host/src/types.ts
index b4642196e..0e5cbb6c6 100644
--- a/mcp-host/src/types.ts
+++ b/mcp-host/src/types.ts
@@ -131,6 +131,7 @@ export type ApiKeys = Partial<Record<LlmProvider, ProviderCredentials>>
export interface McpServerTransport {
type: 'sse' | 'streamableHttp' | 'stdio'
url?: string
+ port?: number
}
/**
@@ -167,9 +168,22 @@ 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
+ /** 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
enabled: boolean
status: McpServerStatus
}
diff --git a/scripts/minikube/pre-gate-runtime.sh b/scripts/minikube/pre-gate-runtime.sh
index b3f7c03fe..ecd36d279 100755
--- a/scripts/minikube/pre-gate-runtime.sh
+++ b/scripts/minikube/pre-gate-runtime.sh
@@ -115,6 +115,56 @@ assert_workflow_gateway_prompt_bridge_finalization_route() {
log "Workflow gateway serves the SDK promptBridge finalization route"
}
+# The HCC gateway also mounts nginx.conf through a subPath. NP-08 gates must
+# prove every active pod serves only the caller-bound v2 Host routes while the
+# two caller-selected legacy Host routes are local tombstones. The global v1
+# inventory remains temporarily for the retained mcp-proxy poller (PR 2).
+assert_hcc_gateway_np08_routes() {
+ local deployment="host-context-controller-api-gateway"
+ local namespace="control-plane"
+ local candidate deletion ready rendered pod_count=0
+
+ if ! ${KC} get deployment "${deployment}" -n "${namespace}" >/dev/null 2>&1; then
+ log "ERROR: ${namespace}/${deployment} is absent; refusing NP-08 gate"
+ return 1
+ fi
+
+ while IFS= read -r candidate; do
+ [[ -z "${candidate}" ]] && continue
+ deletion="$(${KC} get pod "${candidate}" -n "${namespace}" \
+ -o jsonpath='{.metadata.deletionTimestamp}' 2>/dev/null || true)"
+ [[ -n "${deletion}" ]] && continue
+ ready="$(${KC} get pod "${candidate}" -n "${namespace}" \
+ -o jsonpath='{.status.containerStatuses[?(@.name=="nginx")].ready}' 2>/dev/null || true)"
+ [[ "${ready}" == "true" ]] || continue
+ pod_count=$((pod_count + 1))
+ rendered="$(${KC} exec -n "${namespace}" "${candidate}" -c nginx -- nginx -T 2>&1)" || {
+ log "ERROR: could not inspect active ${namespace}/${candidate}; refusing NP-08 gate"
+ return 1
+ }
+ if ! grep -Fq 'location = /api/v2/hosts/self/mcpservers {' <<<"${rendered}" ||
+ ! grep -Fq 'location = /api/v2/hosts/self/mcpservers/credential {' <<<"${rendered}" ||
+ ! grep -Fq 'location ~ ^/api/v1/mcpservers/context/[^/]+$ {' <<<"${rendered}" ||
+ ! grep -Fq 'location ~ ^/api/v1/mcpservers/[^/]+/auth$ {' <<<"${rendered}" ||
+ ! grep -Fq 'proxy_set_header Authorization $http_authorization;' <<<"${rendered}" ||
+ ! grep -Fq 'access_log /dev/stdout hcc_gateway_json;' <<<"${rendered}" ||
+ ! grep -Fq 'add_header Cache-Control "no-store, private" always;' <<<"${rendered}" ||
+ ! grep -Fq 'add_header Pragma "no-cache" always;' <<<"${rendered}" ||
+ ! grep -Fq 'add_header X-Content-Type-Options "nosniff" always;' <<<"${rendered}" ||
+ [[ "$(grep -Fc "return 410 '{\"error\":\"gone\"}';" <<<"${rendered}")" -lt 2 ]]; then
+ log "ERROR: active ${namespace}/${candidate} lacks the NP-08 gateway contract"
+ return 1
+ fi
+ done < <(${KC} get pods -n "${namespace}" -l app="${deployment}" \
+ --field-selector=status.phase=Running -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null || true)
+
+ if [[ "${pod_count}" == "0" ]]; then
+ log "ERROR: ${namespace}/${deployment} has no Ready non-terminating pod; refusing NP-08 gate"
+ return 1
+ fi
+ log "HCC gateway serves caller-bound NP-08 routes"
+}
+
gate_needs_registry() {
[[ "${GATE_NAME}" == *registry* || "${GATE_NAME}" == *marketplace* || "${GATE_NAME}" == *plugin-workload-sdk* ]]
}
diff --git a/scripts/minikube/pre-gate-sync.sh b/scripts/minikube/pre-gate-sync.sh
index 8615b9fff..b8e38cbf5 100755
--- a/scripts/minikube/pre-gate-sync.sh
+++ b/scripts/minikube/pre-gate-sync.sh
@@ -534,17 +534,19 @@ if [[ "${cluster_changed}" == "true" ]]; then
ensure_evenfire_registry
incremental_restart_targets
- # nginx.conf is mounted through a subPath. Kubernetes updates the
- # ConfigMap object but does not refresh that file in an already-running pod,
- # so a full deployment sync must roll the gateway before any SDK probe uses
- # the new route set.
+ # Both nginx gateway configs are mounted through subPath. Kubernetes updates
+ # the ConfigMaps but not the files in existing pods, so a deployment sync
+ # must roll both before any SDK or NP-08 runtime assertion.
if [[ "${INCREMENTAL_FULL_DEPLOYMENT}" == "true" ||
"${FORCE_RESTART}" == "true" ]]; then
rollout_restart_with_retry control-plane nginx-workflow-approval-gateway
rollout_if_present control-plane nginx-workflow-approval-gateway
+ rollout_restart_with_retry control-plane host-context-controller-api-gateway
+ rollout_if_present control-plane host-context-controller-api-gateway
fi
assert_workflow_gateway_prompt_bridge_finalization_route
+ assert_hcc_gateway_np08_routes
rollout_if_present control-plane host-context-controller
rollout_if_present control-plane workflow-recipes
@@ -578,5 +580,7 @@ else
ensure_evenfire_registry
rollout_if_present control-plane nginx-workflow-approval-gateway
assert_workflow_gateway_prompt_bridge_finalization_route
+ rollout_if_present control-plane host-context-controller-api-gateway
+ assert_hcc_gateway_np08_routes
${KC} get deploy -A --no-headers 2>/dev/null | grep -v kube-system || true
fi
diff --git a/scripts/security/run-np08-synthetic-gate.sh b/scripts/security/run-np08-synthetic-gate.sh
new file mode 100755
index 000000000..76c4e9999
--- /dev/null
+++ b/scripts/security/run-np08-synthetic-gate.sh
@@ -0,0 +1,55 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Synthetic NP-08 gate. It performs no Kubernetes writes, never reads a Secret,
+# and only runs the repository-owned authorization unit suite after checking an
+# explicit branch-owned context. The live deployment probe remains Gate F.
+
+context=''
+test_file='host-context-controller/src/mcpAuthorization.test.ts'
+summary=''
+
+while [[ "$#" -gt 0 ]]; do
+ case "$1" in
+ --context)
+ context="${2:-}"
+ shift 2
+ ;;
+ --test)
+ test_file="${2:-}"
+ shift 2
+ ;;
+ --summary)
+ summary="${2:-}"
+ shift 2
+ ;;
+ *)
+ echo "usage: $0 --context <kube-context> [--test <HCC unit test>] --summary <file>" >&2
+ exit 2
+ ;;
+ esac
+done
+
+if [[ -z "${context}" || -z "${summary}" ]]; then
+ echo "usage: $0 --context <kube-context> [--test <HCC unit test>] --summary <file>" >&2
+ exit 2
+fi
+if [[ "${test_file}" != host-context-controller/src/*.test.ts ]]; then
+ echo "FAIL: synthetic gate accepts only the HCC authorization unit suite" >&2
+ exit 2
+fi
+if [[ ! -f "${test_file}" ]]; then
+ echo "FAIL: synthetic test file is absent" >&2
+ exit 1
+fi
+if [[ -L "${summary}" ]]; then
+ echo "FAIL: summary path must not be a symlink" >&2
+ exit 2
+fi
+
+mkdir -p "$(dirname "${summary}")"
+kubectl --context="${context}" get namespace mcp-server -o name >/dev/null
+npm --prefix host-context-controller test -- "${test_file#host-context-controller/}"
+
+printf '{"status":"pass","real_kubernetes_secret_reads":"zero","negative_path_secret_reads":"zero","synthetic_fixture_secret_values":"allowed","kubernetes_writes":"zero"}\n' >"${summary}"
+echo 'PASS: NP-08 synthetic authorization gate (unit matrix; no real Secret reads; negative paths zero)'
diff --git a/scripts/security/scan-np08-evidence.sh b/scripts/security/scan-np08-evidence.sh
new file mode 100755
index 000000000..6d5bd8985
--- /dev/null
+++ b/scripts/security/scan-np08-evidence.sh
@@ -0,0 +1,124 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Evidence hygiene scanner. It counts violations without echoing matching
+# lines. API/log inputs must already be redacted; rendered manifests are a
+# separate scope and may contain Secret references, but never credential values.
+
+tmpdir="$(mktemp -d "${TMPDIR:-/tmp}/np08-evidence.XXXXXX")"
+trap 'rm -rf "${tmpdir}"' EXIT
+
+api_inputs=()
+log_inputs=()
+manifest_inputs=()
+stdin_kind=''
+
+while [[ "$#" -gt 0 ]]; do
+ case "$1" in
+ --api)
+ api_inputs+=("${2:-}")
+ shift 2
+ ;;
+ --logs)
+ log_inputs+=("${2:-}")
+ shift 2
+ ;;
+ --manifest)
+ manifest_inputs+=("${2:-}")
+ shift 2
+ ;;
+ --stdin-kind)
+ stdin_kind="${2:-}"
+ shift 2
+ ;;
+ *)
+ echo "usage: $0 [--api file] [--logs file] [--manifest file] [--stdin-kind api|logs|manifest]" >&2
+ exit 2
+ ;;
+ esac
+done
+
+if [[ "${#api_inputs[@]}" -eq 0 && "${#log_inputs[@]}" -eq 0 && "${#manifest_inputs[@]}" -eq 0 && -z "${stdin_kind}" ]]; then
+ echo "usage: $0 [--api file] [--logs file] [--manifest file] [--stdin-kind api|logs|manifest]" >&2
+ exit 2
+fi
+
+copy_input() {
+ local source="$1"
+ local destination="$2"
+ if [[ ! -f "${source}" || -L "${source}" ]]; then
+ echo 'FAIL: evidence input is absent or a symlink' >&2
+ exit 1
+ fi
+ cp -- "${source}" "${destination}"
+}
+
+scan_scope() {
+ local scope="$1"
+ local pattern="$2"
+ shift 2
+ local count=0
+ local input
+ for input in "$@"; do
+ local hits="${tmpdir}/${scope}-${count}.hits"
+ if rg -n -I -i --no-messages -e "${pattern}" "${input}" >"${hits}"; then
+ count=$((count + $(wc -l <"${hits}")))
+ fi
+ done
+ echo "${scope}_violations=${count}"
+ [[ "${count}" -eq 0 ]]
+}
+
+declare -a api_files=()
+declare -a manifest_files=()
+for input in "${api_inputs[@]}" "${log_inputs[@]}"; do
+ [[ -n "${input}" ]] || { echo 'FAIL: empty evidence path' >&2; exit 2; }
+ destination="${tmpdir}/input-${#api_files[@]}"
+ copy_input "${input}" "${destination}"
+ api_files+=("${destination}")
+done
+for input in "${manifest_inputs[@]}"; do
+ [[ -n "${input}" ]] || { echo 'FAIL: empty evidence path' >&2; exit 2; }
+ destination="${tmpdir}/manifest-${#manifest_files[@]}"
+ copy_input "${input}" "${destination}"
+ manifest_files+=("${destination}")
+done
+
+if [[ -n "${stdin_kind}" ]]; then
+ case "${stdin_kind}" in
+ api|logs)
+ cat >"${tmpdir}/stdin-api"
+ api_files+=("${tmpdir}/stdin-api")
+ ;;
+ manifest)
+ cat >"${tmpdir}/stdin-manifest"
+ manifest_files+=("${tmpdir}/stdin-manifest")
+ ;;
+ *)
+ echo 'FAIL: --stdin-kind must be api, logs, or manifest' >&2
+ exit 2
+ ;;
+ esac
+fi
+
+api_pattern=$'(Bearer[[:space:]]+[A-Za-z0-9._~-]+|[A-Za-z0-9_-]{20,}\\.[A-Za-z0-9_-]{20,}\\.[A-Za-z0-9_-]{20,}|secretRef|secretKey|mcpHostAccessToken|mcpHostRefreshToken|mcpHostControlToken|authorization[[:space:]]*[:=][[:space:]]*[^[:space:]}" ]+|proxy-authorization[[:space:]]*[:=][[:space:]]*[^[:space:]}" ]+|token"[[:space:]]*:[[:space:]]*"[^"}]+)'
+manifest_pattern='(Bearer[[:space:]]+[A-Za-z0-9._~-]+|[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}|-----BEGIN (RSA )?PRIVATE KEY-----)'
+
+api_ok=1
+if [[ "${#api_files[@]}" -gt 0 ]]; then
+ scan_scope api "${api_pattern}" "${api_files[@]}" || api_ok=0
+else
+ echo 'api_violations=0'
+fi
+manifest_ok=1
+if [[ "${#manifest_files[@]}" -gt 0 ]]; then
+ scan_scope manifest "${manifest_pattern}" "${manifest_files[@]}" || manifest_ok=0
+else
+ echo 'manifest_violations=0'
+fi
+
+if [[ "${api_ok}" -ne 1 || "${manifest_ok}" -ne 1 ]]; then
+ echo 'FAIL: NP-08 evidence hygiene violations found' >&2
+ exit 1
+fi
+echo 'PASS: NP-08 evidence hygiene'
diff --git a/scripts/security/verify-np08-hcc-authz.sh b/scripts/security/verify-np08-hcc-authz.sh
new file mode 100755
index 000000000..696f2433f
--- /dev/null
+++ b/scripts/security/verify-np08-hcc-authz.sh
@@ -0,0 +1,85 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Read-only deployment conformance for NP-08. Every Kubernetes call carries the
+# caller-provided context. This script never reads Secret objects, token files,
+# pod filesystems, or tenant data; output is limited to booleans/counts.
+
+context=''
+read_only=0
+redact=0
+while [[ "$#" -gt 0 ]]; do
+ case "$1" in
+ --context)
+ context="${2:-}"
+ shift 2
+ ;;
+ --read-only)
+ read_only=1
+ shift
+ ;;
+ --redact-identifiers)
+ redact=1
+ shift
+ ;;
+ *)
+ echo "usage: $0 --context <kube-context> --read-only --redact-identifiers" >&2
+ exit 2
+ ;;
+ esac
+done
+
+if [[ -z "${context}" || "${read_only}" -ne 1 || "${redact}" -ne 1 ]]; then
+ echo "usage: $0 --context <kube-context> --read-only --redact-identifiers" >&2
+ exit 2
+fi
+
+check() {
+ local name="$1"
+ local result="$2"
+ if [[ "${result}" != 1 ]]; then
+ echo "FAIL: ${name}=false" >&2
+ exit 1
+ fi
+ echo "CHECK ${name}=true"
+}
+
+kubectl --context="${context}" get namespace control-plane -o name >/dev/null
+kubectl --context="${context}" get namespace mcp-host -o name >/dev/null
+kubectl --context="${context}" get namespace mcp-server -o name >/dev/null
+
+hcc_replicas="$(kubectl --context="${context}" -n control-plane get deployment host-context-controller -o jsonpath='{.spec.replicas}')"
+hcc_ready="$(kubectl --context="${context}" -n control-plane get deployment host-context-controller -o jsonpath='{.status.readyReplicas}')"
+gateway_replicas="$(kubectl --context="${context}" -n control-plane get deployment host-context-controller-api-gateway -o jsonpath='{.spec.replicas}')"
+gateway_ready="$(kubectl --context="${context}" -n control-plane get deployment host-context-controller-api-gateway -o jsonpath='{.status.readyReplicas}')"
+check hcc_ready "$([[ -n "${hcc_replicas}" && "${hcc_ready}" == "${hcc_replicas}" ]] && echo 1 || echo 0)"
+check gateway_ready "$([[ -n "${gateway_replicas}" && "${gateway_ready}" == "${gateway_replicas}" ]] && echo 1 || echo 0)"
+
+hcc_key_ref="$(kubectl --context="${context}" -n control-plane get deployment host-context-controller -o jsonpath='{range .spec.template.spec.containers[?(@.name=="host-context-controller")].env[?(@.name=="HCC_MCP_HOST_JWT_PUBLIC_KEY")]}{.valueFrom.configMapKeyRef.name}{"/"}{.valueFrom.configMapKeyRef.key}{end}')"
+check hcc_public_key_ref "$([[ "${hcc_key_ref}" == 'control-api-public-key/CONTROL_API_PUBLIC_KEY_PEM' ]] && echo 1 || echo 0)"
+
+hcc_issuer_ref="$(kubectl --context="${context}" -n control-plane get deployment host-context-controller -o jsonpath='{range .spec.template.spec.containers[?(@.name=="host-context-controller")].env[?(@.name=="HCC_MCP_HOST_JWT_ISSUER")]}{.valueFrom.configMapKeyRef.name}{"/"}{.valueFrom.configMapKeyRef.key}{end}')"
+check hcc_issuer_config_ref "$([[ "${hcc_issuer_ref}" == 'control-api-config/CONTROL_API_ADMIN_JWT_ISSUER' ]] && echo 1 || echo 0)"
+
+proxy_flag="$(kubectl --context="${context}" -n mcp-host get configmap mcp-host-config -o jsonpath='{.data.MCP_PROXY_ENABLED}')"
+check mcp_proxy_enabled_false "$([[ "${proxy_flag}" == 'false' ]] && echo 1 || echo 0)"
+
+proxy_replicas="$(kubectl --context="${context}" -n mcp-server get deployment mcp-proxy -o jsonpath='{.spec.replicas}')"
+proxy_ready="$(kubectl --context="${context}" -n mcp-server get deployment mcp-proxy -o jsonpath='{.status.readyReplicas}')"
+check proxy_singleton_replicas "$([[ "${proxy_replicas}" == '1' ]] && echo 1 || echo 0)"
+check proxy_singleton_ready "$([[ "${proxy_ready}" == '1' ]] && echo 1 || echo 0)"
+
+host_proxy_ports="$(kubectl --context="${context}" -n mcp-host get networkpolicies -o jsonpath='{range .items[*].spec.egress[*].ports[*]}{.port}{"\n"}{end}')"
+if rg -x -q '8083' <<<"${host_proxy_ports}"; then
+ host_proxy_8083_ok=0
+else
+ host_proxy_8083_ok=1
+fi
+check no_host_proxy_8083_egress "${host_proxy_8083_ok}"
+
+gateway_config="$(kubectl --context="${context}" -n control-plane get configmap host-context-controller-api-gateway -o jsonpath='{.data.nginx\.conf}')"
+check v1_context_tombstone "$(rg -q 'location ~ \^/api/v1/mcpservers/context/\[\^/\]\+\$' <<<"${gateway_config}" && rg -q 'return 410' <<<"${gateway_config}" && echo 1 || echo 0)"
+check v1_auth_tombstone "$(rg -q 'location ~ \^/api/v1/mcpservers/\[\^/\]\+/auth\$' <<<"${gateway_config}" && rg -q 'return 410' <<<"${gateway_config}" && echo 1 || echo 0)"
+check v2_host_routes "$(rg -q '/api/v2/hosts/self/mcpservers' <<<"${gateway_config}" && rg -q '/api/v2/hosts/self/mcpservers/credential' <<<"${gateway_config}" && echo 1 || echo 0)"
+
+echo 'PASS: NP-08 read-only HCC deployment conformance'
diff --git a/scripts/tests/test-minikube-pre-gate-sync-state.sh b/scripts/tests/test-minikube-pre-gate-sync-state.sh
index 1273936d1..4f9e0c9d6 100755
--- a/scripts/tests/test-minikube-pre-gate-sync-state.sh
+++ b/scripts/tests/test-minikube-pre-gate-sync-state.sh
@@ -117,7 +117,7 @@ else
fail "pre-gate sync does not use the shared idempotent auth-key sync helper"
fi
-if contains 'nginx.conf is mounted through a subPath' &&
+if contains 'Both nginx gateway configs are mounted through subPath' &&
contains 'INCREMENTAL_FULL_DEPLOYMENT' &&
contains 'rollout_restart_with_retry control-plane nginx-workflow-approval-gateway' &&
contains 'rollout_if_present control-plane nginx-workflow-approval-gateway' &&
@@ -127,6 +127,33 @@ else
fail "pre-gate sync can leave a stale workflow gateway after ConfigMap changes"
fi
+hcc_gateway_restart_line="$(grep -nF 'rollout_restart_with_retry control-plane host-context-controller-api-gateway' "$SCRIPT" | head -n 1 | cut -d: -f1)"
+hcc_gateway_wait_line="$(grep -nF 'rollout_if_present control-plane host-context-controller-api-gateway' "$SCRIPT" | head -n 1 | cut -d: -f1)"
+hcc_gateway_assert_line="$(grep -nF 'assert_hcc_gateway_np08_routes' "$SCRIPT" | head -n 1 | cut -d: -f1)"
+if [[ -n "$hcc_gateway_restart_line" &&
+ -n "$hcc_gateway_wait_line" &&
+ -n "$hcc_gateway_assert_line" &&
+ "$hcc_gateway_restart_line" -lt "$hcc_gateway_wait_line" &&
+ "$hcc_gateway_wait_line" -lt "$hcc_gateway_assert_line" ]]; then
+ pass "pre-gate restarts and waits for the subPath-mounted HCC gateway before NP-08 inspection"
+else
+ fail "pre-gate can inspect a stale HCC gateway after its ConfigMap changes"
+fi
+
+if runtime_contains 'assert_hcc_gateway_np08_routes()' &&
+ runtime_contains 'location = /api/v2/hosts/self/mcpservers {' &&
+ runtime_contains 'location = /api/v2/hosts/self/mcpservers/credential {' &&
+ runtime_contains 'location ~ ^/api/v1/mcpservers/context/[^/]+$ {' &&
+ runtime_contains 'location ~ ^/api/v1/mcpservers/[^/]+/auth$ {' &&
+ runtime_contains 'proxy_set_header Authorization $http_authorization;' &&
+ runtime_contains 'add_header Pragma "no-cache" always;' &&
+ runtime_contains 'access_log /dev/stdout hcc_gateway_json;' &&
+ runtime_contains 'return 410'; then
+ pass "pre-gate fails closed when the running HCC gateway lacks the NP-08 route contract"
+else
+ fail "pre-gate does not verify the running NP-08 HCC gateway contract"
+fi
+
if runtime_contains 'assert_workflow_gateway_prompt_bridge_finalization_route()' &&
runtime_contains 'nginx_config="$(${KC} exec' &&
runtime_contains 'could not inspect the active nginx configuration' &&
diff --git a/scripts/tests/test-np08-evidence-scanner.sh b/scripts/tests/test-np08-evidence-scanner.sh
new file mode 100755
index 000000000..2a4fee539
--- /dev/null
+++ b/scripts/tests/test-np08-evidence-scanner.sh
@@ -0,0 +1,32 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+SCANNER="${ROOT}/scripts/security/scan-np08-evidence.sh"
+tmpdir="$(mktemp -d "${TMPDIR:-/tmp}/np08-scan-test.XXXXXX")"
+trap 'rm -rf "${tmpdir}"' EXIT
+
+if ! printf '%s\n' '{"error":"authorization_unavailable"}' | bash "${SCANNER}" --stdin-kind api >/dev/null; then
+ echo 'FAIL: sanitized authorization error was treated as a credential leak' >&2
+ exit 1
+fi
+
+if printf '%s\n' '{"Authorization":"Bearer abc.def.ghi"}' | bash "${SCANNER}" --stdin-kind api >/dev/null 2>&1; then
+ echo 'FAIL: bearer header was not rejected' >&2
+ exit 1
+fi
+
+if printf '%s\n' '{"token":"credential-value"}' | bash "${SCANNER}" --stdin-kind api >/dev/null 2>&1; then
+ echo 'FAIL: credential field was not rejected' >&2
+ exit 1
+fi
+
+printf '%s\n' 'env: secretRef: runtime-token' >"${tmpdir}/rendered.yaml"
+bash "${SCANNER}" --manifest "${tmpdir}/rendered.yaml" >/dev/null
+
+if printf '%s\n' '-----BEGIN PRIVATE KEY-----' | bash "${SCANNER}" --stdin-kind manifest >/dev/null 2>&1; then
+ echo 'FAIL: private key material was not rejected' >&2
+ exit 1
+fi
+
+echo 'PASS: NP-08 evidence scanner fixtures'
diff --git a/scripts/tests/test-np08-render-contract.sh b/scripts/tests/test-np08-render-contract.sh
new file mode 100755
index 000000000..d814ea3d9
--- /dev/null
+++ b/scripts/tests/test-np08-render-contract.sh
@@ -0,0 +1,132 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+if [[ "$#" -lt 1 ]]; then
+ echo "usage: $0 <rendered-yaml|-> [...]" >&2
+ exit 2
+fi
+
+for rendered in "$@"; do
+ if [[ "${rendered}" != "-" && ! -f "${rendered}" ]]; then
+ echo "FAIL: rendered manifest is absent" >&2
+ exit 1
+ fi
+
+ RUBYOPT=--disable=gems ruby -ryaml -e '
+ source = ARGV.fetch(0)
+ yaml = source == "-" ? STDIN.read : File.read(source)
+ documents = YAML.load_stream(yaml).select { |document| document.is_a?(Hash) }
+
+ find = lambda do |kind, name, namespace|
+ documents.find do |document|
+ document["kind"] == kind &&
+ document.dig("metadata", "name") == name &&
+ document.dig("metadata", "namespace") == namespace
+ end
+ end
+ require_resource = lambda do |kind, name, namespace|
+ find.call(kind, name, namespace) || abort("missing #{namespace}/#{kind}/#{name}")
+ end
+
+ host_config = require_resource.call("ConfigMap", "mcp-host-config", "mcp-host")
+ abort("mcp-host must keep direct MCP transport") unless host_config.dig("data", "MCP_PROXY_ENABLED") == "false"
+ abort("HCC authority staleness must stay bounded at 60 seconds") unless host_config.dig("data", "HCC_AUTHORITY_MAX_STALENESS_MS") == "60000"
+
+ hcc = require_resource.call("Deployment", "host-context-controller", "control-plane")
+ hcc_container = Array(hcc.dig("spec", "template", "spec", "containers")).find do |container|
+ container["name"] == "host-context-controller"
+ end
+ abort("HCC container is missing") unless hcc_container
+ hcc_env = Array(hcc_container["env"]).to_h { |entry| [entry["name"], entry] }
+ public_key_ref = hcc_env.dig("HCC_MCP_HOST_JWT_PUBLIC_KEY", "valueFrom", "configMapKeyRef")
+ unless public_key_ref == {
+ "name" => "control-api-public-key",
+ "key" => "CONTROL_API_PUBLIC_KEY_PEM",
+ }
+ abort("HCC Host JWT public-key wiring is not authoritative")
+ end
+ issuer_ref = hcc_env.dig("HCC_MCP_HOST_JWT_ISSUER", "valueFrom", "configMapKeyRef")
+ unless issuer_ref == {
+ "name" => "control-api-config",
+ "key" => "CONTROL_API_ADMIN_JWT_ISSUER",
+ }
+ abort("HCC Host JWT issuer is not wired to the Control API issuer contract")
+ end
+ max_ttl_ref = hcc_env.dig("HCC_MCP_HOST_JWT_MAX_TTL_SECONDS", "valueFrom", "configMapKeyRef")
+ unless max_ttl_ref == {
+ "name" => "control-api-config",
+ "key" => "WORKFLOW_APPROVAL_ACCESS_TTL_SEC",
+ }
+ abort("HCC Host JWT maximum TTL must share the Control API access-token contract")
+ end
+
+ gateway = require_resource.call("ConfigMap", "host-context-controller-api-gateway", "control-plane")
+ nginx = gateway.dig("data", "nginx.conf").to_s
+ location_block = lambda do |marker|
+ start = nginx.index(marker) || abort("gateway is missing #{marker}")
+ finish = nginx.index(/^\s*location\s/m, start + marker.length) || nginx.length
+ nginx[start...finish]
+ end
+ inventory = location_block.call("location = /api/v2/hosts/self/mcpservers {")
+ credential = location_block.call("location = /api/v2/hosts/self/mcpservers/credential {")
+ [inventory, credential].each do |block|
+ abort("v2 route forwards ambient request headers") unless block.include?("proxy_pass_request_headers off;")
+ abort("v2 route does not explicitly forward Authorization") unless block.include?("proxy_set_header Authorization $http_authorization;")
+ abort("v2 route permits caching") unless block.include?("Cache-Control \"no-store, private\"")
+ end
+ abort("credential route is not POST-only") unless credential.include?("$request_method != POST")
+ abort("credential body is not bounded") unless credential.include?("client_max_body_size 1k;")
+ abort("credential route does not preserve explicit body framing") unless credential.include?("proxy_set_header Content-Length $content_length;")
+ abort("inventory route is not GET-only") unless inventory.include?("$request_method != GET")
+ secure_local_response = lambda do |block, label|
+ abort("#{label} permits caching") unless block.include?("Cache-Control \"no-store, private\"")
+ abort("#{label} omits legacy no-cache protection") unless block.include?("Pragma \"no-cache\"")
+ abort("#{label} permits content sniffing") unless block.include?("X-Content-Type-Options \"nosniff\"")
+ end
+ legacy_context = location_block.call("location ~ ^/api/v1/mcpservers/context/[^/]+$ {")
+ legacy_credential = location_block.call("location ~ ^/api/v1/mcpservers/[^/]+/auth$ {")
+ [legacy_context, legacy_credential].each do |block|
+ abort("legacy Host route is not tombstoned") unless block.include?("return 410")
+ secure_local_response.call(block, "legacy Host tombstone")
+ end
+ %w[@hcc_bad_request @hcc_method_not_allowed @hcc_payload_too_large].each do |location|
+ secure_local_response.call(location_block.call("location #{location} {"), "gateway error response")
+ end
+ abort("temporary system inventory compatibility route is absent") unless nginx.include?("location = /api/v1/mcpservers {")
+
+ access_log = nginx[/log_format hcc_gateway_json.*?;/m].to_s
+ abort("sanitized HCC audit log is absent") if access_log.empty?
+ %w[$uri $request_uri $request_body $http_authorization].each do |forbidden|
+ abort("HCC audit log includes request-derived sensitive data") if access_log.include?(forbidden)
+ end
+
+ proxy_deployment = require_resource.call("Deployment", "mcp-proxy", "mcp-server")
+ require_resource.call("Service", "mcp-proxy", "mcp-server")
+ abort("PR 1 must not disable the retained mcp-proxy") unless proxy_deployment.dig("spec", "replicas") == 1
+
+ policies = documents.select do |document|
+ document["kind"] == "NetworkPolicy" && document.dig("metadata", "namespace") == "mcp-host"
+ end
+ hcc_lane = policies.any? do |policy|
+ Array(policy.dig("spec", "egress")).any? do |rule|
+ ports = Array(rule["ports"])
+ peers = Array(rule["to"])
+ ports.any? { |port| port["port"] == 8081 && port.fetch("protocol", "TCP") == "TCP" } &&
+ peers.any? do |peer|
+ peer.dig("namespaceSelector", "matchLabels", "kubernetes.io/metadata.name") == "control-plane" &&
+ peer.dig("podSelector", "matchLabels", "app") == "host-context-controller-api-gateway"
+ end
+ end
+ end
+ abort("mcp-host to HCC TCP 8081 lane is absent") unless hcc_lane
+
+ host_proxy_lane = policies.any? do |policy|
+ Array(policy.dig("spec", "egress")).any? do |rule|
+ Array(rule["ports"]).any? { |port| port["port"] == 8083 }
+ end
+ end
+ abort("mcp-host must not gain an egress lane to mcp-proxy TCP 8083") if host_proxy_lane
+ ' "${rendered}"
+
+ echo "PASS: NP-08 rendered contract (${rendered##*/})"
+done
diff --git a/scripts/tests/test-np08-v1-reference-inventory.sh b/scripts/tests/test-np08-v1-reference-inventory.sh
new file mode 100755
index 000000000..56596843d
--- /dev/null
+++ b/scripts/tests/test-np08-v1-reference-inventory.sh
@@ -0,0 +1,38 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+cd "${ROOT}"
+
+fail=0
+
+if rg -n -F '/api/v1/mcpservers' mcp-host/src; then
+ echo "FAIL: mcp-host must not retain an HCC v1 discovery or credential path" >&2
+ fail=1
+fi
+
+if rg -n 'listServersByContext|getAuthTokenForServer|pollServers\([^)]*context' mcp-host/src; then
+ echo "FAIL: mcp-host retains a caller-selected Context or legacy credential API" >&2
+ fail=1
+fi
+
+if ! rg -q -F '/api/v1/mcpservers' mcp-proxy/src/hccClient.ts; then
+ echo "FAIL: the temporary PR 2 global-inventory consumer is no longer explicit" >&2
+ fail=1
+fi
+
+if rg -n '/api/v1/mcpservers/(context/|[^/]+/auth)' mcp-proxy/src; then
+ echo "FAIL: mcp-proxy must not consume caller-selected v1 Host routes" >&2
+ fail=1
+fi
+
+if rg -n 'getMcpServers\s*\([^)]*context|getMcpAuth|getAuthTokenForServer' tests/e2e; then
+ echo "FAIL: E2E helpers retain a caller-selected v1 Host contract" >&2
+ fail=1
+fi
+
+if [[ "${fail}" -ne 0 ]]; then
+ exit 1
+fi
+
+echo "PASS: NP-08 v1 reference inventory"
diff --git a/tests/e2e/helpers.ts b/tests/e2e/helpers.ts
index aadf1b29d..4d8d1cc78 100644
--- a/tests/e2e/helpers.ts
+++ b/tests/e2e/helpers.ts
@@ -204,9 +204,9 @@ export async function waitForTasksProcessed(minCount: number, timeoutMs = 60_000
throw new Error(`Agent did not process ${minCount} tasks within ${timeoutMs}ms`)
}
-/** Query host-context-controller for MCP servers in a context. */
-export async function getMcpServers(contextRef: string): Promise<any> {
- const { data } = await fetchJson(`${CTX_MAPPER_URL}/api/v1/mcpservers/context/${contextRef}`)
+/** Query the temporary PR 2 global-inventory compatibility route. */
+export async function getGlobalMcpInventory(): Promise<any> {
+ const { data } = await fetchJson(`${CTX_MAPPER_URL}/api/v1/mcpservers`)
return data
}
diff --git a/tests/e2e/mcp-host/context-mapper.test.ts b/tests/e2e/mcp-host/context-mapper.test.ts
index 7b8a80bf9..7e83847b5 100644
--- a/tests/e2e/mcp-host/context-mapper.test.ts
+++ b/tests/e2e/mcp-host/context-mapper.test.ts
@@ -1,8 +1,8 @@
/**
- * E2E: Context Mapper — verify server discovery and filtering.
+ * E2E: Context Mapper — verify the PR 1 route and disclosure boundaries.
*/
import { beforeAll, describe, expect, it } from 'vitest'
-import { CTX_MAPPER_URL, getMcpServers, healthCheck } from '../helpers.js'
+import { CTX_MAPPER_URL, getGlobalMcpInventory, healthCheck } from '../helpers.js'
let contextMapperUp = false
@@ -16,27 +16,37 @@ beforeAll(async () => {
})
describe('Context Mapper', () => {
- it('GET /api/v1/mcpservers/context/context1 returns servers', async () => {
+ it('retains only the metadata-only global v1 inventory for the PR 2 proxy migration', async () => {
if (!contextMapperUp) return
- const data = await getMcpServers('context1')
+ const data = await getGlobalMcpInventory()
expect(data.servers).toBeDefined()
expect(Array.isArray(data.servers)).toBe(true)
- expect(data.contextRef).toBe('context1')
+ expect(data.contextRef).toBe('*')
+ for (const server of data.servers) {
+ expect(server).not.toHaveProperty('auth')
+ expect(server).not.toHaveProperty('secretRef')
+ expect(server).not.toHaveProperty('secretKey')
+ }
})
- it('context1 includes at least one ready MCP server with transport metadata', async () => {
+ it.each([
+ '/api/v1/mcpservers/context/context1',
+ '/api/v1/mcpservers/server-from-another-context/auth',
+ ])('tombstones caller-selected legacy Host route %s', async path => {
if (!contextMapperUp) return
- const data = await getMcpServers('context1')
- const readyServer = data.servers.find((s: any) => s.status?.ready === true)
- expect(readyServer).toBeDefined()
- expect(readyServer.transport).toBeDefined()
- expect(readyServer.transport.type).toBeDefined()
+ const response = await fetch(`${CTX_MAPPER_URL}${path}`)
+
+ expect(response.status).toBe(410)
+ expect(response.headers.get('cache-control')).toContain('no-store')
+ await expect(response.json()).resolves.toEqual({ error: 'gone' })
})
- it('non-existent context returns empty server list', async () => {
+ it('rejects the v2 Host inventory without an authenticated Host JWT', async () => {
if (!contextMapperUp) return
- const res = await fetch(`${CTX_MAPPER_URL}/api/v1/mcpservers/context/does-not-exist`)
- const data = await res.json()
- expect(data.servers).toEqual([])
+ const response = await fetch(`${CTX_MAPPER_URL}/api/v2/hosts/self/mcpservers`)
+
+ expect(response.status).toBe(401)
+ expect(response.headers.get('cache-control')).toContain('no-store')
+ await expect(response.json()).resolves.toEqual({ error: 'unauthorized' })
})
})
diff --git a/tests/e2e/mcp-host/tool-discovery.test.ts b/tests/e2e/mcp-host/tool-discovery.test.ts
index 65464cba7..77fe1365a 100644
--- a/tests/e2e/mcp-host/tool-discovery.test.ts
+++ b/tests/e2e/mcp-host/tool-discovery.test.ts
@@ -1,44 +1,47 @@
/**
* E2E: Tool Discovery — verify mcp-host discovers MCP tools via context-mapper.
*
- * Checks both the context-mapper API and mcp-host startup logs to confirm
- * MCP tools are registered and used during message processing.
+ * Uses mcp-host's authenticated runtime status and startup logs to confirm MCP
+ * tools are registered and used during message processing. It deliberately
+ * does not call an HCC route with a caller-selected Context.
*/
-import { describe, it, expect } from "vitest";
-import { getMcpServers, sendMessage, waitForIdle, getPodLogs } from "../helpers.js";
+import { describe, expect, it } from 'vitest'
+import { getPodLogs, getStatus, sendMessage, waitForIdle } from '../helpers.js'
-describe("Tool Discovery", () => {
- it("context-mapper reports mock-server with 2 tools", async () => {
- const data = await getMcpServers("context1");
- const mock = data.servers.find((s: any) => s.name === "mock-server");
- expect(mock).toBeDefined();
- expect(mock.status.ready).toBe(true);
- });
+describe('Tool Discovery', () => {
+ it('mcp-host publishes only its effective connected mock-server fleet', async () => {
+ const status = await getStatus()
+ const mock = status.mcpServers?.find((server: any) => server.name === 'mock-server')
- it("mcp-host connected to mock-server and found tools", async () => {
+ expect(mock).toBeDefined()
+ expect(mock.state).toBe('connected')
+ expect(mock.toolCount).toBe(2)
+ })
+
+ it('mcp-host connected to mock-server and found tools', async () => {
// These log lines are emitted by MCP connection logic (shared by both pipelines)
- const logs = getPodLogs("mcp-host", "mcp-host", 500);
- expect(logs).toContain("[MCP:mock-server] Connected successfully");
- expect(logs).toContain("[MCP:mock-server] Found 2 tool(s):");
- expect(logs).toContain("echo: Echoes back the provided text");
- expect(logs).toContain("add: Adds two numbers together");
- });
+ const logs = getPodLogs('mcp-host', 'mcp-host', 500)
+ expect(logs).toContain('[MCP:mock-server] Connected successfully')
+ expect(logs).toContain('[MCP:mock-server] Found 2 tool(s):')
+ expect(logs).toContain('echo: Echoes back the provided text')
+ expect(logs).toContain('add: Adds two numbers together')
+ })
it("mcp-host reports total tools available (at least mock-server's 2)", async () => {
- const logs = getPodLogs("mcp-host", "mcp-host", 500);
+ const logs = getPodLogs('mcp-host', 'mcp-host', 500)
// Cluster may have additional MCP servers beyond mock-server;
// verify the log line exists and reports >= 2 tools
- const match = logs.match(/\[Main\] Total tools available: (\d+)/);
- expect(match).not.toBeNull();
- expect(Number(match![1])).toBeGreaterThanOrEqual(2);
- });
+ const match = logs.match(/\[Main\] Total tools available: (\d+)/)
+ expect(match).not.toBeNull()
+ expect(Number(match![1])).toBeGreaterThanOrEqual(2)
+ })
- it("mcp-host processes messages via single pipeline", async () => {
- await sendMessage("tool discovery test");
- await waitForIdle(30_000);
+ it('mcp-host processes messages via single pipeline', async () => {
+ await sendMessage('tool discovery test')
+ await waitForIdle(30_000)
- const logs = getPodLogs("mcp-host", "mcp-host", 200);
+ const logs = getPodLogs('mcp-host', 'mcp-host', 200)
// Single pipeline — verify the task was processed
- expect(logs).toContain("[Agent] Processing task");
- });
-});
+ expect(logs).toContain('[Agent] Processing task')
+ })
+})
diff --git a/workflow-recipes/tests/e2e/hcc-wrc-integration.test.ts b/workflow-recipes/tests/e2e/hcc-wrc-integration.test.ts
index e34d0e3d5..4930973f9 100644
--- a/workflow-recipes/tests/e2e/hcc-wrc-integration.test.ts
+++ b/workflow-recipes/tests/e2e/hcc-wrc-integration.test.ts
@@ -116,13 +116,15 @@ describe('HCC-WRC Integration E2E', () => {
expect(logs).toContain(MCP_SERVER_NAME)
})
- // E6.10: HCC Discovery API serves the delegated McpServer
- // The Discovery API filters by Context allowlist. The WRC must first:
+ // E6.10: temporary PR 2 system inventory serves the delegated McpServer
+ // This suite does not mint a Host JWT, so it cannot exercise the v2 Host
+ // route. Keep the current global metadata-only poll assertion here until
+ // PR 2 adds an authenticated system-inventory fixture.
// 1. Create the McpServer CRD (done in E6.9)
// 2. Patch the Context to add the server to mcpServers[]
// 3. HCC watches Context change → caches the server → serves via API
// We wait for Context to be patched first, then poll the Discovery API.
- it('E6.10 — HCC Discovery API lists delegated McpServer', { timeout: 60_000 }, async () => {
+ it('E6.10 — HCC metadata inventory lists delegated McpServer', { timeout: 60_000 }, async () => {
// Wait for WRC to patch Context (may take a reconciliation cycle)
const ctxStart = Date.now()
while (Date.now() - ctxStart < 30_000) {
@@ -138,9 +140,7 @@ describe('HCC-WRC Integration E2E', () => {
let found: { name: string; transport?: { type: string } } | undefined
while (Date.now() - start < 20_000) {
- const { data } = await fetchJson(
- `http://localhost:${HCC_LOCAL_PORT}/api/v1/mcpservers/context/default`
- )
+ const { data } = await fetchJson(`http://localhost:${HCC_LOCAL_PORT}/api/v1/mcpservers`)
const response = data as { servers: Array<{ name: string; transport?: { type: string } }> }
if (response.servers) {
found = response.servers.find(s => s.name === MCP_SERVER_NAME)
@@ -151,6 +151,9 @@ describe('HCC-WRC Integration E2E', () => {
expect(found).toBeDefined()
expect(found!.transport?.type).toBe('streamableHttp')
+ expect(found).not.toHaveProperty('secretRef')
+ expect(found).not.toHaveProperty('secretKey')
+ expect(found).not.toHaveProperty('auth')
})
// E6.11: Context patch triggers L2 context-allow NetworkPolicy from HCC
@@ -228,11 +231,9 @@ describe('HCC-WRC Integration E2E', () => {
expect(body).toContain('clerum_hcc_mcpservers_total')
})
- // E6.14: HCC Discovery API no longer serves the deleted McpServer
- it('E6.14 — HCC Discovery API no longer lists deleted McpServer', async () => {
- const { data } = await fetchJson(
- `http://localhost:${HCC_LOCAL_PORT}/api/v1/mcpservers/context/default`
- )
+ // E6.14: temporary PR 2 metadata inventory no longer lists the deleted server
+ it('E6.14 — HCC metadata inventory no longer lists deleted McpServer', async () => {
+ const { data } = await fetchJson(`http://localhost:${HCC_LOCAL_PORT}/api/v1/mcpservers`)
const response = data as { servers: Array<{ name: string }> }
const found = (response.servers ?? []).find(s => s.name === MCP_SERVER_NAME)
diff --git a/workflow-recipes/tests/e2e/package-lock.json b/workflow-recipes/tests/e2e/package-lock.json
index 3bbbf90d3..885666681 100644
--- a/workflow-recipes/tests/e2e/package-lock.json
+++ b/workflow-recipes/tests/e2e/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workflow-recipes-e2e",
- "version": "0.1.18",
+ "version": "0.1.19",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workflow-recipes-e2e",
- "version": "0.1.18",
+ "version": "0.1.19",
"devDependencies": {
"@types/node": "^20.10.0",
"typescript": "^5.3.0",
diff --git a/workflow-recipes/tests/e2e/package.json b/workflow-recipes/tests/e2e/package.json
index 075f12ed2..1f91e6533 100644
--- a/workflow-recipes/tests/e2e/package.json
+++ b/workflow-recipes/tests/e2e/package.json
@@ -1,6 +1,6 @@
{
"name": "workflow-recipes-e2e",
- "version": "0.1.18",
+ "version": "0.1.19",
"private": true,
"description": "E2E tests for Workload Recipes Controller (minikube)",
"scripts": {