Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(guardrails): circuit breaker for advisory llm hooks (§8.6)
Andy Pavia5865158a21ca
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 5cda18368..faa75624d 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.253",+ "version": "0.1.254","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.253",+ "version": "0.1.254","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex a3a56f48a..98be58cfb 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.253",+ "version": "0.1.254","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__/remoteLlmHook.test.ts b/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.tsindex 37d1f2039..60e46dce9 100644--- a/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts+++ b/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts@@ -10,6 +10,7 @@ import {type ToolCompletionRequest,type ToolCompletionResponse,} from '../../../types'+import { HookBreakerRegistry } from '../hookBreaker'import { RemoteLlmHook } from '../remoteLlmHook'import type { HookDescriptor, HookFetcher, HookHttpResult } from '../types'@@ -288,3 +289,92 @@ describe('quarantine (§8.2 digest mismatch → fail-closed, N11)', () => {expect(await h.preCall(req())).toBeNull()})})++describe('circuit breaker (§8.6)', () => {+ // Advisory hook (may_add_context, not may_deny) that opts into breaker mode.+ const advisory = (over: Partial<HookDescriptor> = {}): HookDescriptor =>+ desc({+ capabilities: ['may_add_context'],+ failMode: 'open',+ lifecyclePoints: ['moderate'],+ onUnavailable: { mode: 'breaker', failureThreshold: 3, cooldownMs: 1000 },+ ...over,+ })++ /** A fetcher that counts its dials and returns whatever `getResult` yields. */+ function countingFetcher(getResult: () => HookHttpResult) {+ let calls = 0+ const fetch: HookFetcher = async () => {+ calls += 1+ return getResult()+ }+ return { fetch, calls: () => calls }+ }++ const unavailable: HookHttpResult = { status: 0, body: undefined, unavailable: true }++ it('trips after failureThreshold and stops dialing during cooldown', async () => {+ const reg = new HookBreakerRegistry()+ const cf = countingFetcher(() => unavailable)+ const h = new RemoteLlmHook(advisory(), cf.fetch, reg, () => 0)++ // 3 unavailable dials trip the breaker (each dials the network).+ for (let i = 0; i < 3; i++) expect(await h.moderate(req())).toBeNull()+ expect(cf.calls()).toBe(3)++ // Now open: further calls short-circuit WITHOUT dialing (the resilience win).+ expect(await h.moderate(req())).toBeNull()+ expect(await h.moderate(req())).toBeNull()+ expect(cf.calls()).toBe(3)+ })++ it('re-probes once after cooldown and closes on success', async () => {+ const reg = new HookBreakerRegistry()+ let t = 0+ let healthy = false+ const cf = countingFetcher(() =>+ healthy ? { status: 200, body: {}, unavailable: false } : unavailable+ )+ const h = new RemoteLlmHook(advisory(), cf.fetch, reg, () => t)++ for (let i = 0; i < 3; i++) await h.moderate(req()) // trip+ await h.moderate(req()) // open → no dial+ expect(cf.calls()).toBe(3)++ t = 1000 // cooldown elapsed → half-open: one probe allowed+ healthy = true+ await h.moderate(req())+ expect(cf.calls()).toBe(4)++ await h.moderate(req()) // breaker closed → dials normally again+ expect(cf.calls()).toBe(5)+ })++ it('deny-authoritative (may_deny) hook ignores breaker — always dials strict', async () => {+ const reg = new HookBreakerRegistry()+ const cf = countingFetcher(() => unavailable)+ const h = new RemoteLlmHook(+ advisory({ capabilities: ['may_deny'], failMode: 'closed' }),+ cf.fetch,+ reg,+ () => 0+ )+ for (let i = 0; i < 6; i++) {+ expect((await h.moderate(req()))?.decision).toBe('deny') // fail-closed each time+ }+ expect(cf.calls()).toBe(6) // never short-circuited+ })++ it('strict mode never trips (always dials)', async () => {+ const reg = new HookBreakerRegistry()+ const cf = countingFetcher(() => unavailable)+ const h = new RemoteLlmHook(+ advisory({ onUnavailable: { mode: 'strict', failureThreshold: 3, cooldownMs: 1000 } }),+ cf.fetch,+ reg,+ () => 0+ )+ for (let i = 0; i < 6; i++) await h.moderate(req())+ expect(cf.calls()).toBe(6)+ })+})diff --git a/mcp-host/src/core/guardrails/hooks/hookBreaker.ts b/mcp-host/src/core/guardrails/hooks/hookBreaker.tsnew file mode 100644index 000000000..90422a39d--- /dev/null+++ b/mcp-host/src/core/guardrails/hooks/hookBreaker.ts@@ -0,0 +1,76 @@+/**+ * Per-hook circuit breaker (spec §8.6).+ *+ * `RemoteLlmHook` instances are rebuilt per logical request (the hooked LLM port+ * is wrapped per task), so breaker state cannot live on the instance. It lives+ * here, in a registry keyed by hook identity (endpoint+path), so a hook that is+ * down trips ONCE and every subsequent call across tasks short-circuits without+ * re-paying the timeout — "per-hook, not global" (§8.6): one hook tripping never+ * affects another (different key).+ *+ * State machine (closed → open → half-open → …):+ * - closed: dial normally; each unavailable result increments `failures`.+ * - open: `failures ≥ threshold` set `openUntil = now + cooldownMs`; while+ * `now < openUntil` the caller short-circuits WITHOUT dialing.+ * - half-open: once `openUntil` passes, one probe is allowed through; a success+ * closes the breaker (reset), a failure re-opens it for another+ * cooldown. Because open calls never dial, `failures` only advances+ * on real probe results.+ */+export interface BreakerState {+ /** Consecutive unavailable results (probe failures). Reset to 0 on success. */+ failures: number+ /** Epoch ms until which the breaker is open (short-circuit without dialing). */+ openUntil: number+}++export class HookBreakerRegistry {+ private readonly states = new Map<string, BreakerState>()++ private state(key: string): BreakerState {+ let s = this.states.get(key)+ if (!s) {+ s = { failures: 0, openUntil: 0 }+ this.states.set(key, s)+ }+ return s+ }++ /** True while the breaker is open — the caller must short-circuit, not dial. */+ isOpen(key: string, now: number): boolean {+ return now < this.state(key).openUntil+ }++ /** A reachable response closes the breaker (the hook is healthy again). */+ recordSuccess(key: string): void {+ const s = this.state(key)+ s.failures = 0+ s.openUntil = 0+ }++ /**+ * Record an unavailable probe result. Returns true when THIS failure tripped+ * the breaker open (crossed the threshold from a closed/half-open state), so+ * the caller can emit the §8.6 "alert" exactly once per trip.+ */+ recordFailure(key: string, failureThreshold: number, cooldownMs: number, now: number): boolean {+ const s = this.state(key)+ s.failures += 1+ if (s.failures >= failureThreshold && s.openUntil <= now) {+ s.openUntil = now + cooldownMs+ return true+ }+ return false+ }++ /** Test seam: drop all breaker state. */+ reset(): void {+ this.states.clear()+ }+}++/**+ * Process-shared default registry. The hooked LLM port is rebuilt per task, so a+ * shared registry is what makes a trip survive across requests to the same hook.+ */+export const defaultBreakerRegistry = new HookBreakerRegistry()diff --git a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.tsindex 453c55098..a083b481b 100644--- a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts+++ b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts@@ -26,6 +26,7 @@ import type {ToolCompletionResponse,} from '../../types'import type { Capability, Contributor } from '../types'+import { type HookBreakerRegistry, defaultBreakerRegistry } from './hookBreaker'import type { HookDescriptor, HookFetcher, HookHttpResult, LifecyclePoint } from './types'type LlmContributor = Contributor<ToolCompletionRequest, ToolCompletionResponse>@@ -69,28 +70,75 @@ function filteredPostResponse(usage: ToolCompletionResponse['usage']): ToolComplexport class RemoteLlmHook {constructor(private readonly descriptor: HookDescriptor,- private readonly fetch: HookFetcher+ private readonly fetch: HookFetcher,+ /** Shared so a trip survives the per-task rebuild of this instance (§8.6). */+ private readonly breakers: HookBreakerRegistry = defaultBreakerRegistry,+ /** Injectable clock for deterministic breaker tests. */+ private readonly now: () => number = () => Date.now()) {}private has(cap: Capability): boolean {return this.descriptor.capabilities.includes(cap)}+ /** Identity of the breaker state (per hook pod+path), shared across tasks (§8.6). */+ private breakerKey(): string {+ return `${this.descriptor.endpoint}${this.descriptor.path}`+ }+/**- * Transport with the quarantine gate (§8.2): a quarantined hook (e.g. digest- * mismatch) never reaches the network — every call reports `unavailable`, so- * each point's §8.6 fail-posture applies (deny for a `may_deny`/fail-closed- * hook, no contribution for an advisory one). Never a silent allow.+ * The circuit breaker is honored only for an advisory hook that opted into+ * `breaker` mode (§8.6): a deny-authoritative (`may_deny`) hook always dials+ * strict so it can never be tripped into failing open.*/- private fetchGuarded(args: {+ private breakerEngaged(): boolean {+ return this.descriptor.onUnavailable?.mode === 'breaker' && !this.has('may_deny')+ }++ /**+ * Transport with the quarantine gate (§8.2) and the §8.6 circuit breaker.+ *+ * A quarantined hook (e.g. digest mismatch) never reaches the network — every+ * call reports `unavailable`, so each point's §8.6 fail-posture applies. When a+ * `breaker`-mode advisory hook has tripped, calls likewise short-circuit to+ * `unavailable` WITHOUT dialing for the cooldown window, so a down hook is not+ * re-dialed (and re-timed-out) on every request. Every branch reports+ * `unavailable` — never a silent allow.+ */+ private async fetchGuarded(args: {point: LifecyclePointdescriptor: HookDescriptorbody: unknown}): Promise<HookHttpResult> {if (this.descriptor.quarantined) {- return Promise.resolve({ status: 0, body: undefined, unavailable: true })+ return { status: 0, body: undefined, unavailable: true }+ }+ const engaged = this.breakerEngaged()+ if (engaged && this.breakers.isOpen(this.breakerKey(), this.now())) {+ // Breaker open: skip the dial (and its timeout); report unavailable.+ return { status: 0, body: undefined, unavailable: true }+ }+ const res = await this.fetch(args)+ if (engaged) {+ const policy = this.descriptor.onUnavailable!+ if (res.unavailable) {+ const tripped = this.breakers.recordFailure(+ this.breakerKey(),+ policy.failureThreshold,+ policy.cooldownMs,+ this.now()+ )+ if (tripped) {+ console.warn(+ `[Guardrails] hook ${this.descriptor.id} breaker tripped after ${policy.failureThreshold} failures; ` ++ `failing open for ${policy.cooldownMs}ms`+ )+ }+ } else {+ this.breakers.recordSuccess(this.breakerKey())+ }}- return this.fetch(args)+ return res}private handles(point: LifecyclePoint): boolean {diff --git a/mcp-host/src/core/guardrails/hooks/types.ts b/mcp-host/src/core/guardrails/hooks/types.tsindex a05d78c39..c63a4560e 100644--- a/mcp-host/src/core/guardrails/hooks/types.ts+++ b/mcp-host/src/core/guardrails/hooks/types.ts@@ -31,6 +31,20 @@ export interface HookDescriptor {capabilities: readonly Capability[]/** Fail-posture when the hook is unavailable (spec §8.6). */failMode: 'open' | 'closed'+ /**+ * Circuit-breaker policy (spec §8.6). `strict` (the default) always dials the+ * hook and applies `failMode` on each unavailable result. `breaker` trips a+ * per-hook breaker after `failureThreshold` consecutive unavailable results,+ * short-circuiting to "unavailable" for `cooldownMs` (then a single re-probe)+ * instead of re-paying the timeout on every call. Per §8.6 the breaker is only+ * honored for advisory (non-`may_deny`) hooks; a deny-authoritative hook always+ * dials strict so it can never fail open.+ */+ onUnavailable?: {+ mode: 'strict' | 'breaker'+ failureThreshold: number+ cooldownMs: number+ }order: number/*** True for a `remote` (external) target dialed over the public internet. Suchdiff --git a/mcp-host/src/guardrailHookResolver.ts b/mcp-host/src/guardrailHookResolver.tsindex 69f71daa3..e4e98006a 100644--- a/mcp-host/src/guardrailHookResolver.ts+++ b/mcp-host/src/guardrailHookResolver.ts@@ -156,6 +156,19 @@ export async function resolveGuardrailHookDescriptors(const failMode: 'open' | 'closed' = cr.spec?.failMode === 'open' ? 'open' : 'closed'const order = typeof cr.spec?.order === 'number' ? cr.spec.order : 100+ // §8.6 circuit-breaker policy (CRD defaults: strict / 5 / 30000). `strict`+ // preserves the always-dial behavior; `breaker` is honored at runtime only+ // for advisory (non-may_deny) hooks (RemoteLlmHook.breakerEngaged).+ const ou = cr.spec?.onUnavailable+ const onUnavailable = {+ mode: ou?.mode === 'breaker' ? ('breaker' as const) : ('strict' as const),+ failureThreshold:+ typeof ou?.failureThreshold === 'number' && ou.failureThreshold >= 1+ ? ou.failureThreshold+ : 5,+ cooldownMs: typeof ou?.cooldownMs === 'number' && ou.cooldownMs >= 0 ? ou.cooldownMs : 30000,+ }+// `remote` targets are dialed over the public internet → SSRF-guarded// transport (private/metadata-range reject + DNS-pin). image/service targets// resolve to cluster-private IPs and must bypass that guard.@@ -185,6 +198,7 @@ export async function resolveGuardrailHookDescriptors(lifecyclePoints: points,capabilities,failMode,+ onUnavailable,order,external,...(quarantined ? { quarantined: true } : {}),diff --git a/mcp-host/src/k8sClient.ts b/mcp-host/src/k8sClient.tsindex 04e525479..0a49afd4a 100644--- a/mcp-host/src/k8sClient.ts+++ b/mcp-host/src/k8sClient.ts@@ -40,6 +40,11 @@ export interface LlmHookCR {lifecyclePoints?: string[]order?: numberfailMode?: 'open' | 'closed'+ onUnavailable?: {+ mode?: 'strict' | 'breaker'+ failureThreshold?: number+ cooldownMs?: number+ }capabilities?: string[]}status?: { observedDigest?: string }