Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(guardrails): scaffold phase 1 in-process engine + tool-lane adapter
Andy Pavia2185bb024918
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 1d99f9891..365674759 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.231",+ "version": "0.1.232","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.231",+ "version": "0.1.232","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 5af75af7b..92d6ef984 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.231",+ "version": "0.1.232","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.tsnew file mode 100644index 000000000..44de0df81--- /dev/null+++ b/mcp-host/src/core/guardrails/__tests__/boundary.test.ts@@ -0,0 +1,29 @@+/**+ * 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`.+ */+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)')+})diff --git a/mcp-host/src/core/guardrails/__tests__/decision.test.ts b/mcp-host/src/core/guardrails/__tests__/decision.test.tsnew file mode 100644index 000000000..6fb7f5992--- /dev/null+++ b/mcp-host/src/core/guardrails/__tests__/decision.test.ts@@ -0,0 +1,86 @@+/**+ * Decision algebra tests (spec §3). The algebra is pure + fully implemented in+ * Phase 1, so this is real coverage — not a skeleton.+ */+import { describe, expect, it } from 'vitest'+import {+ aggregateDecision,+ atLeastAsStrict,+ pickPresentationReason,+ stricter,+ unmatchedDefault,+} from '../decision'+import type { Contributor, Decision } from '../types'++function c(+ decision: Decision,+ source: Contributor<unknown, unknown>['source'],+ sourceId: string,+ reasonCode: string+): Contributor<unknown, unknown> {+ return { phase: 'pre', source, sourceId, decision, reasonCode }+}++describe('strictness order (deny > ask > allow > no_decision)', () => {+ it('ranks stricter() correctly', () => {+ expect(stricter('allow', 'deny')).toBe('deny')+ expect(stricter('ask', 'allow')).toBe('ask')+ expect(stricter('no_decision', 'allow')).toBe('allow')+ expect(stricter('deny', 'ask')).toBe('deny')+ })++ it('atLeastAsStrict() is a total order', () => {+ expect(atLeastAsStrict('deny', 'ask')).toBe(true)+ expect(atLeastAsStrict('allow', 'ask')).toBe(false)+ expect(atLeastAsStrict('allow', 'allow')).toBe(true)+ })+})++describe('aggregateDecision', () => {+ it('empty set → no_decision', () => {+ expect(aggregateDecision([])).toBe('no_decision')+ })++ it('returns the strictest contribution regardless of array order', () => {+ const contribs = [+ c('allow', 'host_rule', 'a', 'ok'),+ c('deny', 'host_rule', 'b', 'blocked'),+ c('ask', 'host_rule', 'c', 'confirm'),+ ]+ expect(aggregateDecision(contribs)).toBe('deny')+ expect(aggregateDecision([...contribs].reverse())).toBe('deny')+ })++ it('a single allow does not override a deny', () => {+ expect(+ aggregateDecision([c('deny', 'admin_rule', 'x', 'r'), c('allow', 'hook', 'y', 'r')])+ ).toBe('deny')+ })+})++describe('unmatchedDefault (spec §3)', () => {+ it('non-empty rule set → ask; absent → no_decision', () => {+ expect(unmatchedDefault(true)).toBe('ask')+ expect(unmatchedDefault(false)).toBe('no_decision')+ })+})++describe('pickPresentationReason (tie-break — presentation only)', () => {+ it('prefers admin_rule over hook/host_rule for the winning decision', () => {+ const contribs = [+ c('deny', 'host_rule', 'h', 'host_reason'),+ c('deny', 'admin_rule', 'a', 'admin_reason'),+ c('allow', 'hook', 'z', 'ignored'),+ ]+ expect(pickPresentationReason(contribs, 'deny')).toBe('admin_reason')+ })++ it('breaks ties within a source by lexical sourceId', () => {+ const contribs = [c('deny', 'hook', 'b', 'reason_b'), c('deny', 'hook', 'a', 'reason_a')]+ expect(pickPresentationReason(contribs, 'deny')).toBe('reason_a')+ })++ it('returns undefined when no contribution carries the decision', () => {+ expect(pickPresentationReason([c('allow', 'hook', 'a', 'r')], 'deny')).toBeUndefined()+ })+})diff --git a/mcp-host/src/core/guardrails/boundary.ts b/mcp-host/src/core/guardrails/boundary.tsnew file mode 100644index 000000000..99ab59d71--- /dev/null+++ b/mcp-host/src/core/guardrails/boundary.ts@@ -0,0 +1,43 @@+/**+ * The lane-neutral GuardrailBoundary engine (spec §2, §4).+ *+ * 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.+ */+import { aggregateDecision, pickPresentationReason } from './decision'+import type { BoundaryOutcome, Contributors, GuardrailBoundary } from './types'++export interface CoreBoundaryDeps<Input, Result, Identity> {+ lane: 'tool' | 'llm'+ contributors: Contributors<Input, Result, Identity>+ /** Whether a non-empty rule set exists (drives the unmatched default, spec §3). */+ 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.+ */+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)')+ },+ }+}diff --git a/mcp-host/src/core/guardrails/capabilities.ts b/mcp-host/src/core/guardrails/capabilities.tsnew file mode 100644index 000000000..31bbca2fb--- /dev/null+++ b/mcp-host/src/core/guardrails/capabilities.ts@@ -0,0 +1,44 @@+/**+ * Capability set + enforcement helpers (spec §4.3, §8.1).+ *+ * A hook's powers beyond its default `allow` are admin-granted capabilities,+ * enforced on the hook RESPONSE (not merely declared): an ungranted action is+ * discarded. Phase 1 defines the set + the ceiling check; response enforcement+ * over the `/v1` protocol lands with the hook adapter in Phase 3.+ */+import type { Capability, Contributor } from './types'++export const ALL_CAPABILITIES: readonly Capability[] = [+ 'may_deny',+ 'may_rewrite',+ 'may_substitute_result',+ 'may_add_context',+]++/** Whether `granted` covers `needed` (per-hook grant ⊆ capabilityCeiling — spec §5). */+export function withinCeiling(+ granted: readonly Capability[],+ ceiling: readonly Capability[]+): boolean {+ return granted.every(c => ceiling.includes(c))+}++/**+ * Neutralize any action a contribution took without the matching capability+ * (spec §8.1): a `deny` without `may_deny` downgrades to `no_decision`; an+ * unhonored `rewrite`/`substitute` is dropped.+ *+ * TODO(phase1/3): full response-capability enforcement + audit of dropped+ * actions lives in the hook adapter; this is the pure downgrade helper.+ */+export function enforceCapabilities<I, R>(+ contribution: Contributor<I, R>,+ granted: readonly Capability[]+): Contributor<I, R> {+ const out: Contributor<I, R> = { ...contribution }+ if (out.decision === 'deny' && !granted.includes('may_deny')) out.decision = 'no_decision'+ if (out.rewrite !== undefined && !granted.includes('may_rewrite')) delete out.rewrite+ if (out.substitute !== undefined && !granted.includes('may_substitute_result'))+ delete out.substitute+ return out+}diff --git a/mcp-host/src/core/guardrails/config.ts b/mcp-host/src/core/guardrails/config.tsnew file mode 100644index 000000000..9f3abd903--- /dev/null+++ b/mcp-host/src/core/guardrails/config.ts@@ -0,0 +1,49 @@+/**+ * `Host.spec.guardrails` config block (spec §5).+ *+ * mcp-host CONSUMES this block; the CRD schema is owned by the CRD chart. Kept+ * additive and loosely typed where Phase 1 does not yet interpret a field+ * (hooks/builtins land in Phases 2–3). Absent/empty = no guardrails =+ * byte-identical to today (no-config compatibility, spec §5).+ *+ * TODO(phase1): parse + validate (limits, predicate admission) — see spec §5/§6.1.+ */+import type { Capability } from './types'++/** A single permission rule item (spec §6.1). Predicate shapes: spec §6.1. */+export interface GuardrailRule {+ id: string+ action: 'allow' | 'ask' | 'deny'+ reasonCode?: string+ match: {+ tool: { provenance: 'native' | 'mcp'; server?: string; name?: string }+ arguments?: Array<{+ type: 'path' | 'url' | 'command' | 'json'+ pointer: string+ op: string+ value?: unknown+ }>+ }+}++/** Engine limits (spec §5). */+export interface GuardrailLimits {+ maxRules?: number+ maxHooksPerPhase?: number+ maxHookTimeoutMs?: number+ maxHookOutputBytes?: number+}++/**+ * The whole admin-authored block. `hooks`/`builtins` are RAW here — Phase 1 does+ * not interpret them (installed hooks = Phase 3, built-ins = Phase 2).+ */+export interface GuardrailsConfig {+ rules?: GuardrailRule[]+ hooks?: Record<string, unknown>+ builtins?: unknown[]+ minInstalledHookTrustLevel?: 'low' | 'mid' | 'high'+ approvalPolicies?: string[]+ capabilityCeiling?: Capability[]+ limits?: GuardrailLimits+}diff --git a/mcp-host/src/core/guardrails/decision.ts b/mcp-host/src/core/guardrails/decision.tsnew file mode 100644index 000000000..70409cc63--- /dev/null+++ b/mcp-host/src/core/guardrails/decision.ts@@ -0,0 +1,82 @@+/**+ * Decision algebra & aggregation (spec §3).+ *+ * Pure, lane-neutral, fully implemented in Phase 1. Strictness order is+ * `deny > ask > allow > no_decision`; the boundary outcome is the strictest+ * contribution, and every contribution is retained by the caller for audit.+ */+import type { Contributor, ContributorSource, Decision } from './types'++/** Strictness rank: higher = stricter (spec §3). */+const RANK: Record<Decision, number> = {+ deny: 3,+ ask: 2,+ allow: 1,+ no_decision: 0,+}++/** True if `a` is at least as strict as `b`. */+export function atLeastAsStrict(a: Decision, b: Decision): boolean {+ return RANK[a] >= RANK[b]+}++/** The stricter of two decisions. */+export function stricter(a: Decision, b: Decision): Decision {+ return RANK[a] >= RANK[b] ? a : b+}++/**+ * Aggregate contributions to the strictest decision (spec §3).+ * Empty set → `no_decision`.+ */+export function aggregateDecision<I, R>(contributions: ReadonlyArray<Contributor<I, R>>): Decision {+ let outcome: Decision = 'no_decision'+ for (const c of contributions) outcome = stricter(outcome, c.decision)+ return outcome+}++/**+ * The unmatched-default for a lane (spec §3): a non-empty rule set contributes+ * `ask` when nothing matched; an entirely absent guardrail config contributes+ * `no_decision` (no-config compatibility — spec §5).+ */+export function unmatchedDefault(hasRules: boolean): Decision {+ return hasRules ? 'ask' : 'no_decision'+}++/**+ * Presentation tie-break source order (spec §3). Selects which reason to show+ * for a metric/model-facing result — NEVER severity.+ */+const SOURCE_ORDER: ContributorSource[] = [+ 'admin_rule',+ 'hook',+ 'host_rule',+ 'validator',+ 'current',+]++function sourceRank(s: ContributorSource): number {+ const i = SOURCE_ORDER.indexOf(s)+ return i === -1 ? SOURCE_ORDER.length : i+}++/**+ * Pick the presentation reason code among the contributions that carry the+ * winning `decision` (spec §3): deterministic order admin_rule → hook → host_rule+ * → validator → current, then lexical `sourceId`. Returns undefined when no+ * contribution carries the decision (e.g. an unmatched default).+ */+export function pickPresentationReason<I, R>(+ contributions: ReadonlyArray<Contributor<I, R>>,+ decision: Decision+): string | undefined {+ const matching = contributions.filter(c => c.decision === decision)+ if (matching.length === 0) return undefined+ matching.sort((a, b) => {+ const r = sourceRank(a.source) - sourceRank(b.source)+ if (r !== 0) return r+ return a.sourceId < b.sourceId ? -1 : a.sourceId > b.sourceId ? 1 : 0+ })+ return matching[0].reasonCode+}diff --git a/mcp-host/src/core/guardrails/index.ts b/mcp-host/src/core/guardrails/index.tsnew file mode 100644index 000000000..0d72894ed--- /dev/null+++ b/mcp-host/src/core/guardrails/index.ts@@ -0,0 +1,17 @@+/**+ * 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.+ */+export * from './types'+export * from './decision'+export * from './capabilities'+export { createGuardrailBoundary } from './boundary'+export type { CoreBoundaryDeps } from './boundary'+export type { GuardrailsConfig, GuardrailRule, GuardrailLimits } from './config'+export { buildToolLaneBoundary } from './tool/toolLaneAdapter'+export type { ToolLaneBoundary, ToolLaneInput, ToolLaneResult } from './tool/toolLaneAdapter'+export type { ToolIdentity } from './tool/provenance'+export { guardrailDecisionsTotal, guardrailBoundaryDurationMs } from './metrics'diff --git a/mcp-host/src/core/guardrails/metrics.ts b/mcp-host/src/core/guardrails/metrics.tsnew file mode 100644index 000000000..57003e91a--- /dev/null+++ b/mcp-host/src/core/guardrails/metrics.ts@@ -0,0 +1,54 @@+/**+ * Guardrail engine metrics (spec §9).+ *+ * Fixed-enum labels only — ids/paths/args/free-form reasons/digests are+ * forbidden as labels (spec §9). Follows the idempotent `getOrCreate*` pattern+ * of `usage/governedRunMetrics.ts` so hot-reload/re-import never double-registers.+ */+import { Counter, Histogram, register } from 'prom-client'++function getOrCreateCounter<Label extends string>(options: {+ name: string+ help: string+ labelNames: Label[]+}): Counter<Label> {+ const existing = register.getSingleMetric(options.name)+ if (existing) return existing as Counter<Label>+ return new Counter<Label>({ ...options, registers: [register] })+}++function getOrCreateHistogram<Label extends string>(options: {+ name: string+ help: string+ labelNames: Label[]+ buckets: number[]+}): Histogram<Label> {+ const existing = register.getSingleMetric(options.name)+ if (existing) return existing as Histogram<Label>+ return new Histogram<Label>({ ...options, registers: [register] })+}++/** One count per guarded boundary outcome. Labels are fixed enums only (spec §9). */+export const guardrailDecisionsTotal = getOrCreateCounter({+ name: 'clerum_mcp_host_guardrail_decisions_total',+ help: 'Guardrail boundary outcomes by lane/decision/source/reason.',+ labelNames: [+ 'lane',+ 'decision',+ 'source',+ 'execution_mode',+ 'phase',+ 'outcome',+ 'reason_code',+ ] as const as Array<+ 'lane' | 'decision' | 'source' | 'execution_mode' | 'phase' | 'outcome' | 'reason_code'+ >,+})++/** Wall-clock of one boundary pass (contributors + aggregate), excluding execute. */+export const guardrailBoundaryDurationMs = getOrCreateHistogram({+ name: 'clerum_mcp_host_guardrail_boundary_duration_ms',+ help: 'Guardrail boundary evaluation latency (ms), excluding tool/model execution.',+ labelNames: ['lane'] as const as Array<'lane'>,+ buckets: [1, 5, 10, 25, 50, 100, 250, 500, 1000],+})diff --git a/mcp-host/src/core/guardrails/tool/doomLoop.ts b/mcp-host/src/core/guardrails/tool/doomLoop.tsnew file mode 100644index 000000000..a797c7ac0--- /dev/null+++ b/mcp-host/src/core/guardrails/tool/doomLoop.ts@@ -0,0 +1,34 @@+/**+ * Doom-loop guard (spec §6.4).+ *+ * Within one task, three consecutive identical `(resolved tool, effective-input+ * digest)` calls → `deny (repeated_identical_call)`. Any intervening different+ * tool or input resets the counter; the counter is persisted with task state.+ *+ * This is a best-effort RUNAWAY/cost guard, NOT a security control — alternating+ * calls evade it (spec §6.4 / N12). The tool-lane rules are the real control.+ *+ * TODO(phase1): implement the per-task counter + persistence hook.+ */++const LIMIT = 3++export interface DoomLoopState {+ lastKey?: string+ count: number+}++/**+ * Record a call and report whether it trips the guard. `key` is+ * `hash(resolvedTool + effectiveInputDigest)`.+ *+ * TODO(phase1): wire persistence with task state; this is the pure transition.+ */+export function recordAndCheck(+ state: DoomLoopState,+ key: string+): { tripped: boolean; state: DoomLoopState } {+ const count = state.lastKey === key ? state.count + 1 : 1+ const next: DoomLoopState = { lastKey: key, count }+ return { tripped: count >= LIMIT, state: next }+}diff --git a/mcp-host/src/core/guardrails/tool/predicates.ts b/mcp-host/src/core/guardrails/tool/predicates.tsnew file mode 100644index 000000000..97485fb7c--- /dev/null+++ b/mcp-host/src/core/guardrails/tool/predicates.ts@@ -0,0 +1,45 @@+/**+ * Typed argument predicates for permission rules (spec §6.1).+ *+ * Each predicate names a constrained RFC-6901 JSON Pointer into the tool+ * arguments and a typed operator. Predicates are DEFENSE-IN-DEPTH, not a sandbox+ * (spec §6.1/§12.3): a `command` predicate sees only `argv[0]`, and `path`/`url`+ * are not TOCTOU-safe — authoritative containment is the hard-validator layer.+ *+ * TODO(phase1): implement each `evaluate` with the admission-time constraints+ * (constrained pointers, bounded wildcards `*`/`?` only, canonicalization).+ */++export type PredicateType = 'path' | 'url' | 'command' | 'json'++export interface ArgumentPredicate {+ type: PredicateType+ /** Constrained RFC-6901 JSON Pointer into the arguments. */+ pointer: string+ /** Operator, per `type` (spec §6.1). */+ op: string+ value?: unknown+}++/** Resolve a constrained JSON Pointer against the tool arguments. TODO(phase1). */+export function resolvePointer(_args: Record<string, unknown>, _pointer: string): unknown {+ // TODO(phase1): constrained RFC-6901 resolution; reject invalid/over-depth pointers at admission.+ throw new Error('resolvePointer not yet implemented (Phase 1 scaffold)')+}++/**+ * Evaluate one predicate against the tool arguments.+ *+ * - path — equals | under | outside; normalized, symlink-aware, boundary-safe; prefixes forbidden.+ * - url — scheme_in | host_in | port_in | path_under; parsed + canonicalized (lowercase host,+ * IDN→punycode, trailing-dot stripped); credentials-in-URL rejected (spec §12.4 / F12).+ * - command — executable_is | argv_prefix; structured executable + argv, not a parsed shell string.+ * - json — exists | equals | one_of | contains; size/depth-bounded; key order canonicalized.+ */+export function evaluatePredicate(+ _args: Record<string, unknown>,+ _predicate: ArgumentPredicate+): boolean {+ // TODO(phase1): dispatch on `predicate.type`/`op`; see the per-type notes above.+ throw new Error('evaluatePredicate not yet implemented (Phase 1 scaffold)')+}diff --git a/mcp-host/src/core/guardrails/tool/provenance.ts b/mcp-host/src/core/guardrails/tool/provenance.tsnew file mode 100644index 000000000..5de25f128--- /dev/null+++ b/mcp-host/src/core/guardrails/tool/provenance.ts@@ -0,0 +1,39 @@+/**+ * Tool provenance resolution (spec §6, §6.1).+ *+ * Provenance (`native` vs `mcp`, server + name) comes from the REGISTRY, never+ * inferred from a `__` name pattern. The authoritative MCP server identity is+ * `McpTool.serverName` (via `McpManager`), NOT the `__`-split `sourceRef` that+ * `McpToolAdapter.traceDescriptor()` currently derives.+ *+ * 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'++/** The resolved identity the tool-lane boundary evaluates (spec §6 `ResolvedIdentity`). */+export interface ToolIdentity {+ provenance: 'native' | 'mcp'+ /** MCP server name (registry-authoritative), when provenance is `mcp`. */+ server?: string+ /** The real tool name after any dynamic-bridge resolution. */+ name: string+}++/**+ * Map a registry trace descriptor to a lane identity. `serverName` is passed in+ * from the manager (registry-authoritative), NOT parsed from the tool name.+ *+ * TODO(phase1): wire the real `serverName` source; today `descriptor.sourceRef`+ * for MCP tools is still `__`-derived (see file header).+ */+export function resolveToolIdentity(+ name: string,+ descriptor: ToolTraceDescriptor | undefined,+ serverName?: string+): ToolIdentity {+ if (descriptor?.kind === 'mcp_server_tool') {+ return { provenance: 'mcp', server: serverName ?? descriptor.sourceRef ?? undefined, name }+ }+ return { provenance: 'native', name }+}diff --git a/mcp-host/src/core/guardrails/tool/rules.ts b/mcp-host/src/core/guardrails/tool/rules.tsnew file mode 100644index 000000000..39f88a270--- /dev/null+++ b/mcp-host/src/core/guardrails/tool/rules.ts@@ -0,0 +1,49 @@+/**+ * Permission-rule engine (spec §6.1) — the tool lane's declarative contributors.+ *+ * Matches a resolved tool call on provenance + typed argument predicates and+ * produces `allow`/`ask`/`deny` contributions. All matching rules contribute;+ * array order is NEVER security precedence (the engine aggregates, spec §3).+ * Unmatched default: non-empty rules → `ask`; absent → `no_decision` (spec §3).+ *+ * NOTE (spec §6.1): an `allow` is an affirmative grant over the WHOLE call — a+ * rule that pins only some arguments still permits arbitrary values in the rest.+ *+ * TODO(phase1): implement matching (provenance + predicates) + admission checks.+ */+import type { GuardrailRule } from '../config'+import type { Contributor } from '../types'+import { evaluatePredicate } from './predicates'+import type { ToolIdentity } from './provenance'++/** A rule set compiled + validated at admission (spec §5 limits, §6.1 predicates). */+export interface CompiledRules {+ readonly rules: readonly GuardrailRule[]+ readonly hasRules: boolean+}++/**+ * Compile + validate the raw rules (bounded count/depth, valid pointers, bounded+ * wildcards). Malformed input fails closed at admission (spec §3).+ *+ * TODO(phase1): validation.+ */+export function compileRules(rules: readonly GuardrailRule[] | undefined): CompiledRules {+ return { rules: rules ?? [], hasRules: (rules?.length ?? 0) > 0 }+}++/**+ * Evaluate the compiled rules against a resolved call, returning one `pre`+ * contributor per matching rule.+ *+ * TODO(phase1): match provenance (identity) + all argument predicates; emit+ * `host_rule` contributors with the rule's `action`/`reasonCode`.+ */+export function evaluateRules(+ _compiled: CompiledRules,+ _identity: ToolIdentity,+ _args: Record<string, unknown>+): Array<Contributor<Record<string, unknown>, string>> {+ void evaluatePredicate+ throw new Error('evaluateRules not yet implemented (Phase 1 scaffold)')+}diff --git a/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts b/mcp-host/src/core/guardrails/tool/toolLaneAdapter.tsnew file mode 100644index 000000000..958b233d9--- /dev/null+++ b/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts@@ -0,0 +1,57 @@+/**+ * Tool-lane adapter (spec §6) — specializes the GuardrailBoundary 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).+ */+import { createGuardrailBoundary } from '../boundary'+import type { GuardrailsConfig } from '../config'+import type { GuardrailBoundary } from '../types'+import type { ToolIdentity } from './provenance'+import { compileRules } 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>++/**+ * Build the tool-lane boundary from the Host guardrails config. Returns+ * `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`).+ */+export function buildToolLaneBoundary(+ config: GuardrailsConfig | undefined+): ToolLaneBoundary | undefined {+ const compiled = compileRules(config?.rules)+ 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 post() {+ return []+ },+ },+ })+}diff --git a/mcp-host/src/core/guardrails/types.ts b/mcp-host/src/core/guardrails/types.tsnew file mode 100644index 000000000..9ac64f562--- /dev/null+++ b/mcp-host/src/core/guardrails/types.ts@@ -0,0 +1,91 @@+/**+ * Guardrail engine — lane-neutral core contracts.+ *+ * Spec: docs/features/mcp-host-guardrails/mcp-host-guardrails-spec.md §2–§4.+ * Phase 1 scaffold: these contracts are stable; several implementations are+ * marked TODO(phase1) in sibling files.+ */++/** The four-valued decision (spec §3). Strictness: deny > ask > allow > no_decision. */+export type Decision = 'deny' | 'ask' | 'allow' | 'no_decision'++/** Phase of a contributor (spec §2.1). */+export type ContributorPhase = 'pre' | 'post'++/** Where a contribution came from (spec §2.1). `current` = the existing approval path. */+export type ContributorSource = 'admin_rule' | 'host_rule' | 'hook' | 'validator' | 'current'++/** Admin-granted hook capabilities (spec §4.3). */+export type Capability = 'may_deny' | 'may_rewrite' | 'may_substitute_result' | 'may_add_context'++/**+ * Bounded, redacted audit payload carried by a contribution (spec §2.1).+ * Fields serve different surfaces and MUST NOT be copied across surfaces+ * without explicit redaction (spec §12.4 / F14).+ */+export interface ContributorAudit {+ modelReason?: string+ userReason?: string+ details?: Record<string, unknown>+}++/**+ * The unit every guardrail source produces (spec §2.1). Generic over the lane's+ * `Input` (e.g. tool arguments) and `Result` (e.g. the tool result).+ */+export interface Contributor<Input, Result> {+ phase: ContributorPhase+ source: ContributorSource+ /** Stable configured id. */+ sourceId: string+ decision: Decision+ /** Bounded per-lane reason-code enum (spec §9). */+ reasonCode: string+ /** Full replacement of the input (pre only). Honored only with `may_rewrite`. */+ rewrite?: Input+ /** Caller-visible result substitute. Honored only with `may_substitute_result`. */+ substitute?: Result+ audit?: ContributorAudit+}++/** Outcome of aggregating contributions over one boundary pass (spec §3). */+export interface AggregateOutcome<Input, Result> {+ decision: Decision+ /** The presentation reason code (tie-break for display only — spec §3). */+ reasonCode: string+ /** The effective input after any honored rewrites (spec §4.1). */+ effectiveInput: Input+ /** A gated substitute result, if any (spec §4.3). */+ substitute?: Result+ /** All contributions, retained for audit (spec §3). */+ contributions: Array<Contributor<Input, Result>>+}++/**+ * A source of pre/post contributions for a boundary (rules, hooks, validators).+ * The tool lane supplies a rules-backed implementation (spec §6); Phase 2 adds+ * installed hooks (spec §8).+ */+export interface Contributors<Input, Result, Identity> {+ pre(input: Input, identity: Identity): Promise<Array<Contributor<Input, Result>>>+ post(result: Result, identity: Identity): Promise<Array<Contributor<Input, Result>>>+}++/** What a boundary returns to its caller. */+export type BoundaryOutcome<Result> =+ | { kind: 'executed'; result: Result }+ | { kind: 'denied'; reasonCode: string }+ | { kind: 'ask'; reasonCode: string }++/**+ * The lane-neutral guardrail boundary (spec §2). A lane specializes it over its+ * own `Input`/`Result`/`Identity` types. `execute` runs the guarded call+ * at-most-once (spec §4.2) only when the aggregate permits it.+ */+export interface GuardrailBoundary<Input, Result, Identity> {+ guard(args: {+ identity: Identity+ input: Input+ execute: (effectiveInput: Input) => Promise<Result>+ }): Promise<BoundaryOutcome<Result>>+}diff --git a/mcp-host/src/core/orchestration/loopConfig.ts b/mcp-host/src/core/orchestration/loopConfig.tsindex 1cac6e16e..5f38ebecd 100644--- a/mcp-host/src/core/orchestration/loopConfig.ts+++ b/mcp-host/src/core/orchestration/loopConfig.ts@@ -1,5 +1,6 @@import type { TaskBrakeConfig } from '../../budget/taskBrake'import type { ProgressReporter } from '../../progress/types.js'+import type { ToolLaneBoundary } from '../guardrails'import {AgentEventEmitter,ContextManageOptions,@@ -40,6 +41,13 @@ export interface LoopConfig {contextManager: ContextManagertoolOutputProcessor: 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`.+ */+ guardrails?: ToolLaneBoundary+// Progress reportingprogressReporter?: ProgressReporterdiff --git a/mcp-host/src/core/types.ts b/mcp-host/src/core/types.tsindex 199aa4f1e..d78fdd527 100644--- a/mcp-host/src/core/types.ts+++ b/mcp-host/src/core/types.ts@@ -520,6 +520,7 @@ export type AgentEventType =| 'llm:completed'| 'safety:input_blocked'| 'safety:output_sanitized'+ | 'guardrail:decision'| 'context:compacted'| 'compaction:skipped'| 'compaction:thrashing'diff --git a/mcp-host/src/types.ts b/mcp-host/src/types.tsindex b4642196e..077596793 100644--- a/mcp-host/src/types.ts+++ b/mcp-host/src/types.ts@@ -2,6 +2,7 @@* Shared types for the MCP Host.*/import type { ApprovalConfig } from './core/extensions/approvalTypes'+import type { GuardrailsConfig } from './core/guardrails/config'import type { LlmProvider } from './llm/registryCore'/**@@ -72,6 +73,13 @@ export interface HostSpec {* CR like `spec.model`; hot-reloads with the rest of the spec.*/allowedModels?: HostAllowedModel[]+ /**+ * Guardrails — the admin-authored `Host.spec.guardrails` block (spec §5).+ * mcp-host CONSUMES it; the CRD schema is owned by the CRD chart. Absent/empty+ * = no guardrails = byte-identical to today (no-config compatibility, spec §5).+ * Phase 1: only `rules` + `limits` are interpreted.+ */+ guardrails?: GuardrailsConfig}/**