Skip to content

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

TypeScript

feat(guardrails): add /v1 hook http transport + non-conforming fail-safe (phase 3)

Andy Pavia53d1fe0a7c7d
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 8a35a59c2..df150f9ed 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.241",
+ "version": "0.1.242",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.241",
+ "version": "0.1.242",
"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 af4bc1034..eec8a01de 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.241",
+ "version": "0.1.242",
"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__/hookFetcher.test.ts b/mcp-host/src/core/guardrails/hooks/__tests__/hookFetcher.test.ts
new file mode 100644
index 000000000..277b76aed
--- /dev/null
+++ b/mcp-host/src/core/guardrails/hooks/__tests__/hookFetcher.test.ts
@@ -0,0 +1,103 @@
+/**
+ * HookFetcher transport tests (spec §8.1 wire contract): URL building, auth
+ * header, and outcome classification (5xx / timeout / malformed / oversized →
+ * unavailable; 2xx/4xx returned for the mapping).
+ */
+import { describe, expect, it, vi } from 'vitest'
+import { type FetchLike, buildHookUrl, createHookFetcher } from '../hookFetcher'
+import type { HookDescriptor } from '../types'
+
+const desc: HookDescriptor = {
+ id: 'h',
+ endpoint: 'http://hook-server.llm-hooks.svc/',
+ path: '/pii-redact',
+ lifecyclePoints: ['moderate'],
+ capabilities: [],
+ failMode: 'closed',
+ order: 100,
+}
+
+const okResponse = (
+ status: number,
+ text: string
+): { status: number; text: () => Promise<string> } => ({
+ status,
+ text: async () => text,
+})
+
+describe('buildHookUrl', () => {
+ it('normalizes slashes → {endpoint}{path}/v1/{point}', () => {
+ expect(buildHookUrl('http://svc/', '/pii-redact', 'moderate')).toBe(
+ 'http://svc/pii-redact/v1/moderate'
+ )
+ expect(buildHookUrl('http://svc', '/', 'pre_call')).toBe('http://svc/v1/pre_call')
+ expect(buildHookUrl('http://svc', '', 'on_error')).toBe('http://svc/v1/on_error')
+ })
+})
+
+describe('createHookFetcher', () => {
+ it('POSTs with bearer auth to the built URL and parses JSON', async () => {
+ const fetchImpl = vi.fn<FetchLike>(async () => okResponse(200, '{"action":"continue"}'))
+ const fetcher = createHookFetcher({ getAuthToken: () => 'tok', fetchImpl })
+ const r = await fetcher({ point: 'moderate', descriptor: desc, body: { a: 1 } })
+ expect(r).toEqual({ status: 200, body: { action: 'continue' }, unavailable: false })
+ const [url, init] = fetchImpl.mock.calls[0]
+ expect(url).toBe('http://hook-server.llm-hooks.svc/pii-redact/v1/moderate')
+ expect(init.headers.Authorization).toBe('Bearer tok')
+ expect(init.method).toBe('POST')
+ })
+
+ it('5xx → unavailable', async () => {
+ const fetcher = createHookFetcher({
+ getAuthToken: () => 't',
+ fetchImpl: async () => okResponse(503, ''),
+ })
+ expect((await fetcher({ point: 'moderate', descriptor: desc, body: {} })).unavailable).toBe(
+ true
+ )
+ })
+
+ it('4xx is NOT unavailable (mapping classifies it)', async () => {
+ const fetcher = createHookFetcher({
+ getAuthToken: () => 't',
+ fetchImpl: async () => okResponse(422, '{"code":"blocked"}'),
+ })
+ const r = await fetcher({ point: 'moderate', descriptor: desc, body: {} })
+ expect(r).toEqual({ status: 422, body: { code: 'blocked' }, unavailable: false })
+ })
+
+ it('malformed JSON → unavailable', async () => {
+ const fetcher = createHookFetcher({
+ getAuthToken: () => 't',
+ fetchImpl: async () => okResponse(200, 'not json'),
+ })
+ expect((await fetcher({ point: 'moderate', descriptor: desc, body: {} })).unavailable).toBe(
+ true
+ )
+ })
+
+ it('oversized body → unavailable', async () => {
+ const fetcher = createHookFetcher({
+ getAuthToken: () => 't',
+ maxOutputBytes: 4,
+ fetchImpl: async () => okResponse(200, '{"action":"continue"}'),
+ })
+ expect((await fetcher({ point: 'moderate', descriptor: desc, body: {} })).unavailable).toBe(
+ true
+ )
+ })
+
+ it('connection error / timeout → unavailable', async () => {
+ const fetcher = createHookFetcher({
+ getAuthToken: () => 't',
+ fetchImpl: async () => {
+ throw new Error('ECONNREFUSED')
+ },
+ })
+ expect(await fetcher({ point: 'moderate', descriptor: desc, body: {} })).toEqual({
+ status: 0,
+ body: undefined,
+ unavailable: true,
+ })
+ })
+})
diff --git a/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts b/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts
index 3aec04243..f05b2609a 100644
--- a/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts
+++ b/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts
@@ -73,6 +73,23 @@ describe('pre_call', () => {
})
})
+describe('pre_call non-conforming → fail-mode (§8.1)', () => {
+ it('non-200 with may_deny → deny (never a silent allow)', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: ['may_deny'] }),
+ fetcher({ status: 418, body: {}, unavailable: false })
+ )
+ expect((await h.preCall(req()))?.decision).toBe('deny')
+ })
+ it('200 with no valid action + may_deny → deny', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: ['may_deny'] }),
+ fetcher({ status: 200, body: { nonsense: true }, unavailable: false })
+ )
+ expect((await h.preCall(req()))?.decision).toBe('deny')
+ })
+})
+
describe('moderate', () => {
it('200 → pass (no contribution)', async () => {
const h = new RemoteLlmHook(
diff --git a/mcp-host/src/core/guardrails/hooks/hookFetcher.ts b/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
new file mode 100644
index 000000000..f929be85b
--- /dev/null
+++ b/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
@@ -0,0 +1,81 @@
+/**
+ * Concrete `/v1` HTTP transport for installed hooks (spec §8.1 wire contract).
+ *
+ * POSTs JSON to `{endpoint}{path}/v1/{point}` with a short-lived bearer token
+ * (mcp-host's env-injected token via a `getAuthToken` closure — the same pattern
+ * as `credentialBrokerClient.ts`; no in-process signing). Enforces the timeout
+ * and body cap, and classifies the outcome per §8.1: `5xx` / timeout /
+ * connection error / malformed or oversized body → `unavailable` (→ the hook's
+ * fail-mode, §8.6). `4xx`/`2xx` are returned for the per-point mapping to judge.
+ *
+ * In-cluster (`image`/`service`) targets are trusted and dialed directly. The
+ * SSRF-guarded `remote`-mode transport (DNS-pin + `isPrivateIp`, spec §8.3) is a
+ * later increment — pass a guarded `fetchImpl` to reuse this shell for it.
+ */
+import type { HookFetcher, LifecyclePoint } from './types'
+
+/** Minimal fetch surface (injectable for tests + a future SSRF-guarded impl). */
+export type FetchLike = (
+ url: string,
+ init: { method: string; headers: Record<string, string>; body: string; signal: AbortSignal }
+) => Promise<{ status: number; text: () => Promise<string> }>
+
+export interface HookFetcherDeps {
+ getAuthToken: () => string
+ timeoutMs?: number
+ maxOutputBytes?: number
+ /** Defaults to the global `fetch`. Inject an SSRF-guarded impl for `remote` hooks. */
+ fetchImpl?: FetchLike
+}
+
+const POINT_PATH: Record<LifecyclePoint, string> = {
+ pre_call: 'pre_call',
+ moderate: 'moderate',
+ post_call: 'post_call',
+ on_error: 'on_error',
+}
+
+/** Build `{endpoint}{path}/v1/{point}`, normalizing slashes (spec §8.1). */
+export function buildHookUrl(endpoint: string, path: string, point: LifecyclePoint): string {
+ const base = endpoint.replace(/\/+$/, '')
+ const mid = !path || path === '/' ? '' : '/' + path.replace(/^\/+|\/+$/g, '')
+ return `${base}${mid}/v1/${POINT_PATH[point]}`
+}
+
+export function createHookFetcher(deps: HookFetcherDeps): HookFetcher {
+ const timeoutMs = deps.timeoutMs ?? 5000
+ const maxOutputBytes = deps.maxOutputBytes ?? 65536
+ const doFetch: FetchLike = deps.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)
+
+ return async ({ point, descriptor, body }) => {
+ const url = buildHookUrl(descriptor.endpoint, descriptor.path, point)
+ try {
+ const res = await doFetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${deps.getAuthToken()}`,
+ },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(timeoutMs),
+ })
+ const text = await res.text()
+ if (text.length > maxOutputBytes) {
+ return { status: res.status, body: undefined, unavailable: true } // oversized → unavailable
+ }
+ let parsed: unknown = {}
+ if (text) {
+ try {
+ parsed = JSON.parse(text)
+ } catch {
+ return { status: res.status, body: undefined, unavailable: true } // malformed → unavailable
+ }
+ }
+ // 5xx → unavailable; 2xx/4xx are returned for the mapping to classify.
+ return { status: res.status, body: parsed, unavailable: res.status >= 500 }
+ } catch {
+ // timeout / connection error → unavailable
+ return { status: 0, body: undefined, unavailable: true }
+ }
+ }
+}
diff --git a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts
index 0e03489d7..84c141639 100644
--- a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts
+++ b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts
@@ -76,7 +76,8 @@ export class RemoteLlmHook {
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()
+ // §8.1: non-200 or unavailable → fail-mode (never a silent allow).
+ if (res.unavailable || res.status !== 200) return this.onUnavailable()
const body = isRecord(res.body) ? res.body : {}
if (body.action === 'reject') {
@@ -86,14 +87,15 @@ export class RemoteLlmHook {
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 })
+ if (body.action === 'continue') {
+ const patch = isRecord(body.patch) ? body.patch : undefined
+ if (patch && this.has('may_rewrite')) {
+ return this.contribution('allow', 'shaped', { rewrite: this.applyPatch(request, patch) })
+ }
+ return null // continue with no honored patch → no contribution (allow).
}
- // Continue with no honored patch → no contribution (allow).
- return null
+ // A 200 with no valid action is non-conforming (§8.1) → fail-mode.
+ return this.onUnavailable()
}
/** Apply a `pre_call` patch: NON-system messages + params only (N4). */
@@ -145,7 +147,8 @@ export class RemoteLlmHook {
descriptor: this.descriptor,
body: { request, error },
})
- if (res.unavailable) return null // can't recover a failed call if the recovery hook is also down.
+ // Recovery only on a proper 200 `recover`; anything else = no recovery (error surfaces).
+ if (res.unavailable || res.status !== 200) return null
const body = isRecord(res.body) ? res.body : {}
if (body.action !== 'recover' || !this.has('may_substitute_result')) return null
diff --git a/mcp-host/src/core/guardrails/index.ts b/mcp-host/src/core/guardrails/index.ts
index 72f5a5fad..059eaf51a 100644
--- a/mcp-host/src/core/guardrails/index.ts
+++ b/mcp-host/src/core/guardrails/index.ts
@@ -31,4 +31,6 @@ 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 { buildHookUrl, createHookFetcher } from './hooks/hookFetcher'
+export type { FetchLike, HookFetcherDeps } from './hooks/hookFetcher'
export { guardrailDecisionsTotal, guardrailBoundaryDurationMs } from './metrics'