Skip to content

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

TypeScript

feat(guardrails): add installed-hook /v1 response mapping with invariants (phase 3)

Andy Pavia419838965d18
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 15f46834e..8a35a59c2 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.240",
+ "version": "0.1.241",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.240",
+ "version": "0.1.241",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 0fd114fe5..af4bc1034 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.240",
+ "version": "0.1.241",
"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__/remoteLlmHook.test.ts b/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts
new file mode 100644
index 000000000..3aec04243
--- /dev/null
+++ b/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts
@@ -0,0 +1,150 @@
+/**
+ * RemoteLlmHook `/v1` response→contributor mapping (spec §8.1), focusing on the
+ * security invariants: response-capability enforcement (F4), system-prompt
+ * immutability (N4), subtractive actions (N5), and fail-posture (§8.6).
+ */
+import { describe, expect, it } from 'vitest'
+import type { ChatMessage, ToolCompletionRequest } from '../../../types'
+import { RemoteLlmHook } from '../remoteLlmHook'
+import type { HookDescriptor, HookFetcher, HookHttpResult } 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 fetcher =
+ (result: HookHttpResult): HookFetcher =>
+ async () =>
+ result
+const req = (messages: ChatMessage[] = []): ToolCompletionRequest => ({ messages, tools: [] })
+
+describe('pre_call', () => {
+ it('reject + may_deny → deny', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: ['may_deny'] }),
+ fetcher({ status: 200, body: { action: 'reject', code: 'pii' }, unavailable: false })
+ )
+ expect((await h.preCall(req()))?.decision).toBe('deny')
+ })
+
+ it('reject WITHOUT may_deny → downgraded to no_decision (F4)', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: [] }),
+ fetcher({ status: 200, body: { action: 'reject', code: 'pii' }, unavailable: false })
+ )
+ expect((await h.preCall(req()))?.decision).toBe('no_decision')
+ })
+
+ it('continue + patch + may_rewrite → rewrite (system-role messages stripped, N4)', async () => {
+ const patch = {
+ messages: [
+ { role: 'system', content: 'evil' },
+ { role: 'user', content: 'hi' },
+ ],
+ params: { temperature: 0.1 },
+ }
+ const h = new RemoteLlmHook(
+ desc({ capabilities: ['may_rewrite'] }),
+ fetcher({ status: 200, body: { action: 'continue', patch }, unavailable: false })
+ )
+ const c = await h.preCall(req())
+ expect(c?.rewrite?.messages.every(m => m.role !== 'system')).toBe(true)
+ expect(c?.rewrite?.messages).toHaveLength(1)
+ expect(c?.rewrite?.temperature).toBe(0.1)
+ })
+
+ it('continue + patch WITHOUT may_rewrite → patch dropped (F4)', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: [] }),
+ fetcher({
+ status: 200,
+ body: { action: 'continue', patch: { params: { temperature: 0.9 } } },
+ unavailable: false,
+ })
+ )
+ expect(await h.preCall(req())).toBeNull()
+ })
+})
+
+describe('moderate', () => {
+ it('200 → pass (no contribution)', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: ['may_deny'] }),
+ fetcher({ status: 200, body: {}, unavailable: false })
+ )
+ expect(await h.moderate(req())).toBeNull()
+ })
+ it('4xx + may_deny → deny', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: ['may_deny'] }),
+ fetcher({ status: 422, body: { code: 'blocked' }, unavailable: false })
+ )
+ expect((await h.moderate(req()))?.decision).toBe('deny')
+ })
+})
+
+describe('on_error', () => {
+ it('recover + may_substitute_result → text-only substitute (N5: tool_calls dropped)', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: ['may_substitute_result'] }),
+ fetcher({
+ status: 200,
+ body: {
+ action: 'recover',
+ response: { content: 'safe', tool_calls: [{ id: 'x', name: 'rm', arguments: {} }] },
+ },
+ unavailable: false,
+ })
+ )
+ const c = await h.onError(req(), new Error('boom'))
+ expect(c?.substitute?.content).toBe('safe')
+ expect(c?.substitute?.tool_calls).toBeNull() // injected tool_calls are dropped
+ })
+ it('recover WITHOUT may_substitute_result → no recovery', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: [] }),
+ fetcher({
+ status: 200,
+ body: { action: 'recover', response: { content: 'x' } },
+ unavailable: false,
+ })
+ )
+ expect(await h.onError(req(), new Error('boom'))).toBeNull()
+ })
+})
+
+describe('fail-posture (§8.6)', () => {
+ it('unavailable + failMode closed + may_deny → deny hook_unavailable', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: ['may_deny'], failMode: 'closed' }),
+ fetcher({ status: 0, body: undefined, unavailable: true })
+ )
+ const c = await h.moderate(req())
+ expect(c?.decision).toBe('deny')
+ expect(c?.reasonCode).toBe('hook_unavailable')
+ })
+ it('unavailable + failMode open → no contribution', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: ['may_deny'], failMode: 'open' }),
+ fetcher({ status: 0, body: undefined, unavailable: true })
+ )
+ expect(await h.moderate(req())).toBeNull()
+ })
+})
+
+describe('lifecycle scoping', () => {
+ it('a point the hook does not subscribe to → null', async () => {
+ const h = new RemoteLlmHook(
+ desc({ lifecyclePoints: ['moderate'] }),
+ fetcher({ status: 200, body: { action: 'reject' }, unavailable: false })
+ )
+ expect(await h.preCall(req())).toBeNull()
+ })
+})
diff --git a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts
new file mode 100644
index 000000000..0e03489d7
--- /dev/null
+++ b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts
@@ -0,0 +1,163 @@
+/**
+ * RemoteLlmHook (spec §8) — calls an installed hook over the `/v1` protocol and
+ * maps its response to an LLM-lane `Contributor`, enforcing the security
+ * invariants on the RESPONSE (the hook is an untrusted out-of-process container):
+ *
+ * - Response-capability enforcement (F4, §8.1): a `reject` from a hook without
+ * `may_deny` downgrades to `no_decision`; a `patch` without `may_rewrite` is
+ * dropped; a `recover` without `may_substitute_result` is dropped.
+ * - System prompt is immutable to installed hooks (N4, §8.1): a `pre_call`
+ * patch may edit only NON-system messages + params — system-role messages in
+ * the patch are dropped.
+ * - Actions come only from the model (N5, §8.1): an `on_error recover` is
+ * TEXT-ONLY (no tool_calls); a `post_call` transform may drop tool_calls but
+ * never introduce them.
+ * - Fail-posture (§8.6): an unavailable hook degrades per its `failMode`
+ * (closed → deny `hook_unavailable`; open → no contribution).
+ *
+ * Phase 3 increment 1: pre_call / moderate / on_error mapping + invariants,
+ * fetcher-injected. Content projection (§8.4) and the concrete fetcher land next.
+ */
+import { FinishReason } from '../../types'
+import type { ChatMessage, ToolCompletionRequest, ToolCompletionResponse } from '../../types'
+import type { Capability, Contributor } from '../types'
+import type { HookDescriptor, HookFetcher, LifecyclePoint } from './types'
+
+type LlmContributor = Contributor<ToolCompletionRequest, ToolCompletionResponse>
+
+function isRecord(v: unknown): v is Record<string, unknown> {
+ return !!v && typeof v === 'object'
+}
+
+/** Strip system-role messages from a hook's messages patch (N4 — system prompt is first-party). */
+function stripSystemRole(messages: ChatMessage[]): ChatMessage[] {
+ return messages.filter(m => m.role !== 'system')
+}
+
+export class RemoteLlmHook {
+ constructor(
+ private readonly descriptor: HookDescriptor,
+ private readonly fetch: HookFetcher
+ ) {}
+
+ private has(cap: Capability): boolean {
+ return this.descriptor.capabilities.includes(cap)
+ }
+
+ private handles(point: LifecyclePoint): boolean {
+ return this.descriptor.lifecyclePoints.includes(point)
+ }
+
+ /** Fail-posture (§8.6): closed → deny `hook_unavailable`; open → no contribution. */
+ private onUnavailable(): LlmContributor | null {
+ if (this.descriptor.failMode === 'closed' && this.has('may_deny')) {
+ return this.contribution('deny', 'hook_unavailable')
+ }
+ // Fail-open, or a non-deny-authoritative hook: no contribution (advisory).
+ return null
+ }
+
+ private contribution(
+ decision: LlmContributor['decision'],
+ reasonCode: string,
+ extra: Partial<LlmContributor> = {}
+ ): LlmContributor {
+ return {
+ phase: extra.phase ?? 'pre',
+ source: 'hook',
+ sourceId: this.descriptor.id,
+ decision,
+ reasonCode,
+ ...extra,
+ }
+ }
+
+ /** `pre_call` (spec §8.1): reject → deny (gated), continue+patch → rewrite (gated), else allow. */
+ async preCall(request: ToolCompletionRequest): Promise<LlmContributor | null> {
+ if (!this.handles('pre_call')) return null
+ const res = await this.fetch({ point: 'pre_call', descriptor: this.descriptor, body: request })
+ if (res.unavailable) return this.onUnavailable()
+
+ const body = isRecord(res.body) ? res.body : {}
+ if (body.action === 'reject') {
+ // F4: only honored with may_deny; otherwise downgrade to no_decision.
+ const decision = this.has('may_deny') ? 'deny' : 'no_decision'
+ return this.contribution(decision, String(body.code ?? 'content_filtered'), {
+ audit: { modelReason: typeof body.message === 'string' ? body.message : undefined },
+ })
+ }
+ // action === 'continue'
+ const patch = isRecord(body.patch) ? body.patch : undefined
+ if (patch && this.has('may_rewrite')) {
+ const rewrite = this.applyPatch(request, patch)
+ return this.contribution('allow', 'shaped', { rewrite })
+ }
+ // Continue with no honored patch → no contribution (allow).
+ return null
+ }
+
+ /** Apply a `pre_call` patch: NON-system messages + params only (N4). */
+ private applyPatch(
+ request: ToolCompletionRequest,
+ patch: Record<string, unknown>
+ ): ToolCompletionRequest {
+ const next: ToolCompletionRequest = { ...request }
+ if (Array.isArray(patch.messages)) {
+ next.messages = stripSystemRole(patch.messages as ChatMessage[])
+ }
+ const params = isRecord(patch.params) ? patch.params : undefined
+ if (params) {
+ if (typeof params.temperature === 'number') next.temperature = params.temperature
+ if (typeof params.max_tokens === 'number') next.max_tokens = params.max_tokens
+ if (
+ params.tool_choice === 'auto' ||
+ params.tool_choice === 'none' ||
+ params.tool_choice === 'required'
+ ) {
+ next.tool_choice = params.tool_choice
+ }
+ }
+ return next
+ }
+
+ /** `moderate` (spec §8.1): 2xx = pass (no contribution); 4xx = deny (gated). */
+ async moderate(request: ToolCompletionRequest): Promise<LlmContributor | null> {
+ if (!this.handles('moderate')) return null
+ const res = await this.fetch({ point: 'moderate', descriptor: this.descriptor, body: request })
+ if (res.unavailable) return this.onUnavailable()
+ if (res.status >= 200 && res.status < 300) return null // pass
+
+ const body = isRecord(res.body) ? res.body : {}
+ const decision = this.has('may_deny') ? 'deny' : 'no_decision'
+ return this.contribution(decision, String(body.code ?? 'moderation_blocked'), {
+ audit: { modelReason: typeof body.message === 'string' ? body.message : undefined },
+ })
+ }
+
+ /**
+ * `on_error` (spec §8.1): `recover` → a TEXT-ONLY substitute (N5 — no tool_calls),
+ * gated by may_substitute_result; otherwise no recovery (the error surfaces).
+ */
+ async onError(request: ToolCompletionRequest, error: unknown): Promise<LlmContributor | null> {
+ if (!this.handles('on_error')) return null
+ const res = await this.fetch({
+ point: 'on_error',
+ descriptor: this.descriptor,
+ body: { request, error },
+ })
+ if (res.unavailable) return null // can't recover a failed call if the recovery hook is also down.
+
+ const body = isRecord(res.body) ? res.body : {}
+ if (body.action !== 'recover' || !this.has('may_substitute_result')) return null
+
+ const resp = isRecord(body.response) ? body.response : {}
+ // N5: recovery is text-only — a substitute never introduces tool_calls.
+ const substitute: ToolCompletionResponse = {
+ content: typeof resp.content === 'string' ? resp.content : '',
+ tool_calls: null,
+ usage: { input_tokens: 0, output_tokens: 0, total_tokens: 0 },
+ finish_reason: FinishReason.Stop,
+ }
+ return this.contribution('allow', 'recovered', { phase: 'post', substitute })
+ }
+}
diff --git a/mcp-host/src/core/guardrails/hooks/types.ts b/mcp-host/src/core/guardrails/hooks/types.ts
new file mode 100644
index 000000000..15fa7b58f
--- /dev/null
+++ b/mcp-host/src/core/guardrails/hooks/types.ts
@@ -0,0 +1,43 @@
+/**
+ * Installed-hook delivery types (spec §8) — Phase 3.
+ *
+ * A `RemoteLlmHook` calls an installed hook over the `/v1` protocol and maps its
+ * response to a lane `Contributor`, enforcing the response-capability + action
+ * invariants (spec §8.1). The HTTP transport is injected (`HookFetcher`) so the
+ * mapping is testable without real networking; the concrete fetcher (in-cluster
+ * fetch for image/service, SSRF-guarded egress for remote) is a later increment.
+ */
+import type { Capability } from '../types'
+
+/** The four `/v1` lifecycle endpoints (spec §8.1). */
+export type LifecyclePoint = 'pre_call' | 'moderate' | 'post_call' | 'on_error'
+
+/** A resolved installed hook: its endpoint + admin-granted grants (from the LlmHook CR + Host block). */
+export interface HookDescriptor {
+ /** LlmHook CR name (spec §8.2 hook resolution). */
+ id: string
+ /** Base endpoint (image/service Service URL, or a remote https:// URL). */
+ endpoint: string
+ /** API path on the endpoint; calls go to `{endpoint}{path}/v1/{point}` (spec §8.1/§8.2). */
+ path: string
+ lifecyclePoints: readonly LifecyclePoint[]
+ /** 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). */
+ failMode: 'open' | 'closed'
+ order: number
+}
+
+/** Result of one `/v1` HTTP call. `unavailable` = 5xx / timeout / connection error / malformed body (spec §8.1). */
+export interface HookHttpResult {
+ status: number
+ body: unknown
+ unavailable: boolean
+}
+
+/** Injected transport: POST the redacted body to `{endpoint}{path}/v1/{point}` and return the parsed result. */
+export type HookFetcher = (args: {
+ point: LifecyclePoint
+ descriptor: HookDescriptor
+ body: unknown
+}) => Promise<HookHttpResult>
diff --git a/mcp-host/src/core/guardrails/index.ts b/mcp-host/src/core/guardrails/index.ts
index aaac41702..72f5a5fad 100644
--- a/mcp-host/src/core/guardrails/index.ts
+++ b/mcp-host/src/core/guardrails/index.ts
@@ -29,4 +29,6 @@ export { applyPromptShaping } from './llm/builtins/promptShaping'
export type { PromptShapingConfig } from './llm/builtins/promptShaping'
export { applyTokenTrim } from './llm/builtins/tokenTrim'
export type { TokenTrimConfig } from './llm/builtins/tokenTrim'
+export { RemoteLlmHook } from './hooks/remoteLlmHook'
+export type { HookDescriptor, HookFetcher, HookHttpResult, LifecyclePoint } from './hooks/types'
export { guardrailDecisionsTotal, guardrailBoundaryDurationMs } from './metrics'