Skip to content

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

TypeScript

feat(guardrails): wire tool-lane pretooluse installed hooks (phase 3)

Andy Paviaf4fb0ca5ea1f
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 6353d567d..ef637436a 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.243",
+ "version": "0.1.244",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.243",
+ "version": "0.1.244",
"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 03504a1f5..579114d46 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.243",
+ "version": "0.1.244",
"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__/remoteToolHook.test.ts b/mcp-host/src/core/guardrails/hooks/__tests__/remoteToolHook.test.ts
new file mode 100644
index 000000000..9adc3d84d
--- /dev/null
+++ b/mcp-host/src/core/guardrails/hooks/__tests__/remoteToolHook.test.ts
@@ -0,0 +1,82 @@
+/**
+ * RemoteToolHook `/v1` pre_tool_use mapping (spec §6.2/§8.1): capability
+ * enforcement (F4) + fail-posture (§8.6).
+ */
+import { describe, expect, it } from 'vitest'
+import type { ToolIdentity } from '../../tool/provenance'
+import { RemoteToolHook } from '../remoteToolHook'
+import type { HookDescriptor, HookFetcher, HookHttpResult } from '../types'
+
+const desc = (over: Partial<HookDescriptor> = {}): HookDescriptor => ({
+ id: 'th',
+ endpoint: 'http://svc',
+ path: '/',
+ lifecyclePoints: ['pre_tool_use'],
+ capabilities: [],
+ failMode: 'closed',
+ order: 100,
+ ...over,
+})
+
+const fetcher =
+ (result: HookHttpResult): HookFetcher =>
+ async () =>
+ result
+const id: ToolIdentity = { provenance: 'native', name: 'run_command' }
+
+describe('RemoteToolHook.preToolUse', () => {
+ it('deny + may_deny → deny', async () => {
+ const h = new RemoteToolHook(
+ desc({ capabilities: ['may_deny'] }),
+ fetcher({
+ status: 200,
+ body: { decision: 'deny', reasonCode: 'blocked' },
+ unavailable: false,
+ })
+ )
+ const c = await h.preToolUse(id, {})
+ expect(c?.decision).toBe('deny')
+ expect(c?.reasonCode).toBe('blocked')
+ })
+
+ it('deny WITHOUT may_deny → no_decision (F4)', async () => {
+ const h = new RemoteToolHook(
+ desc({ capabilities: [] }),
+ fetcher({ status: 200, body: { decision: 'deny' }, unavailable: false })
+ )
+ expect((await h.preToolUse(id, {}))?.decision).toBe('no_decision')
+ })
+
+ it('updatedInput + may_rewrite → rewrite', async () => {
+ const h = new RemoteToolHook(
+ desc({ capabilities: ['may_rewrite'] }),
+ fetcher({ status: 200, body: { updatedInput: { command: ['ls'] } }, unavailable: false })
+ )
+ const c = await h.preToolUse(id, { command: ['rm', '-rf', '/'] })
+ expect(c?.rewrite).toEqual({ command: ['ls'] })
+ })
+
+ it('updatedInput WITHOUT may_rewrite → dropped (F4)', async () => {
+ const h = new RemoteToolHook(
+ desc({ capabilities: [] }),
+ fetcher({ status: 200, body: { updatedInput: { command: ['ls'] } }, unavailable: false })
+ )
+ expect(await h.preToolUse(id, {})).toBeNull()
+ })
+
+ it('unavailable + closed + may_deny → deny hook_unavailable (§8.6)', async () => {
+ const h = new RemoteToolHook(
+ desc({ capabilities: ['may_deny'], failMode: 'closed' }),
+ fetcher({ status: 0, body: undefined, unavailable: true })
+ )
+ expect((await h.preToolUse(id, {}))?.reasonCode).toBe('hook_unavailable')
+ })
+
+ it('a point the hook does not subscribe to → null', async () => {
+ const h = new RemoteToolHook(
+ desc({ lifecyclePoints: ['moderate'] }),
+ fetcher({ status: 200, body: { decision: 'deny' }, unavailable: false })
+ )
+ expect(await h.preToolUse(id, {})).toBeNull()
+ })
+})
diff --git a/mcp-host/src/core/guardrails/hooks/hookFetcher.ts b/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
index f929be85b..24bf5a3e1 100644
--- a/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
+++ b/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
@@ -33,6 +33,8 @@ const POINT_PATH: Record<LifecyclePoint, string> = {
moderate: 'moderate',
post_call: 'post_call',
on_error: 'on_error',
+ pre_tool_use: 'pre_tool_use',
+ post_tool_use: 'post_tool_use',
}
/** Build `{endpoint}{path}/v1/{point}`, normalizing slashes (spec §8.1). */
diff --git a/mcp-host/src/core/guardrails/hooks/remoteToolHook.ts b/mcp-host/src/core/guardrails/hooks/remoteToolHook.ts
new file mode 100644
index 000000000..0564d13a9
--- /dev/null
+++ b/mcp-host/src/core/guardrails/hooks/remoteToolHook.ts
@@ -0,0 +1,82 @@
+/**
+ * RemoteToolHook (spec §6.2/§8) — calls an installed `PreToolUse` hook over the
+ * `/v1` protocol and maps its response to a tool-lane `Contributor`, enforcing
+ * the response-capability invariant (F4, §8.1): a `deny` from a hook without
+ * `may_deny` downgrades to `no_decision`; an `updatedInput` without `may_rewrite`
+ * is dropped. Fail-posture per `failMode` (§8.6).
+ *
+ * `pre_tool_use` request body = `{ tool, arguments }` (the resolved identity +
+ * args); response = `{ decision?, reasonCode?, updatedInput?, additionalContext? }`.
+ * Phase 3 increment: PreToolUse; PostToolUse (post-execution result transform)
+ * is a later increment.
+ */
+import type { ToolIdentity } from '../tool/provenance'
+import type { Capability, Contributor } from '../types'
+import type { HookDescriptor, HookFetcher } from './types'
+
+type ToolContributor = Contributor<Record<string, unknown>, string>
+
+function isRecord(v: unknown): v is Record<string, unknown> {
+ return !!v && typeof v === 'object'
+}
+
+export class RemoteToolHook {
+ constructor(
+ private readonly descriptor: HookDescriptor,
+ private readonly fetch: HookFetcher
+ ) {}
+
+ private has(cap: Capability): boolean {
+ return this.descriptor.capabilities.includes(cap)
+ }
+
+ private onUnavailable(): ToolContributor | null {
+ if (this.descriptor.failMode === 'closed' && this.has('may_deny')) {
+ return this.contribution('deny', 'hook_unavailable')
+ }
+ return null
+ }
+
+ private contribution(
+ decision: ToolContributor['decision'],
+ reasonCode: string,
+ extra: Partial<ToolContributor> = {}
+ ): ToolContributor {
+ return {
+ phase: 'pre',
+ source: 'hook',
+ sourceId: this.descriptor.id,
+ decision,
+ reasonCode,
+ ...extra,
+ }
+ }
+
+ /** `pre_tool_use` (spec §6.2): deny → deny (gated), updatedInput → rewrite (gated), else allow. */
+ async preToolUse(
+ identity: ToolIdentity,
+ args: Record<string, unknown>
+ ): Promise<ToolContributor | null> {
+ if (!this.descriptor.lifecyclePoints.includes('pre_tool_use')) return null
+ const res = await this.fetch({
+ point: 'pre_tool_use',
+ descriptor: this.descriptor,
+ body: { tool: identity, arguments: args },
+ })
+ // §8.1: non-200 or unavailable → fail-mode (never a silent allow).
+ if (res.unavailable || res.status !== 200) return this.onUnavailable()
+
+ const body = isRecord(res.body) ? res.body : {}
+ if (body.decision === 'deny') {
+ const decision = this.has('may_deny') ? 'deny' : 'no_decision'
+ return this.contribution(decision, String(body.reasonCode ?? 'hook_denied'), {
+ audit: { modelReason: typeof body.reasonCode === 'string' ? body.reasonCode : undefined },
+ })
+ }
+ // updatedInput = full args replacement; only honored with may_rewrite (F4).
+ if (isRecord(body.updatedInput) && this.has('may_rewrite')) {
+ return this.contribution('allow', 'hook_rewrite', { rewrite: body.updatedInput })
+ }
+ return null // allow / no honored action → no contribution.
+ }
+}
diff --git a/mcp-host/src/core/guardrails/hooks/types.ts b/mcp-host/src/core/guardrails/hooks/types.ts
index 15fa7b58f..080dc7c72 100644
--- a/mcp-host/src/core/guardrails/hooks/types.ts
+++ b/mcp-host/src/core/guardrails/hooks/types.ts
@@ -9,8 +9,14 @@
*/
import type { Capability } from '../types'
-/** The four `/v1` lifecycle endpoints (spec §8.1). */
-export type LifecyclePoint = 'pre_call' | 'moderate' | 'post_call' | 'on_error'
+/** The `/v1` lifecycle endpoints (spec §8.1) — LLM lane + tool lane. */
+export type LifecyclePoint =
+ | 'pre_call'
+ | 'moderate'
+ | 'post_call'
+ | 'on_error'
+ | 'pre_tool_use'
+ | 'post_tool_use'
/** A resolved installed hook: its endpoint + admin-granted grants (from the LlmHook CR + Host block). */
export interface HookDescriptor {
diff --git a/mcp-host/src/core/guardrails/index.ts b/mcp-host/src/core/guardrails/index.ts
index c53272932..158687bf8 100644
--- a/mcp-host/src/core/guardrails/index.ts
+++ b/mcp-host/src/core/guardrails/index.ts
@@ -30,6 +30,7 @@ export type { PromptShapingConfig } from './llm/builtins/promptShaping'
export { applyTokenTrim } from './llm/builtins/tokenTrim'
export type { TokenTrimConfig } from './llm/builtins/tokenTrim'
export { RemoteLlmHook } from './hooks/remoteLlmHook'
+export { RemoteToolHook } from './hooks/remoteToolHook'
export type { HookDescriptor, HookFetcher, HookHttpResult, LifecyclePoint } from './hooks/types'
export { buildHookUrl, createHookFetcher } from './hooks/hookFetcher'
export type { FetchLike, HookFetcherDeps } from './hooks/hookFetcher'
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 726600e00..f39ed566e 100644
--- a/mcp-host/src/core/guardrails/tool/__tests__/toolLaneAdapter.test.ts
+++ b/mcp-host/src/core/guardrails/tool/__tests__/toolLaneAdapter.test.ts
@@ -41,6 +41,33 @@ describe('buildToolLaneGuardrail', () => {
expect(d.decision).toBe('ask')
})
+ it('a PreToolUse installed hook can deny (no rules needed)', async () => {
+ const fetchImpl = async (url: string) => ({
+ status: 200,
+ text: async () =>
+ url.endsWith('/v1/pre_tool_use') ? '{"decision":"deny","reasonCode":"hook_blocked"}' : '{}',
+ })
+ const g = buildToolLaneGuardrail(
+ {
+ hookDescriptors: [
+ {
+ id: 'th',
+ endpoint: 'http://svc',
+ path: '/',
+ lifecyclePoints: ['pre_tool_use'],
+ capabilities: ['may_deny'],
+ failMode: 'closed',
+ order: 100,
+ },
+ ],
+ },
+ { getAuthToken: () => '', fetchImpl }
+ )!
+ const d = await g.decide(fileWrite, { path: '/etc/passwd' })
+ expect(d.decision).toBe('deny')
+ expect(d.reasonCode).toBe('hook_blocked')
+ })
+
it('an allow rule → allow', async () => {
const g = buildToolLaneGuardrail({
rules: [
diff --git a/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts b/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts
index 9d89d84e8..742c0aa79 100644
--- a/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts
+++ b/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts
@@ -10,10 +10,39 @@
*/
import { type CoreBoundaryDeps, evaluateBoundary } from '../boundary'
import type { GuardrailsConfig } from '../config'
-import type { Decision } from '../types'
+import { type FetchLike, createHookFetcher } from '../hooks/hookFetcher'
+import { RemoteToolHook } from '../hooks/remoteToolHook'
+import type { HookDescriptor } from '../hooks/types'
+import type { Contributor, Decision } from '../types'
import type { ToolIdentity } from './provenance'
import { compileRules, evaluateRules } from './rules'
+export interface ToolLaneGuardrailDeps {
+ getAuthToken?: () => string
+ fetchImpl?: FetchLike
+}
+
+/** Build the tool-lane installed `PreToolUse` hooks (spec §6.2), ordered by `order`. */
+function buildToolLaneHooks(
+ descriptors: HookDescriptor[] | undefined,
+ deps: ToolLaneGuardrailDeps
+): RemoteToolHook[] {
+ return (descriptors ?? [])
+ .slice()
+ .sort((a, b) => a.order - b.order)
+ .filter(d => d.lifecyclePoints.includes('pre_tool_use'))
+ .map(
+ d =>
+ new RemoteToolHook(
+ d,
+ createHookFetcher({
+ getAuthToken: deps.getAuthToken ?? (() => ''),
+ fetchImpl: deps.fetchImpl,
+ })
+ )
+ )
+}
+
export type ToolLaneInput = Record<string, unknown>
export type ToolLaneResult = string
@@ -42,20 +71,26 @@ export interface ToolLaneGuardrail {
* gate is wired with per-task state.
*/
export function buildToolLaneGuardrail(
- config: GuardrailsConfig | undefined
+ config: GuardrailsConfig | undefined,
+ hookDeps: ToolLaneGuardrailDeps = {}
): ToolLaneGuardrail | undefined {
const compiled = compileRules(config?.rules, config?.limits?.maxRules)
- if (!compiled.hasRules) return undefined
+ const hooks = buildToolLaneHooks(config?.hookDescriptors, hookDeps)
+ if (!compiled.hasRules && hooks.length === 0) return undefined
const deps: CoreBoundaryDeps<ToolLaneInput, ToolLaneResult, ToolIdentity> = {
lane: 'tool',
- hasRules: compiled.hasRules,
+ hasRules: compiled.hasRules, // unmatched default keys on RULES; a hook returning null is just no opinion.
contributors: {
async pre(input, identity) {
- return evaluateRules(compiled, identity, input)
+ const ruleContribs = evaluateRules(compiled, identity, input)
+ const hookContribs = (
+ await Promise.all(hooks.map(h => h.preToolUse(identity, input)))
+ ).filter((c): c is Contributor<ToolLaneInput, ToolLaneResult> => c !== null)
+ return [...ruleContribs, ...hookContribs]
},
async post() {
- return [] // Phase 1: no tool-lane post transforms (PostToolUse = Phase 3).
+ return [] // PostToolUse (post-execution result transform) is a later increment.
},
},
}