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 posttooluse redaction hooks

Andy Pavia3345f29a95ec
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index be772b741..ba135dd08 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.245",
+ "version": "0.1.246",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.245",
+ "version": "0.1.246",
"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 96ac29d9f..0c8c0791f 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.245",
+ "version": "0.1.246",
"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
index 9adc3d84d..a98ea7d8b 100644
--- a/mcp-host/src/core/guardrails/hooks/__tests__/remoteToolHook.test.ts
+++ b/mcp-host/src/core/guardrails/hooks/__tests__/remoteToolHook.test.ts
@@ -80,3 +80,70 @@ describe('RemoteToolHook.preToolUse', () => {
expect(await h.preToolUse(id, {})).toBeNull()
})
})
+
+describe('RemoteToolHook.postToolUse', () => {
+ const result = { content: 'secret=abc123', isError: false }
+
+ it('updatedResult + may_rewrite → redacted content (is_error preserved)', async () => {
+ const h = new RemoteToolHook(
+ desc({ lifecyclePoints: ['post_tool_use'], capabilities: ['may_rewrite'] }),
+ fetcher({
+ status: 200,
+ body: { updatedResult: { content: 'secret=[redacted]' } },
+ unavailable: false,
+ })
+ )
+ const v = await h.postToolUse(id, {}, result)
+ expect(v).toEqual({ content: 'secret=[redacted]', isError: false })
+ })
+
+ it('is_error is authoritative — a hook cannot flip it', async () => {
+ const h = new RemoteToolHook(
+ desc({ lifecyclePoints: ['post_tool_use'], capabilities: ['may_rewrite'] }),
+ fetcher({
+ status: 200,
+ body: { updatedResult: { content: 'x', is_error: true } },
+ unavailable: false,
+ })
+ )
+ const v = await h.postToolUse(id, {}, { content: 'ok', isError: false })
+ expect(v?.isError).toBe(false)
+ })
+
+ it('WITHOUT may_rewrite → no redaction (F4)', async () => {
+ const h = new RemoteToolHook(
+ desc({ lifecyclePoints: ['post_tool_use'], capabilities: [] }),
+ fetcher({ status: 200, body: { updatedResult: { content: 'x' } }, unavailable: false })
+ )
+ expect(await h.postToolUse(id, {}, result)).toBeNull()
+ })
+
+ it('fail-closed + unavailable + may_rewrite → withhold content (§8.6)', async () => {
+ const h = new RemoteToolHook(
+ desc({
+ lifecyclePoints: ['post_tool_use'],
+ capabilities: ['may_rewrite'],
+ failMode: 'closed',
+ }),
+ fetcher({ status: 0, body: undefined, unavailable: true })
+ )
+ const v = await h.postToolUse(id, {}, result)
+ expect(v?.content).not.toContain('abc123')
+ })
+
+ it('fail-open + unavailable → no redaction (original passes through)', async () => {
+ const h = new RemoteToolHook(
+ desc({ lifecyclePoints: ['post_tool_use'], capabilities: ['may_rewrite'], failMode: 'open' }),
+ fetcher({ status: 0, body: undefined, unavailable: true })
+ )
+ expect(await h.postToolUse(id, {}, result)).toBeNull()
+ })
+
+ it('not subscribed to post_tool_use → null', async () => {
+ const h = new RemoteToolHook(
+ desc({ lifecyclePoints: ['pre_tool_use'], capabilities: ['may_rewrite'] }),
+ fetcher({ status: 200, body: { updatedResult: { content: 'x' } }, unavailable: false })
+ )
+ expect(await h.postToolUse(id, {}, result)).toBeNull()
+ })
+})
diff --git a/mcp-host/src/core/guardrails/hooks/remoteToolHook.ts b/mcp-host/src/core/guardrails/hooks/remoteToolHook.ts
index 0564d13a9..c7762963f 100644
--- a/mcp-host/src/core/guardrails/hooks/remoteToolHook.ts
+++ b/mcp-host/src/core/guardrails/hooks/remoteToolHook.ts
@@ -16,6 +16,12 @@ import type { HookDescriptor, HookFetcher } from './types'
type ToolContributor = Contributor<Record<string, unknown>, string>
+/** The model-visible portion of a tool result a `post_tool_use` hook may redact (spec §6.2). */
+export interface ToolResultView {
+ content: string
+ isError: boolean
+}
+
function isRecord(v: unknown): v is Record<string, unknown> {
return !!v && typeof v === 'object'
}
@@ -79,4 +85,48 @@ export class RemoteToolHook {
}
return null // allow / no honored action → no contribution.
}
+
+ /**
+ * `post_tool_use` (spec §6.2 / §10 #3): bounded, model-visible-only REDACTION of
+ * a tool result. Gated by `may_rewrite` — `may_substitute_result` is LLM-lane-only
+ * (§10 #3), so the tool lane rewrites the result `content` rather than substituting
+ * a caller-visible result. `is_error` is preserved (redaction never flips
+ * success/failure). A fail-closed redactor that's unavailable withholds the
+ * un-redacted content (§8.6). Returns the redacted view, or `null` for no change.
+ */
+ async postToolUse(
+ identity: ToolIdentity,
+ args: Record<string, unknown>,
+ result: ToolResultView
+ ): Promise<ToolResultView | null> {
+ if (!this.descriptor.lifecyclePoints.includes('post_tool_use')) return null
+ const res = await this.fetch({
+ point: 'post_tool_use',
+ descriptor: this.descriptor,
+ body: {
+ tool: identity,
+ arguments: args,
+ result: { content: result.content, is_error: result.isError },
+ },
+ })
+ // §8.6: a fail-closed redactor that can't run must NOT leak the un-redacted result.
+ if (res.unavailable || res.status !== 200) {
+ if (this.descriptor.failMode === 'closed' && this.has('may_rewrite')) {
+ return {
+ content: 'This tool result was withheld by a content guardrail policy.',
+ isError: result.isError,
+ }
+ }
+ return null
+ }
+
+ const body = isRecord(res.body) ? res.body : {}
+ const patched = isRecord(body.updatedResult) ? body.updatedResult : undefined
+ if (!patched || !this.has('may_rewrite')) return null
+ // Redaction is content-only; is_error stays authoritative.
+ return {
+ content: typeof patched.content === 'string' ? patched.content : result.content,
+ isError: result.isError,
+ }
+ }
}
diff --git a/mcp-host/src/core/guardrails/index.ts b/mcp-host/src/core/guardrails/index.ts
index 158687bf8..733e6b232 100644
--- a/mcp-host/src/core/guardrails/index.ts
+++ b/mcp-host/src/core/guardrails/index.ts
@@ -31,6 +31,7 @@ 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 { ToolResultView } 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 f39ed566e..5c3aa55d3 100644
--- a/mcp-host/src/core/guardrails/tool/__tests__/toolLaneAdapter.test.ts
+++ b/mcp-host/src/core/guardrails/tool/__tests__/toolLaneAdapter.test.ts
@@ -81,4 +81,35 @@ describe('buildToolLaneGuardrail', () => {
const d = await g.decide({ provenance: 'mcp', server: 'github', name: 'get_issue' }, {})
expect(d.decision).toBe('allow')
})
+
+ it('transformResult is absent when no post_tool_use hooks are configured', () => {
+ const g = buildToolLaneGuardrail(config)!
+ expect(g.transformResult).toBeUndefined()
+ })
+
+ it('a PostToolUse hook redacts the result content (is_error preserved)', async () => {
+ const fetchImpl = async (url: string) => ({
+ status: 200,
+ text: async () =>
+ url.endsWith('/v1/post_tool_use') ? '{"updatedResult":{"content":"[redacted]"}}' : '{}',
+ })
+ const g = buildToolLaneGuardrail(
+ {
+ hookDescriptors: [
+ {
+ id: 'th',
+ endpoint: 'http://svc',
+ path: '/',
+ lifecyclePoints: ['post_tool_use'],
+ capabilities: ['may_rewrite'],
+ failMode: 'closed',
+ order: 100,
+ },
+ ],
+ },
+ { getAuthToken: () => '', fetchImpl }
+ )!
+ const v = await g.transformResult!(fileWrite, {}, { content: 'secret', isError: true })
+ expect(v).toEqual({ content: '[redacted]', isError: true })
+ })
})
diff --git a/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts b/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts
index 742c0aa79..ed0374597 100644
--- a/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts
+++ b/mcp-host/src/core/guardrails/tool/toolLaneAdapter.ts
@@ -11,7 +11,7 @@
import { type CoreBoundaryDeps, evaluateBoundary } from '../boundary'
import type { GuardrailsConfig } from '../config'
import { type FetchLike, createHookFetcher } from '../hooks/hookFetcher'
-import { RemoteToolHook } from '../hooks/remoteToolHook'
+import { RemoteToolHook, type ToolResultView } from '../hooks/remoteToolHook'
import type { HookDescriptor } from '../hooks/types'
import type { Contributor, Decision } from '../types'
import type { ToolIdentity } from './provenance'
@@ -22,25 +22,30 @@ export interface ToolLaneGuardrailDeps {
fetchImpl?: FetchLike
}
-/** Build the tool-lane installed `PreToolUse` hooks (spec §6.2), ordered by `order`. */
+/**
+ * Build the tool-lane installed hooks (spec §6.2), ordered by `order`, split by
+ * lifecycle point: `pre` (`PreToolUse` gate) and `post` (`PostToolUse` redaction).
+ * A hook may subscribe to both.
+ */
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,
- })
- )
+): { pre: RemoteToolHook[]; post: RemoteToolHook[] } {
+ const ordered = (descriptors ?? []).slice().sort((a, b) => a.order - b.order)
+ const pre: RemoteToolHook[] = []
+ const post: RemoteToolHook[] = []
+ for (const d of ordered) {
+ const hook = new RemoteToolHook(
+ d,
+ createHookFetcher({
+ getAuthToken: deps.getAuthToken ?? (() => ''),
+ fetchImpl: deps.fetchImpl,
+ })
)
+ if (d.lifecyclePoints.includes('pre_tool_use')) pre.push(hook)
+ if (d.lifecyclePoints.includes('post_tool_use')) post.push(hook)
+ }
+ return { pre, post }
}
export type ToolLaneInput = Record<string, unknown>
@@ -57,6 +62,18 @@ export interface ToolGuardrailDecision {
/** The tool-lane guardrail the loop consults before executing a tool. */
export interface ToolLaneGuardrail {
decide(identity: ToolIdentity, input: ToolLaneInput): Promise<ToolGuardrailDecision>
+ /**
+ * PostToolUse redaction (spec §6.2 / §10 #3): transform the model-visible tool
+ * result through the installed `post_tool_use` hooks, in order. Optional — a
+ * guardrail with no post hooks omits it (the loop then leaves the result
+ * untouched). Never denies/asks; a fail-closed redactor that's unavailable
+ * withholds the content (§8.6).
+ */
+ transformResult?(
+ identity: ToolIdentity,
+ input: ToolLaneInput,
+ result: ToolResultView
+ ): Promise<ToolResultView>
}
/**
@@ -76,7 +93,7 @@ export function buildToolLaneGuardrail(
): ToolLaneGuardrail | undefined {
const compiled = compileRules(config?.rules, config?.limits?.maxRules)
const hooks = buildToolLaneHooks(config?.hookDescriptors, hookDeps)
- if (!compiled.hasRules && hooks.length === 0) return undefined
+ if (!compiled.hasRules && hooks.pre.length === 0 && hooks.post.length === 0) return undefined
const deps: CoreBoundaryDeps<ToolLaneInput, ToolLaneResult, ToolIdentity> = {
lane: 'tool',
@@ -85,17 +102,17 @@ export function buildToolLaneGuardrail(
async pre(input, identity) {
const ruleContribs = evaluateRules(compiled, identity, input)
const hookContribs = (
- await Promise.all(hooks.map(h => h.preToolUse(identity, input)))
+ await Promise.all(hooks.pre.map(h => h.preToolUse(identity, input)))
).filter((c): c is Contributor<ToolLaneInput, ToolLaneResult> => c !== null)
return [...ruleContribs, ...hookContribs]
},
async post() {
- return [] // PostToolUse (post-execution result transform) is a later increment.
+ return [] // PostToolUse redaction is applied via `transformResult`, not the decision boundary.
},
},
}
- return {
+ const guardrail: ToolLaneGuardrail = {
async decide(identity, input) {
const e = await evaluateBoundary(deps, identity, input)
return {
@@ -106,4 +123,18 @@ export function buildToolLaneGuardrail(
}
},
}
+
+ // Only expose `transformResult` when there are post hooks — a guardrail with none
+ // leaves the loop's post-execution path byte-identical to today.
+ if (hooks.post.length > 0) {
+ guardrail.transformResult = async (identity, input, result) => {
+ let current = result
+ for (const hook of hooks.post) {
+ const redacted = await hook.postToolUse(identity, input, current)
+ if (redacted) current = redacted
+ }
+ return current
+ }
+ }
+ return guardrail
}
diff --git a/mcp-host/src/core/orchestration/__tests__/guardrailGate.test.ts b/mcp-host/src/core/orchestration/__tests__/guardrailGate.test.ts
index 06ac157cb..4c5f77021 100644
--- a/mcp-host/src/core/orchestration/__tests__/guardrailGate.test.ts
+++ b/mcp-host/src/core/orchestration/__tests__/guardrailGate.test.ts
@@ -178,6 +178,22 @@ describe('guardrail gate in executeToolCalls', () => {
expect(r3.toolResults[0].is_error).toBe(false) // counter was reset
})
+ it('PostToolUse transformResult redacts the executed result content (§6.2)', async () => {
+ const tool = new StubTool('do_thing')
+ const guardrail: ToolLaneGuardrail = {
+ async decide(_id, input) {
+ return { decision: 'allow', reasonCode: 'r', effectiveInput: input, source: 'host_rule' }
+ },
+ async transformResult(_id, _input, result) {
+ return { content: `[redacted:${result.content}]`, isError: result.isError }
+ },
+ }
+ const { toolResults } = await executeToolCalls([call], makeConfig(tool, guardrail), 0)
+ expect(tool.calls).toHaveLength(1) // executed
+ expect(toolResults[0].content).toBe('[redacted:ok]') // model-visible content redacted
+ expect(toolResults[0].is_error).toBe(false)
+ })
+
it('ask + matching one-shot approval → proceeds and clears pending', async () => {
const tool = new StubTool('do_thing')
const conversation: Partial<Conversation> = {
diff --git a/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts b/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts
index 642679c1a..43edd09b1 100644
--- a/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts
+++ b/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts
@@ -1,6 +1,11 @@
import { randomUUID } from 'crypto'
import { extractToolIntent, getDisplayName } from '../../progress/intentExtraction.js'
-import { recordAndCheck, recordDecision, resolveToolIdentityFromRegistry } from '../guardrails'
+import {
+ type ToolIdentity,
+ recordAndCheck,
+ recordDecision,
+ resolveToolIdentityFromRegistry,
+} from '../guardrails'
import type { ChatMessage, PendingApproval, TokenUsage, ToolCall, ToolResult } from '../types'
import type { LoopConfig } from './loopConfig'
import { executeSingleTool, reportToolComplete, reportToolStart } from './toolUseLoopSingleTool'
@@ -234,12 +239,15 @@ export async function executeToolCalls(
// Guardrail gate (spec §6) — behind config.guardrails; absent = today.
let gate: 'proceed' | 'skip' | { type: 'suspend'; approval: PendingApproval }
+ // Resolved once when the guardrail runs; reused for PostToolUse redaction below.
+ let toolIdentity: ToolIdentity | undefined
if (config.guardrails) {
const identity = resolveToolIdentityFromRegistry(
call.name,
config.toolRegistry,
call.arguments
)
+ toolIdentity = identity
// Doom-loop guard (spec §6.4): deny 3 consecutive identical (tool, input)
// calls within a task. Best-effort runaway/cost guard, not a security
@@ -383,7 +391,20 @@ export async function executeToolCalls(
}
const progressStart = reportToolStart(config, call, iteration, i, calls.length, llmTextContent)
- const toolResult = await executeSingleTool(call, config, iteration)
+ let toolResult = await executeSingleTool(call, config, iteration)
+
+ // PostToolUse redaction (spec §6.2 / §10 #3): installed `post_tool_use` hooks
+ // may redact the model-visible result `content` (never `is_error`). Only the
+ // LLM-message `content` is touched — `rawContent` (UI preview) is left intact.
+ if (config.guardrails?.transformResult && toolIdentity) {
+ const view = await config.guardrails.transformResult(toolIdentity, call.arguments, {
+ content: toolResult.content,
+ isError: toolResult.is_error,
+ })
+ if (view.content !== toolResult.content) {
+ toolResult = { ...toolResult, content: view.content }
+ }
+ }
toolResults.push(toolResult)
if (config.abortSignal?.aborted) {