Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(mcp-host): resolve installed llm-hook refs into runtime descriptors (§8.2)
Andy Paviaeb4df2a573b1
diff --git a/deploy/base/llm-hooks/rbac.yaml b/deploy/base/llm-hooks/rbac.yamlindex 8da0b043c..84d96b97b 100644--- a/deploy/base/llm-hooks/rbac.yaml+++ b/deploy/base/llm-hooks/rbac.yaml@@ -86,3 +86,36 @@ subjects:- kind: ServiceAccountname: control-apinamespace: control-plane+---+# --- Role: mcp-host hook reader (llm-hooks namespace) ---+# mcp-host is a READ-ONLY consumer of LlmHook CRs (spec §8.2): at boot each+# host pod resolves its `Host.spec.guardrails.hooks` references into runtime+# hook descriptors (endpoint/capabilities/failMode). Host SAs are per-host+# (`host-<name>-sa` in the mcp-host namespace), so the binding targets the whole+# mcp-host ServiceAccount group rather than enumerating each host.+apiVersion: rbac.authorization.k8s.io/v1+kind: Role+metadata:+ name: mcp-host-hook-reader+ namespace: llm-hooks+rules:+ - apiGroups: ["clerum.io"]+ resources: ["llmhooks"]+ verbs: ["get", "list", "watch"]+ - apiGroups: ["clerum.io"]+ resources: ["llmhooks/status"]+ verbs: ["get"]+---+apiVersion: rbac.authorization.k8s.io/v1+kind: RoleBinding+metadata:+ name: mcp-host-hook-reader+ namespace: llm-hooks+roleRef:+ apiGroup: rbac.authorization.k8s.io+ kind: Role+ name: mcp-host-hook-reader+subjects:+ - kind: Group+ name: system:serviceaccounts:mcp-host+ apiGroup: rbac.authorization.k8s.iodiff --git a/hooks/reference-guardrail-hook/Dockerfile b/hooks/reference-guardrail-hook/Dockerfilenew file mode 100644index 000000000..2d665ecc1--- /dev/null+++ b/hooks/reference-guardrail-hook/Dockerfile@@ -0,0 +1,8 @@+# Reference guardrail hook — real `/v1` LLM-lane hook for E2E testing.+FROM node:20-alpine+WORKDIR /app+COPY server.js ./+ENV PORT=8080+EXPOSE 8080+USER node+CMD ["node", "server.js"]diff --git a/hooks/reference-guardrail-hook/deploy.yaml b/hooks/reference-guardrail-hook/deploy.yamlnew file mode 100644index 000000000..d84a16f3f--- /dev/null+++ b/hooks/reference-guardrail-hook/deploy.yaml@@ -0,0 +1,54 @@+# Deployment + Service for the reference guardrail hook, in the llm-hooks+# namespace. LlmHook CRs point at this via a `service` target+# (name: reference-guardrail-hook, namespace: llm-hooks, port: 8080).+apiVersion: apps/v1+kind: Deployment+metadata:+ name: reference-guardrail-hook+ namespace: llm-hooks+ labels:+ app: reference-guardrail-hook+spec:+ replicas: 1+ selector:+ matchLabels:+ app: reference-guardrail-hook+ template:+ metadata:+ labels:+ app: reference-guardrail-hook+ spec:+ containers:+ - name: hook+ image: reference-guardrail-hook:dev+ imagePullPolicy: IfNotPresent+ ports:+ - name: http+ containerPort: 8080+ readinessProbe:+ httpGet:+ path: /healthz+ port: 8080+ initialDelaySeconds: 1+ periodSeconds: 5+ securityContext:+ allowPrivilegeEscalation: false+ runAsNonRoot: true+ runAsUser: 1000+ capabilities:+ drop: ["ALL"]+---+apiVersion: v1+kind: Service+metadata:+ name: reference-guardrail-hook+ namespace: llm-hooks+ labels:+ app: reference-guardrail-hook+spec:+ selector:+ app: reference-guardrail-hook+ ports:+ - name: http+ port: 8080+ targetPort: 8080diff --git a/hooks/reference-guardrail-hook/server.js b/hooks/reference-guardrail-hook/server.jsnew file mode 100644index 000000000..ce50c418f--- /dev/null+++ b/hooks/reference-guardrail-hook/server.js@@ -0,0 +1,189 @@+/*+ * Reference guardrail hook — a real `/v1` LLM-lane hook for end-to-end testing+ * of the MCP Host guardrail engine (spec §8.1). Zero-dependency (node:http) so+ * the image builds without npm.+ *+ * It implements every LLM-lane lifecycle point. Routing is path-suffix based:+ * the engine calls `{endpoint}{path}/v1/{point}`, so a single container can back+ * several LlmHook CRs on distinct `spec.path`s (digest-dedup co-location).+ *+ * POST .../v1/pre_call -> reject obvious jailbreak / prompt-injection (needs may_deny)+ * POST .../v1/moderate -> HTTP 422 on disallowed content, else 200 (needs may_deny)+ * POST .../v1/post_call -> redact PII in the model output (needs may_substitute_result)+ * POST .../v1/on_error -> supply a text-only fallback (needs may_substitute_result)+ *+ * The wire contract mirrors mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts.+ */+const http = require('node:http')++const PORT = Number(process.env.PORT || 8080)++// --- content rules -------------------------------------------------------++const JAILBREAK = [+ /ignore\s+(all\s+|your\s+)?(previous\s+|prior\s+)?(instructions|rules)/i,+ /disregard\s+(the\s+)?(above|previous|prior)/i,+ /you\s+are\s+(now\s+)?dan\b/i,+ /\bjailbreak\b/i,+ /reveal\s+(your\s+)?(full\s+)?system\s+prompt/i,+ /print\s+(your\s+)?system\s+prompt/i,+ /no\s+(more\s+)?rules\b/i,+]++const DISALLOWED = [+ /\bpipe\s*bomb\b/i,+ /\bbomb\b/i,+ /\bexplosive/i,+ /\bphishing\b/i,+ /\bmalware\b/i,+ /how\s+to\s+(make|build|create|synthesize)\s+.*(bomb|weapon|explosive|meth|nerve\s*agent)/i,+ /impersonat\w*\s+.*bank/i,+]++// PII redactors applied to post_call output content.+const REDACTORS = [+ { re: /\b(?:\d[ -]?){13,16}\b/g, to: '[REDACTED_CARD]' }, // card-ish digit runs+ { re: /\b\d{3}-\d{2}-\d{4}\b/g, to: '[REDACTED_SSN]' },+ { re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, to: '[REDACTED_EMAIL]' },+]++// --- helpers -------------------------------------------------------------++function lastUserText(body) {+ const msgs = Array.isArray(body?.messages) ? body.messages : []+ for (let i = msgs.length - 1; i >= 0; i--) {+ const m = msgs[i]+ if (m && m.role === 'user') {+ return typeof m.content === 'string' ? m.content : JSON.stringify(m.content ?? '')+ }+ }+ // Fall back to any last message content so moderation still sees something.+ const last = msgs[msgs.length - 1]+ return last ? (typeof last.content === 'string' ? last.content : JSON.stringify(last.content)) : ''+}++function pointFromUrl(url) {+ const path = (url || '').split('?')[0]+ const m = path.match(/\/v1\/([a-z_]+)\/?$/)+ return m ? m[1] : null+}++function send(res, status, obj) {+ const payload = obj === undefined ? '' : JSON.stringify(obj)+ res.writeHead(status, { 'content-type': 'application/json' })+ res.end(payload)+}++function log(point, decision, extra) {+ console.log(+ JSON.stringify({ hook: 'reference-guardrail-hook', point, decision, ...(extra || {}) })+ )+}++// --- handlers ------------------------------------------------------------++function handlePreCall(body, res) {+ const text = lastUserText(body)+ const hit = JAILBREAK.find(re => re.test(text))+ if (hit) {+ log('pre_call', 'reject', { pattern: String(hit) })+ return send(res, 200, {+ action: 'reject',+ code: 'jailbreak_blocked',+ message: 'Prompt-injection / jailbreak attempt blocked by the pre_call guardrail.',+ })+ }+ log('pre_call', 'continue')+ return send(res, 200, { action: 'continue' })+}++function handleModerate(body, res) {+ const text = lastUserText(body)+ const hit = DISALLOWED.find(re => re.test(text))+ if (hit) {+ log('moderate', 'block', { pattern: String(hit) })+ // 4xx => the engine maps to a deny (needs may_deny).+ return send(res, 422, {+ code: 'moderation_blocked',+ message: 'Content blocked by the moderation guardrail (illicit / harmful request).',+ })+ }+ log('moderate', 'pass')+ return send(res, 200, {}) // 2xx => pass+}++function handlePostCall(body, res) {+ const original = typeof body?.response?.content === 'string' ? body.response.content : ''+ let redacted = original+ let changed = false+ for (const { re, to } of REDACTORS) {+ if (re.test(redacted)) {+ changed = true+ redacted = redacted.replace(re, to)+ }+ }+ log('post_call', changed ? 'redacted' : 'unchanged')+ // Return the (possibly redacted) content; engine substitutes when may_substitute_result.+ return send(res, 200, { response: { content: redacted } })+}++function handleOnError(_body, res) {+ log('on_error', 'recover')+ return send(res, 200, {+ action: 'recover',+ response: {+ content:+ '⚠️ The model call failed; this fallback response was supplied by the on_error guardrail.',+ },+ })+}++const HANDLERS = {+ pre_call: handlePreCall,+ moderate: handleModerate,+ post_call: handlePostCall,+ on_error: handleOnError,+}++// --- server --------------------------------------------------------------++const server = http.createServer((req, res) => {+ if (req.method === 'GET') {+ // Liveness / readiness.+ return send(res, 200, { ok: true })+ }+ if (req.method !== 'POST') return send(res, 405, { error: 'method_not_allowed' })++ const point = pointFromUrl(req.url)+ const handler = point && HANDLERS[point]+ if (!handler) return send(res, 404, { error: 'unknown_lifecycle_point', url: req.url })++ let raw = ''+ let tooBig = false+ req.on('data', chunk => {+ raw += chunk+ if (raw.length > 5_000_000) {+ tooBig = true+ req.destroy()+ }+ })+ req.on('end', () => {+ if (tooBig) return+ let body = {}+ try {+ body = raw ? JSON.parse(raw) : {}+ } catch {+ return send(res, 400, { error: 'invalid_json' })+ }+ try {+ handler(body, res)+ } catch (e) {+ console.error('handler_error', e)+ send(res, 500, { error: 'handler_error' })+ }+ })+})++server.listen(PORT, () => {+ console.log(`[reference-guardrail-hook] listening on :${PORT}`)+})diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex eb3509021..e569f9498 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.247",+ "version": "0.1.248","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.247",+ "version": "0.1.248","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 6c0b6046d..c5c1672fb 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.247",+ "version": "0.1.248","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/__tests__/guardrailHookResolver.test.ts b/mcp-host/src/__tests__/guardrailHookResolver.test.tsnew file mode 100644index 000000000..75cca40a2--- /dev/null+++ b/mcp-host/src/__tests__/guardrailHookResolver.test.ts@@ -0,0 +1,163 @@+/**+ * Hook resolution tests (spec §8.2). Drives `resolveGuardrailHookDescriptors`+ * with an injected `getLlmHook` so it runs without a cluster. The image-target+ * pod-key derivation is asserted against host-context-controller's real output+ * for the redis@…:6379 hook (`b09ff9ee0137b344`) to guard the byte-match.+ */+import { describe, expect, it, vi } from 'vitest'+import type { GuardrailsConfig } from '../core/guardrails/config'+import {+ resolveGuardrailHookDescriptors,+ withResolvedHookDescriptors,+} from '../guardrailHookResolver'+import type { LlmHookCR } from '../k8sClient'++const NS = 'llm-hooks'++function guardrails(+ hooks: Record<string, Array<{ id: string; digest?: string }>>+): GuardrailsConfig {+ return { hooks }+}++function deps(crs: Record<string, LlmHookCR | null>) {+ return {+ llmHooksNamespace: NS,+ getLlmHook: vi.fn(async (name: string) => crs[name] ?? null),+ }+}++describe('resolveGuardrailHookDescriptors', () => {+ it('resolves a service-target hook, mapping phases and preserving caps/failMode', async () => {+ const cr: LlmHookCR = {+ metadata: { name: 'h1' },+ spec: {+ target: { service: { name: 'reference-guardrail-hook', namespace: NS, port: 8080 } },+ path: '/moderate-redact',+ lifecyclePoints: ['moderate', 'postCallSuccess'],+ capabilities: ['may_deny', 'may_substitute_result'],+ failMode: 'closed',+ order: 100,+ },+ }+ const out = await resolveGuardrailHookDescriptors(+ guardrails({ moderate: [{ id: 'h1' }], postCallSuccess: [{ id: 'h1' }] }),+ deps({ h1: cr })+ )+ expect(out).toHaveLength(1) // deduped across phases+ expect(out[0]).toMatchObject({+ id: 'h1',+ endpoint: `http://reference-guardrail-hook.${NS}.svc.cluster.local:8080`,+ path: '/moderate-redact',+ lifecyclePoints: ['moderate', 'post_call'],+ capabilities: ['may_deny', 'may_substitute_result'],+ failMode: 'closed',+ order: 100,+ })+ })++ it('derives the image-target Service DNS with the controller pod-key (byte-match)', async () => {+ const cr: LlmHookCR = {+ metadata: { name: 'img' },+ spec: {+ target: {+ image: {+ ref: 'docker.io/library/redis@sha256:e7723ff73d963f5cc6d9c4643ea3d989527a402a319239054e9472a7fb9219a2',+ port: 6379,+ },+ },+ lifecyclePoints: ['preCall'],+ capabilities: ['may_deny'],+ },+ }+ const out = await resolveGuardrailHookDescriptors(+ guardrails({ preCall: [{ id: 'img' }] }),+ deps({ img: cr })+ )+ expect(out[0].endpoint).toBe(`http://llmhook-b09ff9ee0137b344.${NS}.svc.cluster.local:6379`)+ expect(out[0].lifecyclePoints).toEqual(['pre_call'])+ })++ it('resolves a remote-target hook to its baseUrl', async () => {+ const cr: LlmHookCR = {+ metadata: { name: 'r' },+ spec: {+ target: { remote: { baseUrl: 'https://hooks.example.com' } },+ lifecyclePoints: ['preCall'],+ },+ }+ const out = await resolveGuardrailHookDescriptors(+ guardrails({ preCall: [{ id: 'r' }] }),+ deps({ r: cr })+ )+ expect(out[0].endpoint).toBe('https://hooks.example.com')+ })++ it('skips a dangling reference (CR not found)', async () => {+ const out = await resolveGuardrailHookDescriptors(+ guardrails({ preCall: [{ id: 'missing' }] }),+ deps({ missing: null })+ )+ expect(out).toEqual([])+ })++ it('skips an image hook whose reconciled digest no longer matches the ref (fail-closed)', async () => {+ const cr: LlmHookCR = {+ metadata: { name: 'img' },+ spec: {+ target: { image: { ref: 'repo/img@sha256:new', port: 8080 } },+ lifecyclePoints: ['preCall'],+ },+ status: { observedDigest: 'sha256:new' },+ }+ const out = await resolveGuardrailHookDescriptors(+ guardrails({ preCall: [{ id: 'img', digest: 'sha256:OLD' }] }),+ deps({ img: cr })+ )+ expect(out).toEqual([])+ })++ it('drops unknown capabilities and hooks with no known lifecycle points', async () => {+ const good: LlmHookCR = {+ spec: {+ target: { service: { name: 's', namespace: NS, port: 80 } },+ lifecyclePoints: ['moderate'],+ capabilities: ['may_deny', 'not_a_capability' as never],+ },+ }+ const noPoints: LlmHookCR = {+ spec: { target: { service: { name: 's', namespace: NS, port: 80 } }, lifecyclePoints: [] },+ }+ const out = await resolveGuardrailHookDescriptors(+ guardrails({ moderate: [{ id: 'good' }, { id: 'noPoints' }] }),+ deps({ good, noPoints })+ )+ expect(out).toHaveLength(1)+ expect(out[0].capabilities).toEqual(['may_deny'])+ })+})++describe('withResolvedHookDescriptors', () => {+ it('merges resolved descriptors while preserving inline descriptors and other blocks', () => {+ const inline = {+ id: 'inline',+ endpoint: 'http://x',+ path: '/',+ lifecyclePoints: ['pre_call' as const],+ capabilities: [],+ failMode: 'open' as const,+ order: 0,+ }+ const base: GuardrailsConfig = {+ builtins: [{ type: 'prompt-shaping' }],+ hookDescriptors: [inline],+ }+ const merged = withResolvedHookDescriptors(base, [{ ...inline, id: 'resolved' }])+ expect(merged?.builtins).toEqual([{ type: 'prompt-shaping' }])+ expect(merged?.hookDescriptors?.map(d => d.id)).toEqual(['inline', 'resolved'])+ })++ it('returns undefined when there is nothing to apply', () => {+ expect(withResolvedHookDescriptors(undefined, [])).toBeUndefined()+ })+})diff --git a/mcp-host/src/config.ts b/mcp-host/src/config.tsindex 0eb2e477e..52646e39d 100644--- a/mcp-host/src/config.ts+++ b/mcp-host/src/config.ts@@ -47,6 +47,10 @@ export interface Config {// Kubernetes namespacenamespace: string+ // Namespace where installed LlmHook workloads/Services live (spec §8.2). The+ // guardrail hook resolver derives in-cluster endpoints against this namespace.+ llmHooksNamespace: string+// Name of the operator-managed LLM allowlist ConfigMap watched by the// ConfigStore (R3). Configurable so canary/test namespaces can point at a// differently-named artifact; default matches the control-api writer.@@ -535,6 +539,9 @@ export const config: Config = {// Kubernetes namespacenamespace: getEnv('CLERUM_NAMESPACE', 'default')!,+ // Namespace where installed LlmHook workloads/Services live (spec §8.2).+ llmHooksNamespace: getEnv('CLERUM_LLM_HOOKS_NAMESPACE', 'llm-hooks')!,+// LLM allowlist ConfigMap name (R3). CROSS-SERVICE CONTRACT: the default// (`clerum-llm-allowed-models`) is the CM produced by control-api// (control-api/src/services/llmAllowedModelsConfigMap.ts) and also read by WRCdiff --git a/mcp-host/src/guardrailHookResolver.ts b/mcp-host/src/guardrailHookResolver.tsnew file mode 100644index 000000000..70de38dda--- /dev/null+++ b/mcp-host/src/guardrailHookResolver.ts@@ -0,0 +1,203 @@+/**+ * Guardrail hook resolution (spec §8.2) — turns the admin-authored+ * `Host.spec.guardrails.hooks` references (`{id, digest}` grouped by phase) into+ * runtime `HookDescriptor`s the LLM-lane engine can call.+ *+ * For each unique referenced hook id we read its LlmHook CR (llm-hooks+ * namespace) and derive:+ * - endpoint — image target: the digest-dedup Service DNS the controller+ * deploys (`llmhook-<podKey>.<ns>.svc`); service target: the+ * referenced Service DNS; remote target: the external baseUrl.+ * - path / lifecyclePoints / capabilities / failMode / order from the CR spec.+ *+ * The pod-key derivation MUST byte-match host-context-controller's+ * `computePodKey` (llmHookReconciler.ts) or the Service DNS won't resolve.+ *+ * `getLlmHook` is injected so this is unit-testable without a cluster.+ */+import { createHash } from 'crypto'+import type { GuardrailsConfig } from './core/guardrails/config'+import type { HookDescriptor, LifecyclePoint } from './core/guardrails/hooks/types'+import type { Capability } from './core/guardrails/types'+import type { LlmHookCR } from './k8sClient'++/** Host phase key (CRD/Host naming) → engine lifecycle point. */+const PHASE_TO_POINT: Record<string, LifecyclePoint> = {+ preCall: 'pre_call',+ moderate: 'moderate',+ postCallSuccess: 'post_call',+ onError: 'on_error',+ preToolUse: 'pre_tool_use',+ postToolUse: 'post_tool_use',+}++const KNOWN_CAPABILITIES: readonly string[] = [+ 'may_deny',+ 'may_rewrite',+ 'may_substitute_result',+ 'may_add_context',+]++interface HookRef {+ id?: string+ digest?: string+}++type ImageTarget = NonNullable<NonNullable<LlmHookCR['spec']>['target']>['image']++export interface ResolveHookDeps {+ getLlmHook: (name: string) => Promise<LlmHookCR | null>+ llmHooksNamespace: string+}++/** Unique referenced hook ids (across all phases) → the first digest seen for each. */+function collectRefs(guardrails: GuardrailsConfig | undefined): Map<string, string | undefined> {+ const out = new Map<string, string | undefined>()+ const hooks = guardrails?.hooks as Record<string, unknown> | undefined+ if (!hooks) return out+ for (const phase of Object.keys(hooks)) {+ const refs = hooks[phase]+ if (!Array.isArray(refs)) continue+ for (const r of refs as HookRef[]) {+ if (r && typeof r.id === 'string' && !out.has(r.id)) out.set(r.id, r.digest)+ }+ }+ return out+}++/** Order-independent egress canonicalization — mirrors HCC `normalizeEgressBindings`. */+function normalizeEgressBindings(+ bindings: NonNullable<ImageTarget>['egressBindings']+): Array<{ cidr: string | null; toFQDN: string | null; ports: number[] }> {+ return (bindings ?? [])+ .map(b => ({+ cidr: b.cidr ?? null,+ toFQDN: b.toFQDN ?? null,+ ports: [...(b.ports ?? [])].sort((a, z) => a - z),+ }))+ .sort((a, z) => JSON.stringify(a).localeCompare(JSON.stringify(z)))+}++/** MUST byte-match host-context-controller `computePodKey` (key order matters). */+function computePodKey(img: NonNullable<ImageTarget>): string {+ const canonical = {+ imageRef: img.ref,+ port: img.port,+ envSecret: img.envSecret ?? '',+ egressBindings: normalizeEgressBindings(img.egressBindings),+ addCapabilities: [...(img.security?.addCapabilities ?? [])].sort(),+ }+ return createHash('sha256').update(JSON.stringify(canonical)).digest('hex').slice(0, 16)+}++type ResolvedEndpoint = { endpoint: string; kind: 'image' | 'service' | 'remote' }++function endpointFor(cr: LlmHookCR, ns: string): ResolvedEndpoint | null {+ const t = cr.spec?.target+ const img = t?.image+ if (img?.ref && img.port) {+ const podKey = computePodKey(img)+ return {+ endpoint: `http://llmhook-${podKey}.${ns}.svc.cluster.local:${img.port}`,+ kind: 'image',+ }+ }+ const svc = t?.service+ if (svc?.name && svc.namespace && svc.port) {+ return {+ endpoint: `http://${svc.name}.${svc.namespace}.svc.cluster.local:${svc.port}`,+ kind: 'service',+ }+ }+ if (t?.remote?.baseUrl) return { endpoint: t.remote.baseUrl, kind: 'remote' }+ return null+}++/**+ * Resolve every referenced hook into a `HookDescriptor`. Dangling refs, targets+ * with no resolvable endpoint, and (for image hooks) digest mismatches are+ * skipped with a warning rather than failing the whole boot.+ */+export async function resolveGuardrailHookDescriptors(+ guardrails: GuardrailsConfig | undefined,+ deps: ResolveHookDeps+): Promise<HookDescriptor[]> {+ const refs = collectRefs(guardrails)+ const out: HookDescriptor[] = []++ for (const [id, refDigest] of refs) {+ let cr: LlmHookCR | null+ try {+ cr = await deps.getLlmHook(id)+ } catch (err) {+ console.error(`[Guardrails] failed reading LlmHook ${id}:`, err)+ continue+ }+ if (!cr) continue // dangling reference → skip++ const ep = endpointFor(cr, deps.llmHooksNamespace)+ if (!ep) {+ console.warn(`[Guardrails] LlmHook ${id} has no resolvable target; skipping`)+ continue+ }++ const points = (cr.spec?.lifecyclePoints ?? [])+ .map(p => PHASE_TO_POINT[p])+ .filter((p): p is LifecyclePoint => !!p)+ if (points.length === 0) {+ console.warn(`[Guardrails] LlmHook ${id} declares no known lifecycle points; skipping`)+ continue+ }++ // Digest binding (§8.2): an image hook whose reconciled digest no longer+ // matches the admin-pinned reference is not trusted — skip (fail-closed).+ if (+ ep.kind === 'image' &&+ refDigest &&+ cr.status?.observedDigest &&+ refDigest !== cr.status.observedDigest+ ) {+ console.warn(+ `[Guardrails] LlmHook ${id} digest mismatch (ref=${refDigest} observed=${cr.status.observedDigest}); skipping`+ )+ continue+ }++ const capabilities = (cr.spec?.capabilities ?? []).filter((c): c is Capability =>+ KNOWN_CAPABILITIES.includes(c)+ )+ const path = cr.spec?.path ?? '/'+ const failMode: 'open' | 'closed' = cr.spec?.failMode === 'open' ? 'open' : 'closed'+ const order = typeof cr.spec?.order === 'number' ? cr.spec.order : 100++ out.push({+ id,+ endpoint: ep.endpoint,+ path,+ lifecyclePoints: points,+ capabilities,+ failMode,+ order,+ })+ console.log(+ `[Guardrails] resolved hook ${id} -> ${ep.endpoint}${path} points=[${points.join(',')}] caps=[${capabilities.join(',')}] failMode=${failMode}`+ )+ }++ return out+}++/**+ * Merge resolved descriptors into a guardrails config for the agent. Preserves+ * any inline `hookDescriptors` (dev/E2E via CLERUM_GUARDRAILS_CONFIG) and the+ * rest of the block; returns undefined only when there is nothing to apply.+ */+export function withResolvedHookDescriptors(+ guardrails: GuardrailsConfig | undefined,+ resolved: HookDescriptor[]+): GuardrailsConfig | undefined {+ if (!guardrails && resolved.length === 0) return undefined+ const inline = guardrails?.hookDescriptors ?? []+ const hookDescriptors = [...inline, ...resolved]+ return { ...(guardrails ?? {}), hookDescriptors }+}diff --git a/mcp-host/src/k8sClient.ts b/mcp-host/src/k8sClient.tsindex d6a1aeae8..1ab714733 100644--- a/mcp-host/src/k8sClient.ts+++ b/mcp-host/src/k8sClient.ts@@ -15,6 +15,59 @@ const customObjectsApi = kc.makeApiClient(k8s.CustomObjectsApi)const GROUP = 'clerum.io'const VERSION = 'v1alpha1'const HOSTS_PLURAL = 'hosts'+const LLMHOOKS_PLURAL = 'llmhooks'++/**+ * Raw LlmHook CR (spec §8) as read by mcp-host. mcp-host READS these to resolve+ * `Host.spec.guardrails.hooks` references into runtime hook descriptors; it never+ * writes them (the status subresource is controller-owned).+ */+export interface LlmHookCR {+ metadata?: { name?: string }+ spec?: {+ target?: {+ image?: {+ ref?: string+ port?: number+ envSecret?: string+ egressBindings?: Array<{ cidr?: string; toFQDN?: string; ports?: number[] }>+ security?: { addCapabilities?: string[] }+ }+ service?: { name?: string; namespace?: string; port?: number }+ remote?: { baseUrl?: string }+ }+ path?: string+ lifecyclePoints?: string[]+ order?: number+ failMode?: 'open' | 'closed'+ capabilities?: string[]+ }+ status?: { observedDigest?: string }+}++/**+ * Get an LlmHook CR by name from the llm-hooks namespace (spec §8.2). Returns+ * null on 404 so a dangling `Host.spec.guardrails.hooks` reference resolves to+ * "skip", not a hard failure.+ */+export async function getLlmHook(name: string): Promise<LlmHookCR | null> {+ try {+ const response = await customObjectsApi.getNamespacedCustomObject({+ group: GROUP,+ version: VERSION,+ namespace: config.llmHooksNamespace,+ plural: LLMHOOKS_PLURAL,+ name,+ })+ return response as LlmHookCR+ } catch (error) {+ if ((error as { response?: { statusCode?: number } }).response?.statusCode === 404) {+ console.warn(`[K8s] LlmHook not found: ${name} (ns=${config.llmHooksNamespace})`)+ return null+ }+ throw error+ }+}/*** Get a Host CRD by name.diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex 1e97b2687..0feff9ba1 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -50,7 +50,11 @@ import { WorkflowResultTool } from './core/tools/workflow'import type { Attachment } from './core/types'import { ConversationState } from './core/types'import { wireActivityEvents } from './eventWiring'-import { HostWatcher, getHost } from './k8sClient'+import {+ resolveGuardrailHookDescriptors,+ withResolvedHookDescriptors,+} from './guardrailHookResolver'+import { HostWatcher, getHost, getLlmHook } from './k8sClient'import { StatelessHeartbeat } from './lifecycle/statelessHeartbeat'import { TaskLifecycle } from './lifecycle/taskLifecycle'import { isTerminal } from './lifecycle/types'@@ -1259,7 +1263,17 @@ async function initializeAgent(): Promise<void> {agent.setApprovalConfig(approvalCfg)// Guardrails (spec §5/§6) — Host block, dev-env fallback. Absent = today.- agent.setGuardrailsConfig(currentHost?.spec.guardrails ?? config.guardrailsConfig)+ // Resolve installed-hook references (§8.2) into runtime descriptors so the+ // LLM lane actually calls the hook pods; dangling/invalid refs degrade to skip.+ const hostGuardrails = currentHost?.spec.guardrails ?? config.guardrailsConfig+ const resolvedHookDescriptors = await resolveGuardrailHookDescriptors(hostGuardrails, {+ getLlmHook,+ llmHooksNamespace: config.llmHooksNamespace,+ }).catch(err => {+ console.error('[Main] Guardrail hook resolution failed; running without installed hooks:', err)+ return []+ })+ agent.setGuardrailsConfig(withResolvedHookDescriptors(hostGuardrails, resolvedHookDescriptors))validateApprovalConfig(approvalCfg, knownNativeToolNames, config.nativeTool.httpAllowlist)console.log(`[Main] Approval system: ${config.enableApproval ? 'ENABLED' : 'DISABLED'} (policy: ${approvalCfg?.defaultPolicy || 'none/cli_only'})`