Skip to content

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

TypeScript

fix(mcp-host): sanitize tool error text and pin registry secret redaction

Alfredo Lopez16e1138903aa
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index e83d96b19..cf8571d47 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.511",
+ "version": "0.1.512",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.511",
+ "version": "0.1.512",
"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 46792557b..818ac44eb 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.511",
+ "version": "0.1.512",
"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/orchestration/__tests__/toolUseLoopSingleTool.errorRedaction.test.ts b/mcp-host/src/core/orchestration/__tests__/toolUseLoopSingleTool.errorRedaction.test.ts
new file mode 100644
index 000000000..b3ac191db
--- /dev/null
+++ b/mcp-host/src/core/orchestration/__tests__/toolUseLoopSingleTool.errorRedaction.test.ts
@@ -0,0 +1,109 @@
+/**
+ * A15 item 6 — a thrown tool error reaches the post-result transform and the
+ * model through `errorResult`. A thrown upstream message can carry a secret,
+ * so its text goes through the same tool-output sanitizer the success path
+ * applies (`config.safety.sanitizeOutput`, which `toolOutputProcessor`
+ * delegates to) before the transform sees it.
+ */
+import { describe, expect, it, vi } from 'vitest'
+import { makeFakeConversation } from '../../conversation/__testing__/makeFakeConversation'
+import type { ToolLaneGuardrail } from '../../guardrails'
+import type { ReasoningPort, Tool, ToolRegistry } from '../../interfaces'
+import { BasicSafety } from '../../safety/safety'
+import type { ChatMessage, ToolOutput, ToolResult } from '../../types'
+import { SimpleEventEmitter } from '../eventEmitter'
+import { buildLoopConfig } from '../loopConfig'
+import { runToolUseLoop } from '../toolUseLoop'
+
+const TOKEN = 'ghp_Q1w2E3r4T5y6U7i8O9p0A1s2D3f4G5h6J7k8'
+const TOKEN_BODY = TOKEN.slice('ghp_'.length)
+const UPSTREAM = 'upstream refused the request with credential'
+
+function throwingTool(): Tool & { execute: ReturnType<typeof vi.fn> } {
+ return {
+ name: () => 'fetch_repo',
+ description: () => 'Fetch a repository',
+ parametersSchema: () => ({ type: 'object', properties: {} }),
+ execute: vi.fn(async (): Promise<ToolOutput> => {
+ throw new Error(`${UPSTREAM} ${TOKEN}`)
+ }),
+ requiresSanitization: () => true,
+ requiresApproval: () => false,
+ }
+}
+
+function registryOf(tool: Tool): ToolRegistry {
+ return {
+ get: name => (name === tool.name() ? tool : null),
+ listDefinitions: () => [
+ { name: tool.name(), description: tool.description(), parameters: tool.parametersSchema() },
+ ],
+ register: vi.fn(),
+ }
+}
+
+describe('executeSingleTool — thrown error text is sanitized (A15 item 6)', () => {
+ it('redacts a token in a thrown message before the transform and the model see it', async () => {
+ const tool = throwingTool()
+ const seenByTransform: Array<{ content: string; isError: boolean }> = []
+ const guardrails: ToolLaneGuardrail = {
+ async decide(_id, input) {
+ return { decision: 'allow', reasonCode: 'r', effectiveInput: input, source: 'host_rule' }
+ },
+ async transformResult(_id, _input, result) {
+ seenByTransform.push(result)
+ return result
+ },
+ }
+ const resultsForModel: ToolResult[][] = []
+ const messagesForModel: ChatMessage[][] = []
+ const reasoning: ReasoningPort = {
+ respondWithTools: vi.fn(async () => ({
+ type: 'tool_calls' as const,
+ calls: [{ id: 'tc_1', name: 'fetch_repo', arguments: {} }],
+ })),
+ continueWithToolResults: vi.fn(async (context, results) => {
+ // Copies: the loop keeps mutating the arrays it passed.
+ resultsForModel.push(structuredClone(results))
+ messagesForModel.push(structuredClone(context.messages))
+ return { type: 'text' as const, content: 'done' }
+ }),
+ }
+ const config = buildLoopConfig({
+ reasoning,
+ toolRegistry: registryOf(tool),
+ safety: new BasicSafety(),
+ events: new SimpleEventEmitter(),
+ conversation: makeFakeConversation(),
+ maxIterations: 4,
+ })
+ config.guardrails = guardrails
+
+ const result = await runToolUseLoop(config, [{ role: 'user', content: 'fetch it' }])
+
+ // Witness: the tool ran and threw, and the loop handed its error onward.
+ expect(tool.execute).toHaveBeenCalledTimes(1)
+ expect(result).toMatchObject({ type: 'response', content: 'done' })
+ expect(seenByTransform).toHaveLength(1)
+ expect(resultsForModel).toHaveLength(1)
+ expect(resultsForModel[0]).toHaveLength(1)
+
+ // The result reaching the transform: still an error, error text kept,
+ // token redacted.
+ const transformed = seenByTransform[0]!
+ expect(transformed.isError).toBe(true)
+ expect(transformed.content).toContain(`Tool execution failed: ${UPSTREAM}`)
+ expect(transformed.content).toContain('[REDACTED]')
+ expect(transformed.content).not.toContain(TOKEN_BODY)
+
+ // The result and the messages the model receives.
+ const toModel = resultsForModel[0]![0]!
+ expect(toModel).toMatchObject({ tool_call_id: 'tc_1', is_error: true })
+ expect(toModel.content).toContain(`Tool execution failed: ${UPSTREAM}`)
+ expect(toModel.content).not.toContain(TOKEN_BODY)
+ const toolMessages = messagesForModel[0]!.filter(message => message.role === 'tool')
+ expect(toolMessages).toHaveLength(1)
+ expect(JSON.stringify(toolMessages[0])).toContain(UPSTREAM)
+ expect(JSON.stringify(messagesForModel[0])).not.toContain(TOKEN_BODY)
+ })
+})
diff --git a/mcp-host/src/core/orchestration/toolUseLoopSingleTool.ts b/mcp-host/src/core/orchestration/toolUseLoopSingleTool.ts
index b559f7764..984e69074 100644
--- a/mcp-host/src/core/orchestration/toolUseLoopSingleTool.ts
+++ b/mcp-host/src/core/orchestration/toolUseLoopSingleTool.ts
@@ -35,10 +35,18 @@ export async function executeSingleTool(
): Promise<ToolResult> {
const { toolRegistry, toolOutputProcessor, events, toolTimeout } = config
- // Post-result hooks see error results too: they redact error text (a thrown
- // upstream message can carry a secret) and observe failed calls.
+ // Post-result hooks see error results too and observe failed calls. A thrown
+ // upstream message can carry a secret, so the error text first goes through
+ // the tool-output sanitizer the success path applies (`toolOutputProcessor`
+ // delegates to `config.safety.sanitizeOutput`), unwrapped: error text keeps
+ // its plain shape for the model.
const errorResult = async (content: string): Promise<ToolResult> => {
- const result: ToolResult = { tool_call_id: call.id, name: call.name, content, is_error: true }
+ const result: ToolResult = {
+ tool_call_id: call.id,
+ name: call.name,
+ content: config.safety.sanitizeOutput(call.name, content).content,
+ is_error: true,
+ }
return transformResult ? transformResult(result) : result
}
diff --git a/mcp-host/src/core/tools/__tests__/nativeToolRegistry.attachmentRead.test.ts b/mcp-host/src/core/tools/__tests__/nativeToolRegistry.attachmentRead.test.ts
index 0e509ac3e..6364b8774 100644
--- a/mcp-host/src/core/tools/__tests__/nativeToolRegistry.attachmentRead.test.ts
+++ b/mcp-host/src/core/tools/__tests__/nativeToolRegistry.attachmentRead.test.ts
@@ -8,6 +8,7 @@ import { validateIncomingAttachments } from '../../../agent/incomingAttachments'
import type { IncomingMessage } from '../../../server'
import { AttachmentReadLedger } from '../../attachments/attachmentReadBudget'
import type { NativeToolConfig } from '../../interfaces'
+import { BasicSafety } from '../../safety/safety'
import { SpilloverStorage } from '../../spillover'
import type { Attachment } from '../../types'
import { NativeToolRegistry } from '../nativeToolRegistry'
@@ -255,4 +256,106 @@ describe('NativeToolRegistry — clerum__attachment_read (#666)', () => {
expect(reader.description()).toContain('reader=text')
expect(reader.description()).not.toContain('spillover')
})
+
+ // A15 item 5 — the registry must hand the turn's ConfigStore secrets to the
+ // tool's whole-text redactor. The loop's per-page sanitizer sees the same
+ // secrets, but only whole: a literal cut by a page end reaches the model
+ // unless the tool masked it against the whole text first.
+ it('masks a ConfigStore secret split across pages with the turn secretEntriesProvider', async () => {
+ const TOOL = 'clerum__attachment_read'
+ const secret = 'CfgLiteralSecretValue9f8e7d'
+ const secretEntriesProvider = () => [{ name: 'CFG_TOKEN', value: secret }]
+ // What the loop applies to every page: the same ConfigStore secrets.
+ const loopSafety = new BasicSafety(secretEntriesProvider)
+ const context = {
+ onOutput: () => {},
+ measureResult: (raw: string): number =>
+ Math.ceil(Buffer.byteLength(loopSafety.previewOutputForLlm(TOOL, raw), 'utf8') / 4) + 4,
+ }
+ const before = 'intro text line\n'
+ const text = before + secret + '\ntrailing words here\n'
+ const bytes = Buffer.from(text)
+ const validated = validateIncomingAttachments(
+ [
+ {
+ id: 'file-1',
+ kind: 'file',
+ mimeType: 'text/plain',
+ detectedMediaType: 'text/plain',
+ encoding: 'base64',
+ dataBase64: bytes.toString('base64'),
+ filename: 'notes.txt',
+ sizeBytes: bytes.length,
+ digest: { algorithm: 'sha256', hex: createHash('sha256').update(bytes).digest('hex') },
+ },
+ ],
+ { maxCount: 20, maxBytes: 1_000_000, maxFileBytes: 3_145_728, messageId: 'message-1' }
+ )
+ if (!validated.ok) throw new Error(`fixture rejected: ${validated.error.code}`)
+ const registry = new NativeToolRegistry(
+ config,
+ 'conv-1',
+ undefined,
+ message(validated.attachments!),
+ undefined,
+ undefined,
+ undefined,
+ { ...attachmentOptions(), secretEntriesProvider }
+ )
+ const tool = registry.get(TOOL)!
+
+ /** One page as the model receives it: tool output, then the loop's pass. */
+ const readPage = async (params: Record<string, unknown>) => {
+ const output = await tool.execute(params, context)
+ return {
+ output,
+ body: JSON.parse(output.content) as {
+ kind: string
+ text?: string
+ truncated?: boolean
+ nextOffset?: number
+ },
+ visible: loopSafety.sanitizeOutput(TOOL, output.content).content,
+ }
+ }
+ /** The first 6-character piece of the secret that `visible` shows, if any. */
+ const leakedPiece = (visible: string): string | null => {
+ for (let i = 0; i + 6 <= secret.length; i++) {
+ if (visible.includes(secret.slice(i, i + 6))) return secret.slice(i, i + 6)
+ }
+ return null
+ }
+
+ // Witness: read whole, the file carries the literal and the model sees it
+ // redacted. This holds with or without the provider at the registry (the
+ // loop pass masks a whole literal), so only the split walk below can tell
+ // whether the registry wired the provider into the tool.
+ const whole = await readPage({ attachmentId: 'file-1' })
+ expect(whole.body).toMatchObject({ kind: 'text', truncated: false })
+ expect(whole.visible).toContain('[REDACTED')
+ expect(whole.visible).toContain('intro text line')
+ expect(leakedPiece(whole.visible)).toBeNull()
+
+ // Split: the first page ends in the middle of the literal.
+ const splitAt = Buffer.byteLength(before) + Math.floor(secret.length / 2)
+ const pages: Awaited<ReturnType<typeof readPage>>[] = []
+ let offset = 0
+ for (;;) {
+ const page = await readPage({ attachmentId: 'file-1', offset, maxBytes: splitAt })
+ expect(page.body.kind).toBe('text')
+ pages.push(page)
+ if (!page.body.truncated) break
+ offset = page.body.nextOffset!
+ }
+ // Precondition: the walk really crossed the secret on a page boundary.
+ expect(pages.length).toBeGreaterThan(1)
+ expect(pages[0]!.body.nextOffset).toBe(splitAt)
+ for (const page of pages) {
+ expect(leakedPiece(page.visible)).toBeNull()
+ }
+ // Liveness: the text around the secret is still delivered.
+ const joined = pages.map(page => page.body.text).join('')
+ expect(joined).toContain('intro text line')
+ expect(joined).toContain('trailing words here')
+ })
})