Skip to content

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

TypeScript

feat(guardrails): run installed llm-lane hooks end-to-end (phase 3)

Andy Pavia4c2f36977f14
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index df150f9ed..6353d567d 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.242",
+ "version": "0.1.243",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.242",
+ "version": "0.1.243",
"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 eec8a01de..03504a1f5 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.242",
+ "version": "0.1.243",
"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/adapters/__tests__/hookedLlmPort.test.ts b/mcp-host/src/core/adapters/__tests__/hookedLlmPort.test.ts
index 3e872a182..7ed46d97c 100644
--- a/mcp-host/src/core/adapters/__tests__/hookedLlmPort.test.ts
+++ b/mcp-host/src/core/adapters/__tests__/hookedLlmPort.test.ts
@@ -3,6 +3,7 @@
* passthrough on complete, and inert wrapping when no built-ins are configured.
*/
import { describe, expect, it, vi } from 'vitest'
+import { type FetchLike, type HookDescriptor, buildLlmLaneHooks } from '../../guardrails'
import type { LlmPort } from '../../interfaces'
import type { ToolCompletionRequest } from '../../types'
import { HookedLlmPort, maybeWrapHookedLlmPort } from '../hookedLlmPort'
@@ -45,6 +46,57 @@ describe('HookedLlmPort', () => {
})
})
+describe('installed hooks (end-to-end via HookedLlmPort)', () => {
+ const dscr = (over: Partial<HookDescriptor>): HookDescriptor => ({
+ id: 'h',
+ endpoint: 'http://svc',
+ path: '/',
+ lifecyclePoints: [],
+ capabilities: [],
+ failMode: 'closed',
+ order: 100,
+ ...over,
+ })
+
+ it('a moderate deny returns a filtered response WITHOUT calling the model', async () => {
+ const inner = fakePort()
+ const moderateDeny: FetchLike = async url => ({
+ status: url.endsWith('/v1/moderate') ? 422 : 200,
+ text: async () => '{"code":"blocked"}',
+ })
+ const hooks = buildLlmLaneHooks(
+ [dscr({ lifecyclePoints: ['moderate'], capabilities: ['may_deny'] })],
+ {
+ getAuthToken: () => '',
+ fetchImpl: moderateDeny,
+ }
+ )
+ const hooked = new HookedLlmPort(inner, r => r, hooks)
+ const res = await hooked.completeWithTools({ messages: [], tools: [] })
+ expect(res.finish_reason).toBe('content_filter')
+ expect(vi.mocked(inner.completeWithTools)).not.toHaveBeenCalled()
+ })
+
+ it('a pre_call rewrite reaches the inner port', async () => {
+ const inner = fakePort()
+ const preCallRewrite: FetchLike = async () => ({
+ status: 200,
+ text: async () =>
+ JSON.stringify({ action: 'continue', patch: { params: { temperature: 0.1 } } }),
+ })
+ const hooks = buildLlmLaneHooks(
+ [dscr({ lifecyclePoints: ['pre_call'], capabilities: ['may_rewrite'], failMode: 'open' })],
+ {
+ getAuthToken: () => '',
+ fetchImpl: preCallRewrite,
+ }
+ )
+ const hooked = new HookedLlmPort(inner, r => r, hooks)
+ await hooked.completeWithTools({ messages: [], tools: [] })
+ expect(inner.lastToolReq?.temperature).toBe(0.1)
+ })
+})
+
describe('maybeWrapHookedLlmPort', () => {
it('returns the port unchanged when no built-ins (inert)', () => {
const inner = fakePort()
diff --git a/mcp-host/src/core/adapters/hookedLlmPort.ts b/mcp-host/src/core/adapters/hookedLlmPort.ts
index 4ae26ca7e..edff3d8ba 100644
--- a/mcp-host/src/core/adapters/hookedLlmPort.ts
+++ b/mcp-host/src/core/adapters/hookedLlmPort.ts
@@ -3,27 +3,56 @@
* decorator wrapping the effective port **above failover** so contributors fire
* once per logical request, not per fallback attempt.
*
- * Phase 2 (increment 1): applies the first-party built-in request-shaping chain
- * (`prompt-shaping`) on the MAIN lane (`completeWithTools`). The aux/compaction
- * lane (`complete`) runs the REDUCED set — no guardrail/PII (spec §7.4) — which
- * in this increment is a passthrough. Moderation (concurrent with the call),
- * `on_error` recovery, and installed hooks are later increments / Phase 3.
+ * On the MAIN lane (`completeWithTools`):
+ * 1. apply the first-party built-in request-shaping chain (`prompt-shaping`,
+ * `token-trim`);
+ * 2. run installed `pre_call` hooks (each may rewrite the request or reject);
+ * 3. run installed `moderate` hooks;
+ * 4. aggregate (spec §3) — a `deny` returns a content-filtered response WITHOUT
+ * calling the model; otherwise dispatch the (possibly rewritten) request.
+ * The aux/compaction lane (`complete`) runs the REDUCED set — no guardrail/PII
+ * (spec §7.4) — a passthrough here.
+ *
+ * Response-capability enforcement (F4), system-prompt immutability (N4), and
+ * subtractive actions (N5) are enforced inside `RemoteLlmHook`. `post_call` /
+ * `on_error`, and the concurrent-moderation latency optimization (spec §7.1),
+ * are later increments.
*/
-import type { GuardrailsConfig } from '../guardrails'
+import { aggregateDecision } from '../guardrails'
+import type { Contributor, GuardrailsConfig } from '../guardrails'
import { type RequestShaper, buildLlmBuiltinChain } from '../guardrails/llm/builtinChain'
+import {
+ type LlmLaneHookDeps,
+ type LlmLaneHooks,
+ buildLlmLaneHooks,
+} from '../guardrails/llm/llmLaneHooks'
import type { LlmPort } from '../interfaces'
import type { TokenCounter } from '../tokenizer/tokenCounter'
-import type {
- CompletionRequest,
- CompletionResponse,
- ToolCompletionRequest,
- ToolCompletionResponse,
+import {
+ type CompletionRequest,
+ type CompletionResponse,
+ FinishReason,
+ type ToolCompletionRequest,
+ type ToolCompletionResponse,
} from '../types'
+const EMPTY_HOOKS: LlmLaneHooks = { preCall: [], moderate: [] }
+
+/** A safe content-filtered response returned in place of a denied model call (spec §7.1). */
+function filteredResponse(): ToolCompletionResponse {
+ return {
+ content: 'This request was blocked by a content guardrail policy.',
+ tool_calls: null,
+ usage: { input_tokens: 0, output_tokens: 0, total_tokens: 0 },
+ finish_reason: FinishReason.ContentFilter,
+ }
+}
+
export class HookedLlmPort implements LlmPort {
constructor(
private readonly inner: LlmPort,
- private readonly shapeMainLane: RequestShaper
+ private readonly shapeMainLane: RequestShaper,
+ private readonly hooks: LlmLaneHooks = EMPTY_HOOKS
) {}
modelName(): string {
@@ -38,27 +67,51 @@ export class HookedLlmPort implements LlmPort {
return counter
}
- /** Aux/compaction lane (spec §7.4): reduced set. Increment 1 = passthrough. */
+ /** Aux/compaction lane (spec §7.4): reduced set — passthrough. */
complete(request: CompletionRequest): Promise<CompletionResponse> {
return this.inner.complete(request)
}
- /** Main lane (spec §7): apply the built-in `pre` request shaping, then dispatch. */
- completeWithTools(request: ToolCompletionRequest): Promise<ToolCompletionResponse> {
- return this.inner.completeWithTools(this.shapeMainLane(request))
+ /** Main lane (spec §7): built-ins → installed pre_call/moderate → aggregate → dispatch. */
+ async completeWithTools(request: ToolCompletionRequest): Promise<ToolCompletionResponse> {
+ let req = this.shapeMainLane(request)
+ const contributions: Array<Contributor<ToolCompletionRequest, ToolCompletionResponse>> = []
+
+ for (const hook of this.hooks.preCall) {
+ const c = await hook.preCall(req)
+ if (c) {
+ contributions.push(c)
+ if (c.rewrite) req = c.rewrite // already system-role-stripped + capability-gated (N4/F4)
+ }
+ }
+ for (const hook of this.hooks.moderate) {
+ const c = await hook.moderate(req)
+ if (c) contributions.push(c)
+ }
+
+ if (aggregateDecision(contributions) === 'deny') {
+ return filteredResponse()
+ }
+ return this.inner.completeWithTools(req)
}
}
/**
* Wrap the effective (post-failover) port with the LLM-lane guardrails when any
- * built-ins are configured; otherwise return it unchanged (no-config
- * compatibility, spec §5 — no extra decorator layer when unused).
+ * built-ins OR installed hooks are configured; otherwise return it unchanged
+ * (no-config compatibility, spec §5 — no extra decorator layer when unused).
*/
export function maybeWrapHookedLlmPort(
port: LlmPort,
- config: GuardrailsConfig | undefined
+ config: GuardrailsConfig | undefined,
+ deps: Partial<LlmLaneHookDeps> = {}
): LlmPort {
- // No built-ins → no decorator layer (byte-identical to today).
- if (!config?.builtins || config.builtins.length === 0) return port
- return new HookedLlmPort(port, buildLlmBuiltinChain(config.builtins))
+ const hasBuiltins = !!config?.builtins && config.builtins.length > 0
+ const hooks = buildLlmLaneHooks(config?.hookDescriptors, {
+ getAuthToken: deps.getAuthToken ?? (() => ''),
+ fetchImpl: deps.fetchImpl,
+ })
+ const hasHooks = hooks.preCall.length > 0 || hooks.moderate.length > 0
+ if (!hasBuiltins && !hasHooks) return port
+ return new HookedLlmPort(port, buildLlmBuiltinChain(config?.builtins), hooks)
}
diff --git a/mcp-host/src/core/guardrails/config.ts b/mcp-host/src/core/guardrails/config.ts
index 9f3abd903..7bf1dcf06 100644
--- a/mcp-host/src/core/guardrails/config.ts
+++ b/mcp-host/src/core/guardrails/config.ts
@@ -8,6 +8,7 @@
*
* TODO(phase1): parse + validate (limits, predicate admission) — see spec §5/§6.1.
*/
+import type { HookDescriptor } from './hooks/types'
import type { Capability } from './types'
/** A single permission rule item (spec §6.1). Predicate shapes: spec §6.1. */
@@ -42,6 +43,13 @@ export interface GuardrailsConfig {
rules?: GuardrailRule[]
hooks?: Record<string, unknown>
builtins?: unknown[]
+ /**
+ * Resolved installed-hook descriptors (spec §8). In prod these come from the
+ * LlmHook CR watcher (by `hooks` id, §8.2); for dev/E2E an operator can supply
+ * them inline via `CLERUM_GUARDRAILS_CONFIG` to point at a hook server without
+ * the reconciler. Each descriptor's `lifecyclePoints` decides which lanes it runs on.
+ */
+ hookDescriptors?: HookDescriptor[]
minInstalledHookTrustLevel?: 'low' | 'mid' | 'high'
approvalPolicies?: string[]
capabilityCeiling?: Capability[]
diff --git a/mcp-host/src/core/guardrails/index.ts b/mcp-host/src/core/guardrails/index.ts
index 059eaf51a..c53272932 100644
--- a/mcp-host/src/core/guardrails/index.ts
+++ b/mcp-host/src/core/guardrails/index.ts
@@ -33,4 +33,6 @@ export { RemoteLlmHook } from './hooks/remoteLlmHook'
export type { HookDescriptor, HookFetcher, HookHttpResult, LifecyclePoint } from './hooks/types'
export { buildHookUrl, createHookFetcher } from './hooks/hookFetcher'
export type { FetchLike, HookFetcherDeps } from './hooks/hookFetcher'
+export { buildLlmLaneHooks } from './llm/llmLaneHooks'
+export type { LlmLaneHooks, LlmLaneHookDeps } from './llm/llmLaneHooks'
export { guardrailDecisionsTotal, guardrailBoundaryDurationMs } from './metrics'
diff --git a/mcp-host/src/core/guardrails/llm/llmLaneHooks.ts b/mcp-host/src/core/guardrails/llm/llmLaneHooks.ts
new file mode 100644
index 000000000..4bdc7a248
--- /dev/null
+++ b/mcp-host/src/core/guardrails/llm/llmLaneHooks.ts
@@ -0,0 +1,38 @@
+/**
+ * LLM-lane installed hooks (spec §7.3/§8) — resolve `HookDescriptor`s into
+ * `RemoteLlmHook`s grouped by lifecycle point, each with a concrete `/v1`
+ * fetcher. Ordered by `descriptor.order` (spec §5). The chain is
+ * built-ins → installed (§7.3), applied by `HookedLlmPort`.
+ */
+import { type FetchLike, createHookFetcher } from '../hooks/hookFetcher'
+import { RemoteLlmHook } from '../hooks/remoteLlmHook'
+import type { HookDescriptor } from '../hooks/types'
+
+export interface LlmLaneHooks {
+ preCall: RemoteLlmHook[]
+ moderate: RemoteLlmHook[]
+}
+
+export interface LlmLaneHookDeps {
+ getAuthToken: () => string
+ /** Injected for tests / a future SSRF-guarded remote transport. */
+ fetchImpl?: FetchLike
+}
+
+export function buildLlmLaneHooks(
+ descriptors: HookDescriptor[] | undefined,
+ deps: LlmLaneHookDeps
+): LlmLaneHooks {
+ const preCall: RemoteLlmHook[] = []
+ const moderate: RemoteLlmHook[] = []
+ const ordered = (descriptors ?? []).slice().sort((a, b) => a.order - b.order)
+ for (const d of ordered) {
+ const hook = new RemoteLlmHook(
+ d,
+ createHookFetcher({ getAuthToken: deps.getAuthToken, fetchImpl: deps.fetchImpl })
+ )
+ if (d.lifecyclePoints.includes('pre_call')) preCall.push(hook)
+ if (d.lifecyclePoints.includes('moderate')) moderate.push(hook)
+ }
+ return { preCall, moderate }
+}