Skip to content

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

TypeScript

feat(guardrails): wire the tool-lane gate into the tool-use loop (phase 1)

Andy Pavia6f0f2a26be8e
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 6447202a1..569d33be4 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.234",
+ "version": "0.1.235",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.234",
+ "version": "0.1.235",
"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 52b75c433..77575d6ee 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.234",
+ "version": "0.1.235",
"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/boundary.ts b/mcp-host/src/core/guardrails/boundary.ts
index 780a0727c..436484da3 100644
--- a/mcp-host/src/core/guardrails/boundary.ts
+++ b/mcp-host/src/core/guardrails/boundary.ts
@@ -3,14 +3,19 @@
*
* Intake → Contributors → Aggregate → (Approve) → Execute at-most-once → Post → Evidence.
*
+ * `evaluateBoundary` runs the decision-only part (pre chain + aggregate) so a
+ * lane that owns its own execution/suspension (the tool loop) can act on the
+ * decision itself. `createGuardrailBoundary().guard()` is the wrap-around form
+ * (execute at-most-once inside) — used by the LLM lane (Phase 2).
+ *
* 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
+ * aggregate permits it. Resume (F10) is the CALLER re-invoking the boundary,
+ * 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, unmatchedDefault } from './decision'
@@ -18,6 +23,7 @@ import { guardrailBoundaryDurationMs, guardrailDecisionsTotal } from './metrics'
import type {
BoundaryOutcome,
Contributor,
+ ContributorSource,
Contributors,
Decision,
GuardrailBoundary,
@@ -33,6 +39,49 @@ export interface CoreBoundaryDeps<Input, Result, Identity> {
hasRules: boolean
}
+/** Decision-only result (spec §3) — no execution. */
+export interface BoundaryEvaluation<Input> {
+ decision: Decision
+ reasonCode: string
+ /** The input after any honored rewrites (spec §4.1). */
+ effectiveInput: Input
+ /** The winning contribution's source (for evidence). */
+ source: ContributorSource
+}
+
+/**
+ * Run the pre chain (with F8 rewrite re-aggregation) and aggregate to a decision.
+ * No execution, no metrics — the caller records the final outcome.
+ */
+export async function evaluateBoundary<Input, Result, Identity>(
+ deps: CoreBoundaryDeps<Input, Result, Identity>,
+ identity: Identity,
+ input: Input
+): Promise<BoundaryEvaluation<Input>> {
+ 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.
+ }
+
+ 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 source: ContributorSource =
+ contributions.find(c => c.decision === decision)?.source ?? 'current'
+
+ return { decision, reasonCode, effectiveInput, source }
+}
+
function record(
lane: 'tool' | 'llm',
decision: Decision,
@@ -51,6 +100,17 @@ function record(
})
}
+/** Record a guardrail decision + its outcome (spec §9). Exposed so lane adapters that own execution can emit it. */
+export function recordDecision(
+ lane: 'tool' | 'llm',
+ decision: Decision,
+ source: string,
+ outcome: 'executed' | 'denied' | 'ask',
+ reasonCode: string
+): void {
+ record(lane, decision, source, outcome, reasonCode)
+}
+
export function createGuardrailBoundary<Input, Result, Identity>(
deps: CoreBoundaryDeps<Input, Result, Identity>
): GuardrailBoundary<Input, Result, Identity> {
@@ -58,42 +118,18 @@ export function createGuardrailBoundary<Input, Result, Identity>(
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'
+ const { decision, reasonCode, effectiveInput, source } = await evaluateBoundary(
+ deps,
+ identity,
+ input
+ )
- // --- Act ---
if (decision === 'deny') {
- record(deps.lane, decision, winningSource, 'denied', reasonCode)
+ record(deps.lane, decision, source, 'denied', reasonCode)
return { kind: 'denied', reasonCode }
}
if (decision === 'ask') {
- record(deps.lane, decision, winningSource, 'ask', reasonCode)
+ record(deps.lane, decision, source, 'ask', reasonCode)
return { kind: 'ask', reasonCode }
}
@@ -102,7 +138,7 @@ export function createGuardrailBoundary<Input, Result, Identity>(
// 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)
+ record(deps.lane, decision, source, 'executed', reasonCode)
return { kind: 'executed', result }
} finally {
stopTimer()
diff --git a/mcp-host/src/core/guardrails/index.ts b/mcp-host/src/core/guardrails/index.ts
index 0d72894ed..88075a729 100644
--- a/mcp-host/src/core/guardrails/index.ts
+++ b/mcp-host/src/core/guardrails/index.ts
@@ -1,17 +1,24 @@
/**
* Guardrail engine — public surface (spec §2–§6, §9).
*
- * Phase 1: lane-neutral core (types + decision algebra) is implemented; the
- * boundary pipeline and the tool-lane adapter are scaffolded (TODO(phase1)).
- * The live gate is not yet wired into the tool-use loop.
+ * Phase 1: lane-neutral core (types, decision algebra, boundary pipeline) and
+ * the tool-lane guardrail (rules + predicates) are implemented and wired behind
+ * `config.guardrails` in the tool-use loop. Installed hooks + the LLM lane are
+ * Phases 2–3.
*/
export * from './types'
export * from './decision'
export * from './capabilities'
-export { createGuardrailBoundary } from './boundary'
-export type { CoreBoundaryDeps } from './boundary'
+export { createGuardrailBoundary, evaluateBoundary, recordDecision } from './boundary'
+export type { CoreBoundaryDeps, BoundaryEvaluation } from './boundary'
export type { GuardrailsConfig, GuardrailRule, GuardrailLimits } from './config'
-export { buildToolLaneBoundary } from './tool/toolLaneAdapter'
-export type { ToolLaneBoundary, ToolLaneInput, ToolLaneResult } from './tool/toolLaneAdapter'
+export { buildToolLaneGuardrail } from './tool/toolLaneAdapter'
+export type {
+ ToolLaneGuardrail,
+ ToolGuardrailDecision,
+ ToolLaneInput,
+ ToolLaneResult,
+} from './tool/toolLaneAdapter'
+export { resolveToolIdentity, resolveToolIdentityFromRegistry } from './tool/provenance'
export type { ToolIdentity } from './tool/provenance'
export { guardrailDecisionsTotal, guardrailBoundaryDurationMs } from './metrics'
diff --git a/mcp-host/src/core/guardrails/tool/__tests__/toolLaneAdapter.test.ts b/mcp-host/src/core/guardrails/tool/__tests__/toolLaneAdapter.test.ts
index aa59bb379..726600e00 100644
--- a/mcp-host/src/core/guardrails/tool/__tests__/toolLaneAdapter.test.ts
+++ b/mcp-host/src/core/guardrails/tool/__tests__/toolLaneAdapter.test.ts
@@ -1,15 +1,12 @@
/**
- * Tool-lane adapter integration (spec §6): config → rules → boundary outcome.
+ * Tool-lane adapter integration (spec §6): config → rules → decision.
*/
-import { describe, expect, it, vi } from 'vitest'
+import { describe, expect, it } from 'vitest'
import type { GuardrailsConfig } from '../../config'
import type { ToolIdentity } from '../provenance'
-import { buildToolLaneBoundary } from '../toolLaneAdapter'
+import { buildToolLaneGuardrail } from '../toolLaneAdapter'
-const fileWrite = (path: string) => ({
- input: { path },
- identity: { provenance: 'native', name: 'file_write' } as ToolIdentity,
-})
+const fileWrite: ToolIdentity = { provenance: 'native', name: 'file_write' }
const config: GuardrailsConfig = {
rules: [
@@ -25,30 +22,27 @@ const config: GuardrailsConfig = {
],
}
-describe('buildToolLaneBoundary', () => {
+describe('buildToolLaneGuardrail', () => {
it('returns undefined with no rules (no-config compatibility)', () => {
- expect(buildToolLaneBoundary(undefined)).toBeUndefined()
- expect(buildToolLaneBoundary({})).toBeUndefined()
+ expect(buildToolLaneGuardrail(undefined)).toBeUndefined()
+ expect(buildToolLaneGuardrail({})).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('denies a matching call', async () => {
+ const g = buildToolLaneGuardrail(config)!
+ const d = await g.decide(fileWrite, { path: '/etc/passwd' })
+ expect(d.decision).toBe('deny')
+ expect(d.reasonCode).toBe('path_out_of_bounds')
})
- 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('unmatched call → ask default (non-empty rule set)', async () => {
+ const g = buildToolLaneGuardrail(config)!
+ const d = await g.decide(fileWrite, { path: '/workspace/notes.txt' })
+ expect(d.decision).toBe('ask')
})
- it('an allow rule executes a matching call', async () => {
- const b = buildToolLaneBoundary({
+ it('an allow rule → allow', async () => {
+ const g = buildToolLaneGuardrail({
rules: [
{
id: 'allow-read',
@@ -57,13 +51,7 @@ describe('buildToolLaneBoundary', () => {
},
],
})!
- 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)
+ const d = await g.decide({ provenance: 'mcp', server: 'github', name: 'get_issue' }, {})
+ expect(d.decision).toBe('allow')
})
})
diff --git a/mcp-host/src/core/guardrails/tool/provenance.ts b/mcp-host/src/core/guardrails/tool/provenance.ts
index 5de25f128..c2c05227c 100644
--- a/mcp-host/src/core/guardrails/tool/provenance.ts
+++ b/mcp-host/src/core/guardrails/tool/provenance.ts
@@ -9,7 +9,7 @@
* TODO(phase1): thread `serverName` from `McpManager` into the resolver and
* replace the `__` split at `core/adapters/toolRegistryAdapter.ts:100-103`.
*/
-import type { ToolTraceDescriptor } from '../../interfaces'
+import type { ToolRegistry, ToolTraceDescriptor } from '../../interfaces'
/** The resolved identity the tool-lane boundary evaluates (spec §6 `ResolvedIdentity`). */
export interface ToolIdentity {
@@ -37,3 +37,22 @@ export function resolveToolIdentity(
}
return { provenance: 'native', name }
}
+
+/**
+ * Resolve a resolved tool call's identity from the REGISTRY (spec §6) — the
+ * provenance comes from `tool.traceDescriptor().kind`, never from the tool name.
+ * An unknown tool defaults to `native` (the composite registry resolves native
+ * first; an unresolved name is treated as native for matching purposes).
+ *
+ * TODO(phase1): thread the registry-authoritative `serverName` from `McpManager`
+ * so the MCP `server` is not the `__`-derived `sourceRef` (see `resolveToolIdentity`).
+ */
+export function resolveToolIdentityFromRegistry(
+ name: string,
+ registry: ToolRegistry,
+ args: Record<string, unknown> = {}
+): ToolIdentity {
+ const tool = registry.get(name)
+ const descriptor = tool?.traceDescriptor?.(args)
+ return resolveToolIdentity(name, descriptor)
+}
diff --git a/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts b/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts
index 7342a61b9..9d89d84e8 100644
--- a/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts
+++ b/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts
@@ -1,35 +1,38 @@
/**
- * Tool-lane adapter (spec §6) — specializes the GuardrailBoundary over tool
+ * Tool-lane adapter (spec §6) — specializes the guardrail engine over tool
* execution.
*
- * `Input` = resolved-tool arguments; `Result` = the tool result; `Identity` =
- * the real tool after dynamic-bridge resolution (spec §6). This is the entry
- * point the tool-use loop calls before executing a tool.
- *
- * INTEGRATION SEAM (spec §6, map: toolUseLoopToolBatch.ts:207): the live gate is
- * NOT wired into the loop in the Phase 1 scaffold. When wired, `no_decision`
- * falls through to the existing approval path (`beforeTool`), and `ask` returns
- * a suspension shaped like `mcpApprovalGateController.createSuspension`.
- *
- * TODO(phase1): build the boundary from the rules engine + doom-loop, then wire
- * the gate in `executeToolCalls` behind `config.guardrails` (absent = today).
+ * `Input` = resolved-tool arguments; `Identity` = the real tool after
+ * dynamic-bridge resolution (spec §6). Unlike the LLM lane (which uses the
+ * wrap-around `guard(execute)`), the tool-use loop owns execution + suspension,
+ * so this exposes a decision-only `decide()`; the loop acts on the decision
+ * (deny → bounded error, ask → suspension, allow/no_decision → existing path).
*/
-import { createGuardrailBoundary } from '../boundary'
+import { type CoreBoundaryDeps, evaluateBoundary } from '../boundary'
import type { GuardrailsConfig } from '../config'
-import type { GuardrailBoundary } from '../types'
+import type { Decision } from '../types'
import type { ToolIdentity } from './provenance'
import { compileRules, evaluateRules } from './rules'
-/** The tool-lane input the boundary aggregates over. */
export type ToolLaneInput = Record<string, unknown>
-/** The tool-lane result (kept string-shaped; the loop maps to `ToolResult`). */
export type ToolLaneResult = string
-export type ToolLaneBoundary = GuardrailBoundary<ToolLaneInput, ToolLaneResult, ToolIdentity>
+export interface ToolGuardrailDecision {
+ decision: Decision
+ reasonCode: string
+ /** Arguments after any honored rewrites (spec §4.1). Phase 1 rules never rewrite. */
+ effectiveInput: ToolLaneInput
+ source: string
+}
+
+/** The tool-lane guardrail the loop consults before executing a tool. */
+export interface ToolLaneGuardrail {
+ decide(identity: ToolIdentity, input: ToolLaneInput): Promise<ToolGuardrailDecision>
+}
/**
- * Build the tool-lane boundary from the Host guardrails config. Returns
- * `undefined` when no rules are configured — the caller then behaves exactly as
+ * Build the tool-lane guardrail from the Host guardrails config. Returns
+ * `undefined` when no rules are configured — the loop then behaves exactly as
* today (no-config compatibility, spec §5).
*
* Compilation throws on a malformed rule set (spec §3/§5); the caller must
@@ -38,13 +41,13 @@ export type ToolLaneBoundary = GuardrailBoundary<ToolLaneInput, ToolLaneResult,
* 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(
+export function buildToolLaneGuardrail(
config: GuardrailsConfig | undefined
-): ToolLaneBoundary | undefined {
+): ToolLaneGuardrail | undefined {
const compiled = compileRules(config?.rules, config?.limits?.maxRules)
if (!compiled.hasRules) return undefined
- return createGuardrailBoundary<ToolLaneInput, ToolLaneResult, ToolIdentity>({
+ const deps: CoreBoundaryDeps<ToolLaneInput, ToolLaneResult, ToolIdentity> = {
lane: 'tool',
hasRules: compiled.hasRules,
contributors: {
@@ -52,9 +55,20 @@ export function buildToolLaneBoundary(
return evaluateRules(compiled, identity, input)
},
async post() {
- // Phase 1: no post transforms on the tool lane (PostToolUse = Phase 3).
- return []
+ return [] // Phase 1: no tool-lane post transforms (PostToolUse = Phase 3).
},
},
- })
+ }
+
+ return {
+ async decide(identity, input) {
+ const e = await evaluateBoundary(deps, identity, input)
+ return {
+ decision: e.decision,
+ reasonCode: e.reasonCode,
+ effectiveInput: e.effectiveInput,
+ source: e.source,
+ }
+ },
+ }
}
diff --git a/mcp-host/src/core/orchestration/__tests__/guardrailGate.test.ts b/mcp-host/src/core/orchestration/__tests__/guardrailGate.test.ts
new file mode 100644
index 000000000..f13c622d6
--- /dev/null
+++ b/mcp-host/src/core/orchestration/__tests__/guardrailGate.test.ts
@@ -0,0 +1,158 @@
+/**
+ * Tool-lane guardrail gate wiring in executeToolCalls (spec §6). Verifies the
+ * loop acts on the guardrail decision: deny → bounded error (no execution), ask
+ * → suspension (resume-safe via one-shot approval), allow → execution. When
+ * `config.guardrails` is unset the gate is inert (covered by the existing
+ * tool-loop suite).
+ */
+import { describe, expect, it } from 'vitest'
+import type { Decision, ToolLaneGuardrail } from '../../guardrails'
+import type { AgentEventEmitter, Safety, Tool, ToolRegistry } from '../../interfaces'
+import type { Conversation, ToolCall, ToolDefinition, ToolOutput } from '../../types'
+import type { LoopConfig } from '../loopConfig'
+import { executeToolCalls } from '../toolUseLoopToolBatch'
+
+class StubTool implements Tool {
+ public calls: Record<string, unknown>[] = []
+ constructor(private readonly _name: string) {}
+ name(): string {
+ return this._name
+ }
+ description(): string {
+ return `${this._name} desc`
+ }
+ parametersSchema(): Record<string, unknown> {
+ return { type: 'object', properties: {} }
+ }
+ requiresSanitization(): boolean {
+ return false
+ }
+ requiresApproval(): boolean {
+ return false
+ }
+ async execute(params: Record<string, unknown>): Promise<ToolOutput> {
+ this.calls.push(params)
+ return { content: 'ok', duration_ms: 1, is_error: false }
+ }
+}
+
+function registry(tools: Record<string, Tool>): ToolRegistry {
+ return {
+ get: name => tools[name] ?? null,
+ listDefinitions: (): ToolDefinition[] => [],
+ register: () => {},
+ }
+}
+
+const noopEvents: AgentEventEmitter = { emit: () => {}, on: () => {}, off: () => {} }
+const noopSafety: Safety = {
+ validateInput: () => ({ is_valid: true, errors: [] }),
+ validateToolParams: () => ({ is_valid: true, errors: [] }),
+ sanitizeOutput: (_n, output) => ({ content: output, was_modified: false, warnings: [] }),
+ wrapForLlm: (_n, content) => content,
+}
+
+function fixedGuardrail(decision: Decision, reasonCode = 'r'): ToolLaneGuardrail {
+ return {
+ async decide(_id, input) {
+ return { decision, reasonCode, effectiveInput: input, source: 'host_rule' }
+ },
+ }
+}
+
+function makeConfig(
+ tool: StubTool,
+ guardrails: ToolLaneGuardrail | undefined,
+ conversation: Partial<Conversation> = {}
+): LoopConfig {
+ return {
+ reasoning: {} as never,
+ toolRegistry: registry({ [tool.name()]: tool }),
+ safety: noopSafety,
+ events: noopEvents,
+ conversation: {
+ pending_approval: undefined,
+ auto_approved_tools: new Set<string>(),
+ ...conversation,
+ } as Conversation,
+ loopController: {
+ shouldAccept: () => true,
+ onTextRejected: () => null,
+ beforeTool: () => 'proceed',
+ onExhaustion: () => '',
+ refreshTools: async t => t,
+ },
+ contextManager: {} as never,
+ toolOutputProcessor: {
+ beforeExecution: () => ({ is_valid: true, errors: [] }),
+ afterExecution: (_n, out) => out.content,
+ },
+ guardrails,
+ maxIterations: 10,
+ toolTimeout: 5000,
+ toolProgressInterval: 0,
+ }
+}
+
+const call: ToolCall = { id: 'c1', name: 'do_thing', arguments: { a: 1 } }
+
+describe('guardrail gate in executeToolCalls', () => {
+ it('deny → bounded error result, tool never executes', async () => {
+ const tool = new StubTool('do_thing')
+ const { toolResults, pendingApproval } = await executeToolCalls(
+ [call],
+ makeConfig(tool, fixedGuardrail('deny', 'path_out_of_bounds')),
+ 0
+ )
+ expect(pendingApproval).toBeUndefined()
+ expect(toolResults[0].is_error).toBe(true)
+ expect(toolResults[0].content).toContain('path_out_of_bounds')
+ expect(tool.calls).toHaveLength(0)
+ })
+
+ it('allow → tool executes', async () => {
+ const tool = new StubTool('do_thing')
+ const { toolResults } = await executeToolCalls(
+ [call],
+ makeConfig(tool, fixedGuardrail('allow')),
+ 0
+ )
+ expect(toolResults[0].is_error).toBe(false)
+ expect(tool.calls).toHaveLength(1)
+ })
+
+ it('no_decision → falls through to the existing path and executes', async () => {
+ const tool = new StubTool('do_thing')
+ const { toolResults } = await executeToolCalls(
+ [call],
+ makeConfig(tool, fixedGuardrail('no_decision')),
+ 0
+ )
+ expect(toolResults[0].is_error).toBe(false)
+ expect(tool.calls).toHaveLength(1)
+ })
+
+ it('ask (no prior approval) → suspension, tool does not execute', async () => {
+ const tool = new StubTool('do_thing')
+ const { pendingApproval } = await executeToolCalls(
+ [call],
+ makeConfig(tool, fixedGuardrail('ask', 'needs_ok')),
+ 0
+ )
+ expect(pendingApproval).toBeDefined()
+ expect(pendingApproval?.tool_name).toBe('do_thing')
+ expect(tool.calls).toHaveLength(0)
+ })
+
+ it('ask + matching one-shot approval → proceeds and clears pending', async () => {
+ const tool = new StubTool('do_thing')
+ const conversation: Partial<Conversation> = {
+ pending_approval: { tool_name: 'do_thing' } as Conversation['pending_approval'],
+ }
+ const config = makeConfig(tool, fixedGuardrail('ask'), conversation)
+ const { pendingApproval } = await executeToolCalls([call], config, 0)
+ expect(pendingApproval).toBeUndefined()
+ expect(tool.calls).toHaveLength(1)
+ expect(config.conversation.pending_approval).toBeUndefined()
+ })
+})
diff --git a/mcp-host/src/core/orchestration/loopConfig.ts b/mcp-host/src/core/orchestration/loopConfig.ts
index 5f38ebecd..1c245a30a 100644
--- a/mcp-host/src/core/orchestration/loopConfig.ts
+++ b/mcp-host/src/core/orchestration/loopConfig.ts
@@ -1,6 +1,6 @@
import type { TaskBrakeConfig } from '../../budget/taskBrake'
import type { ProgressReporter } from '../../progress/types.js'
-import type { ToolLaneBoundary } from '../guardrails'
+import type { ToolLaneGuardrail } from '../guardrails'
import {
AgentEventEmitter,
ContextManageOptions,
@@ -42,11 +42,12 @@ export interface LoopConfig {
toolOutputProcessor: ToolOutputProcessor
/**
- * Tool-lane guardrail boundary (spec §6). Absent = no guardrails configured =
- * today's behavior (no-config compatibility, spec §5). Phase 1 scaffold: the
- * live gate in `executeToolCalls` is not yet wired — see `toolLaneAdapter.ts`.
+ * Tool-lane guardrail (spec §6). Absent = no guardrails configured = today's
+ * behavior (no-config compatibility, spec §5). Consulted in `executeToolCalls`
+ * before approval/execution: deny → bounded error, ask → suspension,
+ * allow/no_decision → the existing approval path.
*/
- guardrails?: ToolLaneBoundary
+ guardrails?: ToolLaneGuardrail
// Progress reporting
progressReporter?: ProgressReporter
diff --git a/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts b/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts
index 01f636e20..d6de8f343 100644
--- a/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts
+++ b/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts
@@ -1,9 +1,37 @@
+import { randomUUID } from 'crypto'
import { extractToolIntent, getDisplayName } from '../../progress/intentExtraction.js'
+import { recordDecision, resolveToolIdentityFromRegistry } from '../guardrails'
import type { ChatMessage, PendingApproval, TokenUsage, ToolCall, ToolResult } from '../types'
import type { LoopConfig } from './loopConfig'
import { executeSingleTool, reportToolComplete, reportToolStart } from './toolUseLoopSingleTool'
import { isWorkflowTriggerNotFoundToolResult } from './toolUseLoopWorkflowTriggerFallbacks'
+/**
+ * Build a guardrail-originated approval suspension (spec §6.3), shaped like the
+ * existing approval gate so the batch loop's suspend path handles it unchanged.
+ */
+function buildGuardrailSuspension(
+ call: ToolCall,
+ config: LoopConfig,
+ reasonCode: string
+): { type: 'suspend'; approval: PendingApproval } {
+ const descriptor = config.toolRegistry.get(call.name)?.traceDescriptor?.(call.arguments) ?? {
+ kind: 'internal_tool' as const,
+ sourceRef: 'mcp-host',
+ }
+ const approval: PendingApproval = {
+ request_id: randomUUID(),
+ tool_name: call.name,
+ tool_kind: descriptor.kind,
+ tool_source_ref: descriptor.sourceRef,
+ parameters: call.arguments,
+ description: `Guardrail requires approval (${reasonCode})`,
+ tool_call_id: '', // filled below from call.id
+ context_snapshot: [],
+ }
+ return { type: 'suspend', approval }
+}
+
/** The 3 dynamic-tool-loading bridge tools. They are native and must never be
* the TARGET of `clerum__tool_call` (LOCKED #11 — no recursion). */
const BRIDGE_TOOL_NAMES = new Set([
@@ -204,7 +232,67 @@ export async function executeToolCalls(
continue
}
- const gate = loopController.beforeTool(call.name, call.arguments)
+ // Guardrail gate (spec §6) — behind config.guardrails; absent = today.
+ let gate: 'proceed' | 'skip' | { type: 'suspend'; approval: PendingApproval }
+ if (config.guardrails) {
+ const identity = resolveToolIdentityFromRegistry(
+ call.name,
+ config.toolRegistry,
+ call.arguments
+ )
+ const gd = await config.guardrails.decide(identity, call.arguments)
+ events.emit({
+ type: 'guardrail:decision',
+ data: {
+ toolName: call.name,
+ decision: gd.decision,
+ reasonCode: gd.reasonCode,
+ source: gd.source,
+ iteration,
+ },
+ timestamp: new Date(),
+ })
+
+ if (gd.decision === 'deny') {
+ recordDecision('tool', 'deny', gd.source, 'denied', gd.reasonCode)
+ toolResults.push({
+ tool_call_id: call.id,
+ name: call.name,
+ content: `Blocked by guardrail policy (${gd.reasonCode}).`,
+ is_error: true,
+ })
+ continue
+ }
+
+ // Apply any honored rewrite (Phase 1 rules never rewrite; forward-compatible).
+ if (gd.effectiveInput !== call.arguments) {
+ call = { ...call, arguments: gd.effectiveInput }
+ }
+
+ if (gd.decision === 'ask') {
+ // Resume-safe one-shot: an exact approve-once grant satisfies the ask
+ // (spec §6.3). Broad `auto_approved_tools` do NOT — an explicit guardrail
+ // ask needs an exact approval, so we only consume the pending_approval.
+ const pending = config.conversation.pending_approval
+ if (pending && pending.tool_name === call.name) {
+ config.conversation.pending_approval = undefined
+ recordDecision('tool', 'ask', gd.source, 'executed', gd.reasonCode)
+ gate = 'proceed'
+ } else {
+ recordDecision('tool', 'ask', gd.source, 'ask', gd.reasonCode)
+ gate = buildGuardrailSuspension(call, config, gd.reasonCode)
+ }
+ } else {
+ // allow / no_decision → the existing approval path. Phase 1: guardrail
+ // `allow` does NOT bypass existing approvals (separating containment from
+ // approval is deferred — the safe direction).
+ recordDecision('tool', gd.decision, gd.source, 'executed', gd.reasonCode)
+ gate = loopController.beforeTool(call.name, call.arguments)
+ }
+ } else {
+ gate = loopController.beforeTool(call.name, call.arguments)
+ }
+
if (gate === 'skip') {
toolResults.push({
tool_call_id: call.id,