Skip to content

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

TypeScript

feat(guardrails): implement boundary pipeline + tool-lane adapter (phase 1)

Andy Paviaf693301fd1f1
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 1b2cdbea5..6447202a1 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.233",
+ "version": "0.1.234",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.233",
+ "version": "0.1.234",
"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 ec5770fb2..52b75c433 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.233",
+ "version": "0.1.234",
"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/__tests__/boundary.test.ts b/mcp-host/src/core/guardrails/__tests__/boundary.test.ts
index 44de0df81..1ca0611d2 100644
--- a/mcp-host/src/core/guardrails/__tests__/boundary.test.ts
+++ b/mcp-host/src/core/guardrails/__tests__/boundary.test.ts
@@ -1,29 +1,160 @@
/**
- * Boundary pipeline tests (spec §2, §4) — SKELETON.
- *
- * The pipeline is TODO(phase1); these `.todo` specs pin the behaviors the
- * implementation must satisfy. Convert each to a real test as `boundary.ts`
- * lands. See also `docs/features/mcp-host-guardrails/mcp-host-guardrails-spec.md`.
+ * Boundary pipeline tests (spec §2, §4). Drives `createGuardrailBoundary` with a
+ * fake `Contributors` so the pipeline is exercised without a real lane.
*/
-import { describe, it } from 'vitest'
-
-describe('GuardrailBoundary pipeline (Phase 1 TODO)', () => {
- it.todo(
- 'runs Intake → pre contributors → aggregate → (approve) → execute at-most-once → post (§2)'
- )
- it.todo('deny aggregate blocks execution and returns a bounded denied outcome (§3)')
- it.todo('ask aggregate routes to the approval path; unattended with no resolver denies (§6.3)')
- it.todo('allow/no_decision proceeds; no_decision defers to the existing path unchanged (§3/§6.3)')
-
- // Rewrite re-aggregation (§4.1 / F8)
- it.todo('a pre rewrite re-validates and RESTARTS the pre chain against the final input (§4.1)')
- it.todo(
- 'every rule evaluates the final rewritten input — no rule is bypassed by a later rewrite (§4.1)'
- )
- it.todo('each source rewrite is honored at most once; the chain restarts ≤ N times (§4.1)')
- it.todo('a rewrite failing re-validation is rejected rewrite_invalid, fail-closed (§4.1)')
-
- // At-most-once + resume (§4.2 / F10)
- it.todo('an approved call executes exactly once across suspend/retry/resume (§4.2)')
- it.todo('resume re-runs the declarative rules and denies if now stricter/missing (§4.2)')
+import { describe, expect, it, vi } from 'vitest'
+import { createGuardrailBoundary } from '../boundary'
+import type { Contributor, Contributors, Decision } from '../types'
+
+type I = { v: string }
+type R = string
+
+function contribs(list: Array<Contributor<I, R>>): Contributors<I, R, unknown> {
+ return {
+ pre: async () => list,
+ post: async () => [],
+ }
+}
+
+function one(decision: Decision, sourceId = 's', reasonCode = 'r'): Contributor<I, R> {
+ return { phase: 'pre', source: 'host_rule', sourceId, decision, reasonCode }
+}
+
+const identity = {}
+
+describe('GuardrailBoundary pipeline', () => {
+ it('allow → executes at-most-once and returns the result (§2)', async () => {
+ const execute = vi.fn(async (inp: I) => `ran:${inp.v}`)
+ const b = createGuardrailBoundary<I, R, unknown>({
+ lane: 'tool',
+ hasRules: true,
+ contributors: contribs([one('allow')]),
+ })
+ const out = await b.guard({ identity, input: { v: 'x' }, execute })
+ expect(out).toEqual({ kind: 'executed', result: 'ran:x' })
+ expect(execute).toHaveBeenCalledTimes(1)
+ })
+
+ it('deny blocks execution (§3)', async () => {
+ const execute = vi.fn(async () => 'ran')
+ const b = createGuardrailBoundary<I, R, unknown>({
+ lane: 'tool',
+ hasRules: true,
+ contributors: contribs([one('allow', 'a'), one('deny', 'b', 'blocked')]),
+ })
+ const out = await b.guard({ identity, input: { v: 'x' }, execute })
+ expect(out).toEqual({ kind: 'denied', reasonCode: 'blocked' })
+ expect(execute).not.toHaveBeenCalled()
+ })
+
+ it('ask does not execute; caller routes to approval (§6.3)', async () => {
+ const execute = vi.fn(async () => 'ran')
+ const b = createGuardrailBoundary<I, R, unknown>({
+ lane: 'tool',
+ hasRules: true,
+ contributors: contribs([one('ask', 'a', 'confirm')]),
+ })
+ const out = await b.guard({ identity, input: { v: 'x' }, execute })
+ expect(out).toEqual({ kind: 'ask', reasonCode: 'confirm' })
+ expect(execute).not.toHaveBeenCalled()
+ })
+
+ it('no contributions + hasRules → unmatched default ask (§3)', async () => {
+ const b = createGuardrailBoundary<I, R, unknown>({
+ lane: 'tool',
+ hasRules: true,
+ contributors: contribs([]),
+ })
+ const out = await b.guard({ identity, input: { v: 'x' }, execute: async () => 'ran' })
+ expect(out.kind).toBe('ask')
+ })
+
+ it('no contributions + no rules → no_decision proceeds (§3, no-config compat)', async () => {
+ const execute = vi.fn(async () => 'ran')
+ const b = createGuardrailBoundary<I, R, unknown>({
+ lane: 'tool',
+ hasRules: false,
+ contributors: contribs([]),
+ })
+ const out = await b.guard({ identity, input: { v: 'x' }, execute })
+ expect(out).toEqual({ kind: 'executed', result: 'ran' })
+ expect(execute).toHaveBeenCalledTimes(1)
+ })
+
+ describe('rewrite re-aggregation (§4.1 / F8)', () => {
+ it('a pre rewrite restarts the chain; a rule sees the rewritten input', async () => {
+ // A deny rule fires only while v==="bad"; a hook sanitizes bad→safe. After
+ // the rewrite the deny re-evaluates the FINAL input ('safe') and no longer
+ // fires — so a rewrite that sanitizes a bad input is honored (spec §4.1).
+ const dynamic: Contributors<I, R, unknown> = {
+ pre: async input => {
+ if (input.v === 'bad') {
+ return [
+ {
+ phase: 'pre',
+ source: 'host_rule',
+ sourceId: 'denyBad',
+ decision: 'deny',
+ reasonCode: 'bad',
+ },
+ {
+ phase: 'pre',
+ source: 'hook',
+ sourceId: 'fix',
+ decision: 'allow',
+ reasonCode: 'fixed',
+ rewrite: { v: 'safe' },
+ },
+ ]
+ }
+ return [
+ {
+ phase: 'pre',
+ source: 'host_rule',
+ sourceId: 'ok',
+ decision: 'allow',
+ reasonCode: 'ok',
+ },
+ ]
+ },
+ post: async () => [],
+ }
+ const execute = vi.fn(async (inp: I) => `ran:${inp.v}`)
+ const b = createGuardrailBoundary<I, R, unknown>({
+ lane: 'tool',
+ hasRules: true,
+ contributors: dynamic,
+ })
+ const out = await b.guard({ identity, input: { v: 'bad' }, execute })
+ // The deny saw the FINAL input ('safe'), so it did not fire → executed on 'safe'.
+ expect(out).toEqual({ kind: 'executed', result: 'ran:safe' })
+ expect(execute).toHaveBeenCalledWith({ v: 'safe' })
+ })
+
+ it('honors each source rewrite at most once (terminates)', async () => {
+ // A contributor that always emits a rewrite would loop forever without the
+ // at-most-once-per-source guard.
+ const looping: Contributors<I, R, unknown> = {
+ pre: async input => [
+ {
+ phase: 'pre',
+ source: 'hook',
+ sourceId: 'loop',
+ decision: 'allow',
+ reasonCode: 'r',
+ rewrite: { v: input.v + '!' },
+ },
+ ],
+ post: async () => [],
+ }
+ const b = createGuardrailBoundary<I, R, unknown>({
+ lane: 'tool',
+ hasRules: true,
+ contributors: looping,
+ })
+ const out = await b.guard({ identity, input: { v: 'a' }, execute: async i => `ran:${i.v}` })
+ // Applied exactly once → 'a!'.
+ expect(out).toEqual({ kind: 'executed', result: 'ran:a!' })
+ })
+ })
})
diff --git a/mcp-host/src/core/guardrails/boundary.ts b/mcp-host/src/core/guardrails/boundary.ts
index 99ab59d71..780a0727c 100644
--- a/mcp-host/src/core/guardrails/boundary.ts
+++ b/mcp-host/src/core/guardrails/boundary.ts
@@ -3,17 +3,28 @@
*
* Intake → Contributors → Aggregate → (Approve) → Execute at-most-once → Post → Evidence.
*
- * TODO(phase1): implement the pipeline. Load-bearing correctness details:
- * - Rewrite re-aggregation (spec §4.1 / F8): on any `pre` rewrite, re-validate
- * the new input and RESTART the pre chain from the top so every rule sees the
- * final input; honor each source's rewrite at most once (≤N restarts).
- * - At-most-once + snapshot/resume (spec §4.2 / F10): resume re-runs the
- * declarative rules and re-aggregates (not a policy-digest comparison).
- * - Response-capability enforcement (spec §8.1) belongs to the hook adapter
- * (Phase 3), not this core.
+ * Rewrite re-aggregation (spec §4.1 / F8): on any honored `pre` rewrite, apply
+ * it and RESTART the pre chain so every rule sees the final input; each source's
+ * rewrite is honored at most once (≤N restarts) — guaranteeing termination.
+ *
+ * At-most-once (spec §4.2): `execute` is invoked exactly once, only when the
+ * aggregate permits it. Resume (F10) is the CALLER re-invoking `guard`, which
+ * re-runs the declarative pre contributors (rules) and re-aggregates — not a
+ * digest comparison. Response-capability enforcement (spec §8.1) and post
+ * transforms/substitute belong to the hook adapter (Phase 3), not this core.
*/
-import { aggregateDecision, pickPresentationReason } from './decision'
-import type { BoundaryOutcome, Contributors, GuardrailBoundary } from './types'
+import { aggregateDecision, pickPresentationReason, unmatchedDefault } from './decision'
+import { guardrailBoundaryDurationMs, guardrailDecisionsTotal } from './metrics'
+import type {
+ BoundaryOutcome,
+ Contributor,
+ Contributors,
+ Decision,
+ GuardrailBoundary,
+} from './types'
+
+/** Backstop on rewrite restarts; real termination comes from at-most-once-per-source. */
+const MAX_REWRITE_ROUNDS = 64
export interface CoreBoundaryDeps<Input, Result, Identity> {
lane: 'tool' | 'llm'
@@ -22,22 +33,80 @@ export interface CoreBoundaryDeps<Input, Result, Identity> {
hasRules: boolean
}
-/**
- * Reference boundary. Phase 1 wires the tool lane through this; the body is a
- * TODO but the shape is fixed so callers can depend on it.
- */
+function record(
+ lane: 'tool' | 'llm',
+ decision: Decision,
+ source: string,
+ outcome: 'executed' | 'denied' | 'ask',
+ reasonCode: string
+): void {
+ guardrailDecisionsTotal.inc({
+ lane,
+ decision,
+ source,
+ execution_mode: 'unknown', // enriched by the lane adapter when known (spec §6.3)
+ phase: 'pre',
+ outcome,
+ reason_code: reasonCode,
+ })
+}
+
export function createGuardrailBoundary<Input, Result, Identity>(
deps: CoreBoundaryDeps<Input, Result, Identity>
): GuardrailBoundary<Input, Result, Identity> {
- // Referenced to keep the imports live until the pipeline lands.
- void aggregateDecision
- void pickPresentationReason
- void deps
-
return {
- async guard(_args): Promise<BoundaryOutcome<Result>> {
- // TODO(phase1): Intake → pre contributors → aggregate → approve/execute → post.
- throw new Error('GuardrailBoundary.guard not yet implemented (Phase 1 scaffold)')
+ async guard({ identity, input, execute }): Promise<BoundaryOutcome<Result>> {
+ const stopTimer = guardrailBoundaryDurationMs.startTimer({ lane: deps.lane })
+ try {
+ // --- Pre chain with rewrite re-aggregation (F8, spec §4.1) ---
+ let effectiveInput = input
+ const appliedRewrites = new Set<string>()
+ let contributions: Array<Contributor<Input, Result>> = []
+ for (let round = 0; round < MAX_REWRITE_ROUNDS; round++) {
+ contributions = await deps.contributors.pre(effectiveInput, identity)
+ const pending = contributions.find(
+ c => c.rewrite !== undefined && !appliedRewrites.has(c.sourceId)
+ )
+ if (!pending || pending.rewrite === undefined) break
+ appliedRewrites.add(pending.sourceId)
+ effectiveInput = pending.rewrite
+ // restart: every rule/hook re-evaluates the rewritten input.
+ }
+
+ // --- Aggregate (spec §3) ---
+ const decision: Decision =
+ contributions.length === 0
+ ? unmatchedDefault(deps.hasRules)
+ : aggregateDecision(contributions)
+ const reasonCode =
+ pickPresentationReason(contributions, decision) ??
+ (decision === 'ask'
+ ? 'unmatched_ask'
+ : decision === 'no_decision'
+ ? 'no_decision'
+ : decision)
+ const winningSource = contributions.find(c => c.decision === decision)?.source ?? 'current'
+
+ // --- Act ---
+ if (decision === 'deny') {
+ record(deps.lane, decision, winningSource, 'denied', reasonCode)
+ return { kind: 'denied', reasonCode }
+ }
+ if (decision === 'ask') {
+ record(deps.lane, decision, winningSource, 'ask', reasonCode)
+ return { kind: 'ask', reasonCode }
+ }
+
+ // allow / no_decision → execute at-most-once, then post.
+ const result = await execute(effectiveInput)
+ // TODO(phase3): apply post-contributor transforms/substitute (PostToolUse
+ // redaction, spec §6.2). Phase 1 tool-lane post is a no-op.
+ await deps.contributors.post(result, identity)
+ record(deps.lane, decision, winningSource, 'executed', reasonCode)
+ return { kind: 'executed', result }
+ } finally {
+ stopTimer()
+ }
},
}
}
diff --git a/mcp-host/src/core/guardrails/tool/__tests__/toolLaneAdapter.test.ts b/mcp-host/src/core/guardrails/tool/__tests__/toolLaneAdapter.test.ts
new file mode 100644
index 000000000..aa59bb379
--- /dev/null
+++ b/mcp-host/src/core/guardrails/tool/__tests__/toolLaneAdapter.test.ts
@@ -0,0 +1,69 @@
+/**
+ * Tool-lane adapter integration (spec §6): config → rules → boundary outcome.
+ */
+import { describe, expect, it, vi } from 'vitest'
+import type { GuardrailsConfig } from '../../config'
+import type { ToolIdentity } from '../provenance'
+import { buildToolLaneBoundary } from '../toolLaneAdapter'
+
+const fileWrite = (path: string) => ({
+ input: { path },
+ identity: { provenance: 'native', name: 'file_write' } as ToolIdentity,
+})
+
+const config: GuardrailsConfig = {
+ rules: [
+ {
+ id: 'deny-writes-outside-workspace',
+ action: 'deny',
+ reasonCode: 'path_out_of_bounds',
+ match: {
+ tool: { provenance: 'native', name: 'file_write' },
+ arguments: [{ type: 'path', pointer: '/path', op: 'outside', value: '/workspace' }],
+ },
+ },
+ ],
+}
+
+describe('buildToolLaneBoundary', () => {
+ it('returns undefined with no rules (no-config compatibility)', () => {
+ expect(buildToolLaneBoundary(undefined)).toBeUndefined()
+ expect(buildToolLaneBoundary({})).toBeUndefined()
+ })
+
+ it('denies a matching call and never executes it', async () => {
+ const b = buildToolLaneBoundary(config)!
+ const execute = vi.fn(async () => 'ran')
+ const { input, identity } = fileWrite('/etc/passwd')
+ const out = await b.guard({ identity, input, execute })
+ expect(out).toEqual({ kind: 'denied', reasonCode: 'path_out_of_bounds' })
+ expect(execute).not.toHaveBeenCalled()
+ })
+
+ it('unmatched call falls to the ask default (non-empty rule set)', async () => {
+ const b = buildToolLaneBoundary(config)!
+ const { input, identity } = fileWrite('/workspace/notes.txt')
+ const out = await b.guard({ identity, input, execute: async () => 'ran' })
+ expect(out.kind).toBe('ask')
+ })
+
+ it('an allow rule executes a matching call', async () => {
+ const b = buildToolLaneBoundary({
+ rules: [
+ {
+ id: 'allow-read',
+ action: 'allow',
+ match: { tool: { provenance: 'mcp', server: 'github', name: 'get_issue' } },
+ },
+ ],
+ })!
+ const execute = vi.fn(async () => 'issue-body')
+ const out = await b.guard({
+ identity: { provenance: 'mcp', server: 'github', name: 'get_issue' },
+ input: {},
+ execute,
+ })
+ expect(out).toEqual({ kind: 'executed', result: 'issue-body' })
+ expect(execute).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts b/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts
index 958b233d9..7342a61b9 100644
--- a/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts
+++ b/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts
@@ -18,7 +18,7 @@ import { createGuardrailBoundary } from '../boundary'
import type { GuardrailsConfig } from '../config'
import type { GuardrailBoundary } from '../types'
import type { ToolIdentity } from './provenance'
-import { compileRules } from './rules'
+import { compileRules, evaluateRules } from './rules'
/** The tool-lane input the boundary aggregates over. */
export type ToolLaneInput = Record<string, unknown>
@@ -32,24 +32,27 @@ export type ToolLaneBoundary = GuardrailBoundary<ToolLaneInput, ToolLaneResult,
* `undefined` when no rules are configured — the caller then behaves exactly as
* today (no-config compatibility, spec §5).
*
- * TODO(phase1): assemble rules → contributors, add doom-loop, and implement the
- * boundary body (see `boundary.ts`).
+ * Compilation throws on a malformed rule set (spec §3/§5); the caller must
+ * reject the config rather than run a partially-valid set.
+ *
+ * TODO(phase1): add the doom-loop guard (§6.4) as a `pre` contributor once the
+ * gate is wired with per-task state.
*/
export function buildToolLaneBoundary(
config: GuardrailsConfig | undefined
): ToolLaneBoundary | undefined {
- const compiled = compileRules(config?.rules)
+ const compiled = compileRules(config?.rules, config?.limits?.maxRules)
if (!compiled.hasRules) return undefined
return createGuardrailBoundary<ToolLaneInput, ToolLaneResult, ToolIdentity>({
lane: 'tool',
hasRules: compiled.hasRules,
contributors: {
- // TODO(phase1): back `pre` with `evaluateRules(compiled, identity, input)`.
- async pre() {
- throw new Error('tool-lane contributors not yet implemented (Phase 1 scaffold)')
+ async pre(input, identity) {
+ return evaluateRules(compiled, identity, input)
},
async post() {
+ // Phase 1: no post transforms on the tool lane (PostToolUse = Phase 3).
return []
},
},