Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(guardrails): projectForHook content projection for /v1 hooks (§8.4)
Andy Pavia27e89978489f
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex faa75624d..3c51202a0 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.254",+ "version": "0.1.255","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.254",+ "version": "0.1.255","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 98be58cfb..1eda4c1bd 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.254",+ "version": "0.1.255","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/core/guardrails/hooks/__tests__/hookProjection.test.ts b/mcp-host/src/core/guardrails/hooks/__tests__/hookProjection.test.tsnew file mode 100644index 000000000..2d65ba2eb--- /dev/null+++ b/mcp-host/src/core/guardrails/hooks/__tests__/hookProjection.test.ts@@ -0,0 +1,131 @@+/**+ * `projectForHook` content projection (spec §8.4/§8.7): scope-not-scrub, the+ * system prompt is never exposed, and `pre_call` splits metadata vs content.+ */+import { describe, expect, it } from 'vitest'+import {+ type ChatMessage,+ FinishReason,+ type ToolCompletionRequest,+ type ToolCompletionResponse,+} from '../../../types'+import { projectForHook } from '../hookProjection'+import type { HookDescriptor } from '../types'++const desc = (over: Partial<HookDescriptor> = {}): HookDescriptor => ({+ id: 'h',+ endpoint: 'http://svc',+ path: '/',+ lifecyclePoints: ['pre_call', 'moderate', 'post_call', 'on_error'],+ capabilities: [],+ failMode: 'closed',+ order: 100,+ ...over,+})++const messages: ChatMessage[] = [+ { role: 'system', content: 'PROPRIETARY SYSTEM PROMPT' },+ { role: 'user', content: 'hello world' },+]++const request = (): ToolCompletionRequest =>+ ({+ messages,+ tools: [{ name: 'search' }] as unknown as ToolCompletionRequest['tools'],+ temperature: 0.4,+ max_tokens: 256,+ tool_choice: 'auto',+ signal: new AbortController().signal,+ usageContext: {+ some: 'internal-attribution',+ } as unknown as ToolCompletionRequest['usageContext'],+ systemPromptParts: {+ parts: ['secret'],+ } as unknown as ToolCompletionRequest['systemPromptParts'],+ }) as ToolCompletionRequest++const response = (): ToolCompletionResponse => ({+ content: 'answer',+ tool_calls: null,+ usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },+ finish_reason: FinishReason.Stop,+})++describe('pre_call projection', () => {+ it('metadata flavor → NO messages, keeps params + tool schemas', () => {+ const body = projectForHook(desc({ contentAccess: 'metadata' }), 'pre_call', {+ request: request(),+ }) as Record<string, unknown>+ expect(body.messages).toBeUndefined()+ expect(body.temperature).toBe(0.4)+ expect(body.max_tokens).toBe(256)+ expect(body.tool_choice).toBe('auto')+ expect(body.tools).toBeDefined()+ })++ it('content flavor → includes NON-system messages', () => {+ const body = projectForHook(desc({ contentAccess: 'content' }), 'pre_call', {+ request: request(),+ }) as Record<string, unknown>+ const msgs = body.messages as ChatMessage[]+ expect(msgs).toHaveLength(1)+ expect(msgs[0].role).toBe('user')+ })++ it('absent contentAccess defaults to content (messages included)', () => {+ const body = projectForHook(desc(), 'pre_call', { request: request() }) as Record<+ string,+ unknown+ >+ expect((body.messages as ChatMessage[]).length).toBe(1)+ })+})++describe('system prompt is never exposed (any point, any flavor)', () => {+ for (const contentAccess of ['metadata', 'content', undefined] as const) {+ it(`pre_call (${contentAccess ?? 'absent'}) drops system-role + systemPromptParts + internal fields`, () => {+ const body = projectForHook(desc({ contentAccess }), 'pre_call', {+ request: request(),+ }) as Record<string, unknown>+ expect(body.systemPromptParts).toBeUndefined()+ expect(body.signal).toBeUndefined()+ expect(body.usageContext).toBeUndefined()+ const msgs = (body.messages as ChatMessage[] | undefined) ?? []+ expect(msgs.some(m => m.role === 'system')).toBe(false)+ })+ }++ it('moderate strips the system prompt but keeps user content', () => {+ const body = projectForHook(desc(), 'moderate', { request: request() }) as Record<+ string,+ unknown+ >+ expect(body.systemPromptParts).toBeUndefined()+ const msgs = body.messages as ChatMessage[]+ expect(msgs.every(m => m.role !== 'system')).toBe(true)+ expect(msgs[0].content).toBe('hello world')+ })+})++describe('post_call / on_error projection', () => {+ it('post_call sends only response{content,tool_calls,finish_reason} + usage', () => {+ const body = projectForHook(desc(), 'post_call', { response: response() }) as Record<+ string,+ unknown+ >+ expect(Object.keys(body).sort()).toEqual(['response', 'usage'])+ const r = body.response as Record<string, unknown>+ expect(Object.keys(r).sort()).toEqual(['content', 'finish_reason', 'tool_calls'])+ })++ it('on_error sends the projected request (no system) + the error', () => {+ const body = projectForHook(desc(), 'on_error', {+ request: request(),+ error: { code: 'boom' },+ }) as Record<string, unknown>+ expect(body.error).toEqual({ code: 'boom' })+ const req = body.request as Record<string, unknown>+ expect(req.systemPromptParts).toBeUndefined()+ expect((req.messages as ChatMessage[]).every(m => m.role !== 'system')).toBe(true)+ })+})diff --git a/mcp-host/src/core/guardrails/hooks/hookProjection.ts b/mcp-host/src/core/guardrails/hooks/hookProjection.tsnew file mode 100644index 000000000..dc5e6be35--- /dev/null+++ b/mcp-host/src/core/guardrails/hooks/hookProjection.ts@@ -0,0 +1,91 @@+/**+ * `projectForHook` — the content projection for installed `/v1` hooks (spec §8.4).+ *+ * An installed hook is untrusted third-party code, so it NEVER receives the raw+ * `ToolCompletionRequest`/response. This builds the per-point request body from a+ * projection with exactly two jobs:+ *+ * - SCOPE, don't scrub. It selects which FIELDS a hook receives; it never masks+ * values inside a field it does send — a PII/moderation hook still sees the raw+ * content it exists to inspect (redaction stays a hook's `post_call` OUTPUT+ * transform, never an input filter).+ * - Deny the first-party system prompt in EVERY projection: system-role messages+ * are stripped and `systemPromptParts` is never forwarded, regardless of+ * `contentAccess` (§8.1 — the system prompt is immutable to, and invisible to,+ * installed hooks). Internal-only fields (`signal`, `usageContext`) are dropped+ * too — they are not part of the wire contract and must not reach a hook.+ *+ * Content need is per point: `moderate`/`post_call`/`on_error` are inherently+ * content-bearing; `pre_call` receives messages only when the hook is NOT a+ * `metadata`-only shaper (§8.7). A `metadata` `pre_call` hook gets model + params ++ * tool schemas but no message bodies, which is what lets it egress at low trust.+ */+import type { ChatMessage, ToolCompletionRequest, ToolCompletionResponse } from '../../types'+import type { HookDescriptor, LifecyclePoint } from './types'++/** Fields never forwarded to a hook: the system prompt (both forms) + internal-only wiring. */+const REQUEST_FIELDS_NEVER_SENT = [+ 'systemPromptParts',+ 'signal',+ 'usageContext',+ 'messages',+] as const++function stripSystemRole(messages: ChatMessage[] | undefined): ChatMessage[] {+ return (messages ?? []).filter(m => m.role !== 'system')+}++/**+ * Project a request: always drop the system prompt + internal fields; include the+ * non-system messages only when `includeMessages` (the content flavor). Keeps+ * params + tool schemas (`tools`, `temperature`, `max_tokens`, `tool_choice`).+ */+function projectRequest(+ request: ToolCompletionRequest,+ includeMessages: boolean+): Record<string, unknown> {+ const projected: Record<string, unknown> = { ...(request as unknown as Record<string, unknown>) }+ for (const f of REQUEST_FIELDS_NEVER_SENT) delete projected[f]+ if (includeMessages) projected.messages = stripSystemRole(request.messages)+ return projected+}++/** A `pre_call` hook receives messages unless it explicitly declared `metadata`-only (§8.7). */+export function preCallIncludesContent(descriptor: HookDescriptor): boolean {+ return descriptor.contentAccess !== 'metadata'+}++/** Build the `/v1/{point}` request body for a hook, per the §8.4 projection contract. */+export function projectForHook(+ descriptor: HookDescriptor,+ point: LifecyclePoint,+ ctx: {+ request?: ToolCompletionRequest+ response?: ToolCompletionResponse+ error?: unknown+ }+): unknown {+ switch (point) {+ case 'pre_call':+ return projectRequest(+ ctx.request as ToolCompletionRequest,+ preCallIncludesContent(descriptor)+ )+ case 'moderate':+ return projectRequest(ctx.request as ToolCompletionRequest, true)+ case 'post_call': {+ const r = ctx.response as ToolCompletionResponse+ return {+ response: { content: r.content, tool_calls: r.tool_calls, finish_reason: r.finish_reason },+ usage: r.usage,+ }+ }+ case 'on_error':+ return {+ request: projectRequest(ctx.request as ToolCompletionRequest, true),+ error: ctx.error,+ }+ default:+ return {}+ }+}diff --git a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.tsindex a083b481b..5324fc5e3 100644--- a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts+++ b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts@@ -27,6 +27,7 @@ import type {} from '../../types'import type { Capability, Contributor } from '../types'import { type HookBreakerRegistry, defaultBreakerRegistry } from './hookBreaker'+import { projectForHook } from './hookProjection'import type { HookDescriptor, HookFetcher, HookHttpResult, LifecyclePoint } from './types'type LlmContributor = Contributor<ToolCompletionRequest, ToolCompletionResponse>@@ -175,7 +176,7 @@ export class RemoteLlmHook {const res = await this.fetchGuarded({point: 'pre_call',descriptor: this.descriptor,- body: request,+ body: projectForHook(this.descriptor, 'pre_call', { request }),})// §8.1: non-200 or unavailable → fail-mode (never a silent allow).if (res.unavailable || res.status !== 200) return this.onUnavailable()@@ -229,7 +230,7 @@ export class RemoteLlmHook {const res = await this.fetchGuarded({point: 'moderate',descriptor: this.descriptor,- body: request,+ body: projectForHook(this.descriptor, 'moderate', { request }),})if (res.unavailable) return this.onUnavailable()if (res.status >= 200 && res.status < 300) return null // pass@@ -256,14 +257,7 @@ export class RemoteLlmHook {const res = await this.fetchGuarded({point: 'post_call',descriptor: this.descriptor,- body: {- response: {- content: response.content,- tool_calls: response.tool_calls,- finish_reason: response.finish_reason,- },- usage: response.usage,- },+ body: projectForHook(this.descriptor, 'post_call', { response }),})// §8.6: a fail-closed redactor that can't run must NOT leak the un-redacted body.if (res.unavailable || res.status !== 200) {@@ -310,7 +304,7 @@ export class RemoteLlmHook {const res = await this.fetchGuarded({point: 'on_error',descriptor: this.descriptor,- body: { request, error },+ body: projectForHook(this.descriptor, 'on_error', { request, error }),})// Recovery only on a proper 200 `recover`; anything else = no recovery (error surfaces).if (res.unavailable || res.status !== 200) return nulldiff --git a/mcp-host/src/core/guardrails/hooks/types.ts b/mcp-host/src/core/guardrails/hooks/types.tsindex c63a4560e..8f5e51aa1 100644--- a/mcp-host/src/core/guardrails/hooks/types.ts+++ b/mcp-host/src/core/guardrails/hooks/types.ts@@ -27,6 +27,14 @@ export interface HookDescriptor {/** API path on the endpoint; calls go to `{endpoint}{path}/v1/{point}` (spec §8.1/§8.2). */path: stringlifecyclePoints: readonly LifecyclePoint[]+ /**+ * Content projection this hook receives (spec §8.4/§8.7). `content` = the+ * projected non-system message/response bodies; `metadata` = model+params+tool+ * schemas only, no bodies. `moderate`/`post_call`/`on_error` are inherently+ * content-bearing; only a `pre_call`-only hook is `metadata`. Absent ⇒ inferred+ * (a `pre_call` hook receives messages unless it explicitly declared `metadata`).+ */+ contentAccess?: 'metadata' | 'content'/** Admin-granted capabilities (spec §4.3/§5); enforced on the RESPONSE (§8.1). */capabilities: readonly Capability[]/** Fail-posture when the hook is unavailable (spec §8.6). */diff --git a/mcp-host/src/guardrailHookResolver.ts b/mcp-host/src/guardrailHookResolver.tsindex e4e98006a..79db913e5 100644--- a/mcp-host/src/guardrailHookResolver.ts+++ b/mcp-host/src/guardrailHookResolver.ts@@ -154,6 +154,14 @@ export async function resolveGuardrailHookDescriptors()const path = cr.spec?.path ?? '/'const failMode: 'open' | 'closed' = cr.spec?.failMode === 'open' ? 'open' : 'closed'+ // Content projection selector (§8.4/§8.7). Only an explicit `metadata` makes a+ // pre_call hook content-free; anything else (incl. absent) receives content.+ const contentAccess: 'metadata' | 'content' | undefined =+ cr.spec?.contentAccess === 'metadata'+ ? 'metadata'+ : cr.spec?.contentAccess === 'content'+ ? 'content'+ : undefinedconst order = typeof cr.spec?.order === 'number' ? cr.spec.order : 100// §8.6 circuit-breaker policy (CRD defaults: strict / 5 / 30000). `strict`@@ -201,6 +209,7 @@ export async function resolveGuardrailHookDescriptors(onUnavailable,order,external,+ ...(contentAccess ? { contentAccess } : {}),...(quarantined ? { quarantined: true } : {}),})console.log(diff --git a/mcp-host/src/k8sClient.ts b/mcp-host/src/k8sClient.tsindex 0a49afd4a..280e140b0 100644--- a/mcp-host/src/k8sClient.ts+++ b/mcp-host/src/k8sClient.ts@@ -38,6 +38,7 @@ export interface LlmHookCR {}path?: stringlifecyclePoints?: string[]+ contentAccess?: 'metadata' | 'content'order?: numberfailMode?: 'open' | 'closed'onUnavailable?: {