Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(guardrails): wire llm-lane post_call + on_error installed hooks
Andy Pavia28d584167db6
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex ef637436a..be772b741 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.244",+ "version": "0.1.245","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.244",+ "version": "0.1.245","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 579114d46..96ac29d9f 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.244",+ "version": "0.1.245","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.tsindex 7ed46d97c..e17643847 100644--- a/mcp-host/src/core/adapters/__tests__/hookedLlmPort.test.ts+++ b/mcp-host/src/core/adapters/__tests__/hookedLlmPort.test.ts@@ -95,6 +95,57 @@ describe('installed hooks (end-to-end via HookedLlmPort)', () => {await hooked.completeWithTools({ messages: [], tools: [] })expect(inner.lastToolReq?.temperature).toBe(0.1)})++ it('a post_call hook redacts the model result', async () => {+ const inner = fakePort()+ const redact: FetchLike = async url => ({+ status: 200,+ text: async () =>+ url.endsWith('/v1/post_call') ? '{"response":{"content":"[redacted]"}}' : '{}',+ })+ const hooks = buildLlmLaneHooks(+ [dscr({ lifecyclePoints: ['post_call'], capabilities: ['may_substitute_result'] })],+ { getAuthToken: () => '', fetchImpl: redact }+ )+ const hooked = new HookedLlmPort(inner, r => r, hooks)+ const res = await hooked.completeWithTools({ messages: [], tools: [] })+ expect(res.content).toBe('[redacted]') // inner returned "main"+ })++ it('an on_error recover substitutes a safe result when the model call throws', async () => {+ const inner = fakePort()+ inner.completeWithTools = vi.fn(async () => {+ throw new Error('upstream 500')+ })+ const recover: FetchLike = async url => ({+ status: 200,+ text: async () =>+ url.endsWith('/v1/on_error') ? '{"action":"recover","response":{"content":"safe"}}' : '{}',+ })+ const hooks = buildLlmLaneHooks(+ [dscr({ lifecyclePoints: ['on_error'], capabilities: ['may_substitute_result'] })],+ { getAuthToken: () => '', fetchImpl: recover }+ )+ const hooked = new HookedLlmPort(inner, r => r, hooks)+ const res = await hooked.completeWithTools({ messages: [], tools: [] })+ expect(res.content).toBe('safe')+ expect(res.tool_calls).toBeNull()+ })++ it('the model error surfaces when no on_error hook recovers', async () => {+ const inner = fakePort()+ inner.completeWithTools = vi.fn(async () => {+ throw new Error('upstream 500')+ })+ const hooked = new HookedLlmPort(+ inner,+ r => r,+ buildLlmLaneHooks([], { getAuthToken: () => '' })+ )+ await expect(hooked.completeWithTools({ messages: [], tools: [] })).rejects.toThrow(+ 'upstream 500'+ )+ })})describe('maybeWrapHookedLlmPort', () => {diff --git a/mcp-host/src/core/adapters/hookedLlmPort.ts b/mcp-host/src/core/adapters/hookedLlmPort.tsindex edff3d8ba..f75978d70 100644--- a/mcp-host/src/core/adapters/hookedLlmPort.ts+++ b/mcp-host/src/core/adapters/hookedLlmPort.ts@@ -9,14 +9,17 @@* 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.+ * calling the model; otherwise dispatch the (possibly rewritten) request;+ * 5. if the model call throws, run installed `on_error` hooks — a gated hook may+ * `substitute` a safe text-only result (else the error surfaces);+ * 6. run installed `post_call` hooks over the result — each may redact content or+ * drop tool_calls (never add them, N5), chained in `order`.* 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.+ * subtractive actions (N5) are enforced inside `RemoteLlmHook`. The+ * concurrent-moderation latency optimization (spec §7.1) is a later increment.*/import { aggregateDecision } from '../guardrails'import type { Contributor, GuardrailsConfig } from '../guardrails'@@ -36,7 +39,7 @@ import {type ToolCompletionResponse,} from '../types'-const EMPTY_HOOKS: LlmLaneHooks = { preCall: [], moderate: [] }+const EMPTY_HOOKS: LlmLaneHooks = { preCall: [], moderate: [], postCall: [], onError: [] }/** A safe content-filtered response returned in place of a denied model call (spec §7.1). */function filteredResponse(): ToolCompletionResponse {@@ -92,7 +95,26 @@ export class HookedLlmPort implements LlmPort {if (aggregateDecision(contributions) === 'deny') {return filteredResponse()}- return this.inner.completeWithTools(req)++ let response: ToolCompletionResponse+ try {+ response = await this.inner.completeWithTools(req)+ } catch (err) {+ // on_error (spec §8.1): a gated hook may substitute a safe text-only result;+ // first substitute wins. No hook recovers → the error surfaces unchanged.+ for (const hook of this.hooks.onError) {+ const c = await hook.onError(req, err)+ if (c?.substitute) return c.substitute+ }+ throw err+ }++ // post_call (spec §8.1): redact/subtract over the result, chained in `order`.+ for (const hook of this.hooks.postCall) {+ const c = await hook.postCall(req, response)+ if (c?.substitute) response = c.substitute+ }+ return response}}@@ -111,7 +133,11 @@ export function maybeWrapHookedLlmPort(getAuthToken: deps.getAuthToken ?? (() => ''),fetchImpl: deps.fetchImpl,})- const hasHooks = hooks.preCall.length > 0 || hooks.moderate.length > 0+ const hasHooks =+ hooks.preCall.length > 0 ||+ hooks.moderate.length > 0 ||+ hooks.postCall.length > 0 ||+ hooks.onError.length > 0if (!hasBuiltins && !hasHooks) return portreturn new HookedLlmPort(port, buildLlmBuiltinChain(config?.builtins), hooks)}diff --git a/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts b/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.tsindex f05b2609a..5d477724f 100644--- a/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts+++ b/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts@@ -4,7 +4,12 @@* immutability (N4), subtractive actions (N5), and fail-posture (§8.6).*/import { describe, expect, it } from 'vitest'-import type { ChatMessage, ToolCompletionRequest } from '../../../types'+import {+ type ChatMessage,+ FinishReason,+ type ToolCompletionRequest,+ type ToolCompletionResponse,+} from '../../../types'import { RemoteLlmHook } from '../remoteLlmHook'import type { HookDescriptor, HookFetcher, HookHttpResult } from '../types'@@ -107,6 +112,96 @@ describe('moderate', () => {})})+describe('post_call', () => {+ const resp = (over: Partial<ToolCompletionResponse> = {}): ToolCompletionResponse => ({+ content: 'raw',+ tool_calls: [{ id: 'a', name: 'read', arguments: { path: '/x' } }],+ usage: { input_tokens: 5, output_tokens: 7, total_tokens: 12 },+ finish_reason: FinishReason.Stop,+ ...over,+ })++ it('redacts content + may_substitute_result → substitute (usage/finish preserved)', async () => {+ const h = new RemoteLlmHook(+ desc({ capabilities: ['may_substitute_result'] }),+ fetcher({ status: 200, body: { response: { content: '[redacted]' } }, unavailable: false })+ )+ const c = await h.postCall(req(), resp())+ expect(c?.substitute?.content).toBe('[redacted]')+ // tool_calls key absent from patch → original preserved.+ expect(c?.substitute?.tool_calls).toHaveLength(1)+ expect(c?.substitute?.usage.total_tokens).toBe(12)+ expect(c?.substitute?.finish_reason).toBe(FinishReason.Stop)+ })++ it('WITHOUT may_substitute_result → no transform (F4)', async () => {+ const h = new RemoteLlmHook(+ desc({ capabilities: [] }),+ fetcher({ status: 200, body: { response: { content: 'x' } }, unavailable: false })+ )+ expect(await h.postCall(req(), resp())).toBeNull()+ })++ it('may drop a tool_call (empty patch array) but the result keeps only model-emitted calls', async () => {+ const h = new RemoteLlmHook(+ desc({ capabilities: ['may_substitute_result'] }),+ fetcher({ status: 200, body: { response: { tool_calls: [] } }, unavailable: false })+ )+ const c = await h.postCall(req(), resp())+ expect(c?.substitute?.tool_calls).toBeNull() // dropped+ })++ it('N5: a fabricated tool_call in the patch is discarded (not the model’s own)', async () => {+ const h = new RemoteLlmHook(+ desc({ capabilities: ['may_substitute_result'] }),+ fetcher({+ status: 200,+ body: { response: { tool_calls: [{ id: 'z', name: 'rm', arguments: { path: '/' } }] } },+ unavailable: false,+ })+ )+ const c = await h.postCall(req(), resp())+ // The injected `rm` digest ≠ any model call → nothing survives the intersection.+ expect(c?.substitute?.tool_calls).toBeNull()+ })++ it('N5: an unchanged model tool_call in the patch survives (digest match, model object returned)', async () => {+ const h = new RemoteLlmHook(+ desc({ capabilities: ['may_substitute_result'] }),+ fetcher({+ status: 200,+ // Same identity+args as the model's call, but a different id — must return the model's object.+ body: {+ response: { tool_calls: [{ id: 'HOOK', name: 'read', arguments: { path: '/x' } }] },+ },+ unavailable: false,+ })+ )+ const c = await h.postCall(req(), resp())+ expect(c?.substitute?.tool_calls).toEqual([+ { id: 'a', name: 'read', arguments: { path: '/x' } },+ ])+ })++ it('fail-closed + unavailable + may_substitute_result → withhold body (§8.6)', async () => {+ const h = new RemoteLlmHook(+ desc({ capabilities: ['may_substitute_result'], failMode: 'closed' }),+ fetcher({ status: 0, body: undefined, unavailable: true })+ )+ const c = await h.postCall(req(), resp())+ expect(c?.substitute?.finish_reason).toBe(FinishReason.ContentFilter)+ expect(c?.substitute?.tool_calls).toBeNull()+ })++ it('fail-open + unavailable → no transform (original result passes through)', async () => {+ const h = new RemoteLlmHook(+ desc({ capabilities: ['may_substitute_result'], failMode: 'open' }),+ fetcher({ status: 0, body: undefined, unavailable: true })+ )+ expect(await h.postCall(req(), resp())).toBeNull()+ })+})+describe('on_error', () => {it('recover + may_substitute_result → text-only substitute (N5: tool_calls dropped)', async () => {const h = new RemoteLlmHook(diff --git a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.tsindex 84c141639..f5a69da3b 100644--- a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts+++ b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts@@ -19,7 +19,12 @@* 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 {+ ChatMessage,+ ToolCall,+ ToolCompletionRequest,+ ToolCompletionResponse,+} from '../../types'import type { Capability, Contributor } from '../types'import type { HookDescriptor, HookFetcher, LifecyclePoint } from './types'@@ -34,6 +39,33 @@ function stripSystemRole(messages: ChatMessage[]): ChatMessage[] {return messages.filter(m => m.role !== 'system')}+/** Stable, key-sorted serialization so a tool-call's argument digest is order-independent. */+function stableStringify(v: unknown): string {+ if (Array.isArray(v)) return `[${v.map(stableStringify).join(',')}]`+ if (isRecord(v)) {+ return `{${Object.keys(v)+ .sort()+ .map(k => `${JSON.stringify(k)}:${stableStringify(v[k])}`)+ .join(',')}}`+ }+ return JSON.stringify(v) ?? 'null'+}++/** Identity + argument digest — the key that decides whether a tool_call is the model's own (N5). */+function toolCallDigest(tc: { name?: unknown; arguments?: unknown }): string {+ return `${typeof tc.name === 'string' ? tc.name : ''}:${stableStringify(tc.arguments)}`+}++/** Content-filtered stand-in returned when a fail-closed redactor is unavailable (§8.6). */+function filteredPostResponse(usage: ToolCompletionResponse['usage']): ToolCompletionResponse {+ return {+ content: 'This response was withheld by a content guardrail policy.',+ tool_calls: null,+ usage,+ finish_reason: FinishReason.ContentFilter,+ }+}+export class RemoteLlmHook {constructor(private readonly descriptor: HookDescriptor,@@ -136,6 +168,66 @@ export class RemoteLlmHook {})}+ /**+ * `post_call` (spec §8.1): transform the model-visible result — may redact+ * `content` or DROP `tool_calls`, but NEVER introduce a `tool_call` absent from+ * the model's own output (N5, digest-checked). Gated by `may_substitute_result`+ * (it changes the caller-visible result, not the authoritative action flow, §4.3).+ * A fail-closed redactor that's unavailable withholds the un-redacted body (§8.6).+ */+ async postCall(+ request: ToolCompletionRequest,+ response: ToolCompletionResponse+ ): Promise<LlmContributor | null> {+ if (!this.handles('post_call')) return null+ const res = await this.fetch({+ point: 'post_call',+ descriptor: this.descriptor,+ body: {+ response: {+ content: response.content,+ tool_calls: response.tool_calls,+ finish_reason: response.finish_reason,+ },+ usage: response.usage,+ },+ })+ // §8.6: a fail-closed redactor that can't run must NOT leak the un-redacted body.+ if (res.unavailable || res.status !== 200) {+ if (this.descriptor.failMode === 'closed' && this.has('may_substitute_result')) {+ return this.contribution('allow', 'post_hook_unavailable', {+ phase: 'post',+ substitute: filteredPostResponse(response.usage),+ })+ }+ return null+ }++ const body = isRecord(res.body) ? res.body : {}+ const patched = isRecord(body.response) ? body.response : undefined+ if (!patched || !this.has('may_substitute_result')) return null++ // N5: the result may keep only tool_calls the model itself emitted. We intersect+ // the hook's kept digests with the ORIGINAL calls, so returned entries are always+ // the model's own objects — a hook can drop, never add or rewrite, a call.+ let toolCalls = response.tool_calls+ if (Array.isArray(patched.tool_calls)) {+ const kept = new Set(patched.tool_calls.filter(isRecord).map(toolCallDigest))+ const filtered = (response.tool_calls ?? []).filter((tc: ToolCall) =>+ kept.has(toolCallDigest(tc))+ )+ toolCalls = filtered.length > 0 ? filtered : null+ }++ const substitute: ToolCompletionResponse = {+ content: typeof patched.content === 'string' ? patched.content : response.content,+ tool_calls: toolCalls,+ usage: response.usage,+ finish_reason: response.finish_reason,+ }+ return this.contribution('allow', 'post_transformed', { phase: 'post', substitute })+ }+/*** `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).diff --git a/mcp-host/src/core/guardrails/llm/llmLaneHooks.ts b/mcp-host/src/core/guardrails/llm/llmLaneHooks.tsindex 4bdc7a248..1efd80119 100644--- a/mcp-host/src/core/guardrails/llm/llmLaneHooks.ts+++ b/mcp-host/src/core/guardrails/llm/llmLaneHooks.ts@@ -11,6 +11,8 @@ import type { HookDescriptor } from '../hooks/types'export interface LlmLaneHooks {preCall: RemoteLlmHook[]moderate: RemoteLlmHook[]+ postCall: RemoteLlmHook[]+ onError: RemoteLlmHook[]}export interface LlmLaneHookDeps {@@ -25,6 +27,8 @@ export function buildLlmLaneHooks(): LlmLaneHooks {const preCall: RemoteLlmHook[] = []const moderate: RemoteLlmHook[] = []+ const postCall: RemoteLlmHook[] = []+ const onError: RemoteLlmHook[] = []const ordered = (descriptors ?? []).slice().sort((a, b) => a.order - b.order)for (const d of ordered) {const hook = new RemoteLlmHook(@@ -33,6 +37,8 @@ export function buildLlmLaneHooks()if (d.lifecyclePoints.includes('pre_call')) preCall.push(hook)if (d.lifecyclePoints.includes('moderate')) moderate.push(hook)+ if (d.lifecyclePoints.includes('post_call')) postCall.push(hook)+ if (d.lifecyclePoints.includes('on_error')) onError.push(hook)}- return { preCall, moderate }+ return { preCall, moderate, postCall, onError }}