Skip to content

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

TypeScript

fix(host): redact attachment pages against the whole decoded text

Alfredo Lopez0b8f67966d8c
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 0ad0982c9..173cbea9d 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.506",
+ "version": "0.1.507",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.506",
+ "version": "0.1.507",
"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 3cb8a689f..b6b73c3b7 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.506",
+ "version": "0.1.507",
"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/extensions/__tests__/prePrune.attachmentPageCollapse.test.ts b/mcp-host/src/core/extensions/__tests__/prePrune.attachmentPageCollapse.test.ts
index 522f344da..a67ccb7d3 100644
--- a/mcp-host/src/core/extensions/__tests__/prePrune.attachmentPageCollapse.test.ts
+++ b/mcp-host/src/core/extensions/__tests__/prePrune.attachmentPageCollapse.test.ts
@@ -418,6 +418,7 @@ describe('C17 prePrune — real attachment_read producer (M1, L14)', () => {
return new AttachmentReadTool(message, 65_536, {
contextWindowTokens: 100_000,
ledger: new AttachmentReadLedger(),
+ redactor: new BasicSafety(),
})
}
@@ -508,11 +509,15 @@ describe('C17 prePrune — real attachment_read producer (M1, L14)', () => {
)
// The stored output: the real wrapper around a page that still parses.
+ // The tool masks the value against the whole text (jozer-rami M2), so the
+ // loop's sanitizer finds nothing left to change.
+ const open = '<tool_output name="clerum__attachment_read" sanitized="false">\n'
expect(result.is_error).toBe(false)
- expect(result.content.startsWith(OPEN)).toBe(true)
+ expect(result.content.startsWith(open)).toBe(true)
expect(result.content.endsWith(CLOSE)).toBe(true)
- const inner = result.content.slice(OPEN.length, -CLOSE.length)
+ const inner = result.content.slice(open.length, -CLOSE.length)
expect(parsesAsJson(inner)).toBe(true)
+ expect(JSON.parse(inner).text).toBe('DB_HOST=db.internal\n[REDACTED]')
expect(inner).not.toContain('supersecret99')
const messages: ChatMessage[] = [
@@ -524,8 +529,8 @@ describe('C17 prePrune — real attachment_read producer (M1, L14)', () => {
const pruned = prePrune(messages, OPTIONS, PRESSURE_ON)
expect(pruned.passesApplied).toContain('attachment_page_collapse')
const stubContent = pruned.messages[2].content
- expect(stubContent.startsWith(OPEN)).toBe(true)
- const stub = JSON.parse(stubContent.slice(OPEN.length, -CLOSE.length))
+ expect(stubContent.startsWith(open)).toBe(true)
+ const stub = JSON.parse(stubContent.slice(open.length, -CLOSE.length))
expect(stub).toEqual({
attachmentId: ATTACHMENT_ID,
referenceId: expect.any(String),
diff --git a/mcp-host/src/core/orchestration/__tests__/toolUseLoopSingleTool.attachmentRead.test.ts b/mcp-host/src/core/orchestration/__tests__/toolUseLoopSingleTool.attachmentRead.test.ts
index a68189303..728628bfe 100644
--- a/mcp-host/src/core/orchestration/__tests__/toolUseLoopSingleTool.attachmentRead.test.ts
+++ b/mcp-host/src/core/orchestration/__tests__/toolUseLoopSingleTool.attachmentRead.test.ts
@@ -154,6 +154,7 @@ describe('executeSingleTool — clerum__attachment_read pages stay inline (#666,
return new AttachmentReadTool(message, READ_LIMIT, {
contextWindowTokens: 100_000,
ledger: new AttachmentReadLedger(),
+ redactor: new BasicSafety(),
})
}
diff --git a/mcp-host/src/core/safety/safety.ts b/mcp-host/src/core/safety/safety.ts
index 9100fd42c..72fd38c78 100644
--- a/mcp-host/src/core/safety/safety.ts
+++ b/mcp-host/src/core/safety/safety.ts
@@ -47,7 +47,7 @@ function parsesAsJson(text: string): boolean {
}
}
-type RedactionRange = { start: number; end: number; replacement: string }
+export type RedactionRange = { start: number; end: number; replacement: string }
// `scalar`: the piece is a whole number or literal, replaced by a JSON string.
type RedactionPiece = RedactionRange & { scalar: boolean }
@@ -871,6 +871,18 @@ export class BasicSafety implements Safety {
return secrets
}
+ /**
+ * The ranges of `content` that `sanitizeOutput` redacts as plain text, in
+ * UTF-16 indices, unsorted and possibly overlapping. A caller that emits
+ * slices of a larger text computes them once over the whole text, so a
+ * match does not depend on where a slice ends. Does NOT log.
+ */
+ toolOutputRedactionRanges(toolName: string, content: string): RedactionRange[] {
+ return this.redactionPlan(content, {
+ secretWarning: `Potential secret detected in ${toolName} output`,
+ }).ranges
+ }
+
/**
* The core redaction primitive: strip injection patterns, well-known secret
* shapes, and operator-configured secret values by literal match. Public so
diff --git a/mcp-host/src/core/tools/__tests__/attachmentRead.budget.test.ts b/mcp-host/src/core/tools/__tests__/attachmentRead.budget.test.ts
index cbfa5cc58..c7e410e75 100644
--- a/mcp-host/src/core/tools/__tests__/attachmentRead.budget.test.ts
+++ b/mcp-host/src/core/tools/__tests__/attachmentRead.budget.test.ts
@@ -72,6 +72,7 @@ function toolFor(
tool: new AttachmentReadTool(messageFor(attachments), READ_LIMIT, {
contextWindowTokens: options.windowTokens ?? WINDOW_TOKENS,
ledger,
+ redactor: new BasicSafety(),
}),
ledger,
}
diff --git a/mcp-host/src/core/tools/__tests__/attachmentRead.redaction.test.ts b/mcp-host/src/core/tools/__tests__/attachmentRead.redaction.test.ts
new file mode 100644
index 000000000..0cc0be7e4
--- /dev/null
+++ b/mcp-host/src/core/tools/__tests__/attachmentRead.redaction.test.ts
@@ -0,0 +1,212 @@
+/**
+ * jozer-rami M2 — redaction must not depend on where a page ends. The ranges
+ * come from the whole decoded text, so a secret split by `maxBytes`, by the
+ * budget fit or by a model-chosen `offset` is masked on both sides. What the
+ * model sees is the page after the loop's own per-page `sanitizeOutput`, so
+ * every assertion runs on that.
+ */
+import { describe, expect, it } from 'vitest'
+import { createHash } from 'node:crypto'
+import { validateIncomingAttachments } from '../../../agent/incomingAttachments'
+import type { IncomingMessage } from '../../../server'
+import { AttachmentReadLedger } from '../../attachments/attachmentReadBudget'
+import { BasicSafety } from '../../safety/safety'
+import type { Attachment } from '../../types'
+import { AttachmentReadTool } from '../attachmentRead'
+
+const TOOL = 'clerum__attachment_read'
+const READ_LIMIT = 65_536
+const CONFIGURED = 'CfgLiteralSecretValue9f8e7d'
+const safety = new BasicSafety(() => [{ name: 'CFG_TOKEN', value: CONFIGURED }])
+const measureResult = (raw: string): number =>
+ Math.ceil(Buffer.byteLength(safety.previewOutputForLlm(TOOL, raw), 'utf8') / 4) + 4
+
+// Each shape: the whole string the rule matches, and the secret part of it.
+const SHAPES = [
+ { name: 'GitHub token', label: 'ghp_', value: 'Q1w2E3r4T5y6U7i8O9p0A1s2D3f4G5h6J7k8' },
+ { name: 'Stripe key', label: 'sk_live_', value: 'Ab12Cd34Ef56Gh78Ij90Kl12' },
+ { name: 'Bearer token', label: 'Bearer ', value: 'Zx9Qw8Er7Ty6Ui5Op4As3Df2Gh1Jk0Lm' },
+ { name: 'password value', label: 'password=', value: 'Sup3rS3cretValue123' },
+ { name: 'ConfigStore literal', label: '', value: CONFIGURED },
+] as const
+
+const BEFORE = 'intro text line\n'
+const AFTER = '\ntrailing words here\n'
+
+function admitted(id: string, bytes: Buffer): Attachment {
+ const result = validateIncomingAttachments(
+ [
+ {
+ id,
+ 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: 11_534_336, messageId: 'message-1' }
+ )
+ if (!result.ok) throw new Error(`fixture rejected: ${result.error.code}`)
+ return result.attachments![0]!
+}
+
+function toolFor(attachment: Attachment, contextWindowTokens = 4_000_000): AttachmentReadTool {
+ const message: IncomingMessage = {
+ content: 'Analyze the attached file',
+ channelType: 'rpc',
+ channelId: 'agent-1',
+ sender: 'user-1',
+ timestamp: '2026-10-07T10:00:00Z',
+ messageId: 'message-1',
+ hostRef: 'host-1',
+ attachments: [attachment],
+ }
+ return new AttachmentReadTool(message, READ_LIMIT, {
+ contextWindowTokens,
+ ledger: new AttachmentReadLedger(),
+ redactor: safety,
+ })
+}
+
+/** One page as the model receives it: tool output, then the per-page pass. */
+async function readPage(tool: AttachmentReadTool, params: Record<string, unknown>) {
+ const output = await tool.execute(params, { onOutput: () => {}, measureResult })
+ const visible = safety.sanitizeOutput(TOOL, output.content)
+ return {
+ body: JSON.parse(output.content) as {
+ kind: string
+ text?: string
+ byteRange?: { offset: number; length: number }
+ truncated?: boolean
+ nextOffset?: number
+ limit?: string
+ },
+ visible: visible.content,
+ wasModified: visible.was_modified,
+ }
+}
+
+/** Every page from `offset` to EOF, with a fixed `maxBytes`. */
+async function walk(tool: AttachmentReadTool, maxBytes?: number) {
+ const pages: Awaited<ReturnType<typeof readPage>>[] = []
+ let offset = 0
+ for (;;) {
+ const page = await readPage(tool, {
+ attachmentId: 'file-1',
+ offset,
+ ...(maxBytes ? { maxBytes } : {}),
+ })
+ expect(page.body.kind).toBe('text')
+ pages.push(page)
+ if (!page.body.truncated) return pages
+ offset = page.body.nextOffset!
+ }
+}
+
+/** The first `width`-character piece of `value` that `visible` shows, if any. */
+function leakedPiece(visible: string, value: string, width = 6): string | null {
+ for (let i = 0; i + width <= value.length; i++) {
+ const piece = value.slice(i, i + width)
+ if (visible.includes(piece)) return piece
+ }
+ return null
+}
+
+describe('attachment pages are redacted against the whole text (jozer-rami M2)', () => {
+ it('refuses to register without a redactor', () => {
+ const file = admitted('file-1', Buffer.from('plain text'))
+ const message = { ...({} as IncomingMessage), attachments: [file] }
+ expect(
+ () =>
+ new AttachmentReadTool(message, READ_LIMIT, {
+ contextWindowTokens: 4_000_000,
+ ledger: new AttachmentReadLedger(),
+ } as never)
+ ).toThrow(/require a redactor/)
+ // Witness: the same options with a redactor construct the tool.
+ expect(toolFor(file).name()).toBe(TOOL)
+ })
+
+ it.each(SHAPES)('a $name split across pages by maxBytes does not leak', async shape => {
+ const secret = shape.label + shape.value
+ const text = BEFORE + secret + AFTER
+ const file = admitted('file-1', Buffer.from(text))
+
+ // Witness: read whole, the same text is redacted by the rule under test.
+ const whole = await walk(toolFor(file))
+ expect(whole).toHaveLength(1)
+ expect(whole[0]!.visible).toContain('[REDACTED')
+ expect(leakedPiece(whole[0]!.visible, shape.value)).toBeNull()
+
+ const splitAt = Buffer.byteLength(BEFORE) + Math.floor(secret.length / 2)
+ const pages = await walk(toolFor(file), splitAt)
+ // Precondition: the first page really ends inside the secret.
+ expect(pages.length).toBeGreaterThan(1)
+ expect(pages[0]!.body.nextOffset).toBe(splitAt)
+ for (const page of pages) {
+ expect(leakedPiece(page.visible, shape.value)).toBeNull()
+ }
+ // Liveness: the text around the secret is still delivered.
+ expect(pages.map(p => p.body.text).join('')).toContain('intro text line')
+ expect(pages.map(p => p.body.text).join('')).toContain('trailing words here')
+ })
+
+ it('a page that starts in the middle of a secret leaks none of its tail', async () => {
+ const shape = SHAPES[0]
+ const secret = shape.label + shape.value
+ const file = admitted('file-1', Buffer.from(BEFORE + secret + AFTER))
+ const offset = Buffer.byteLength(BEFORE) + 10
+ const page = await readPage(toolFor(file), { attachmentId: 'file-1', offset })
+ expect(page.body.byteRange?.offset).toBe(offset)
+ expect(page.body.text).toContain('trailing words here')
+ expect(leakedPiece(page.visible, shape.value)).toBeNull()
+ })
+
+ // Regression guard: masking changes the text, never the byte accounting.
+ it('pages walked to EOF still cover every byte of the file once', async () => {
+ const text = BEFORE + SHAPES.map(s => s.label + s.value).join('\n') + AFTER
+ const bytes = Buffer.from(text)
+ const pages = await walk(toolFor(admitted('file-1', bytes)), 17)
+ let expected = 0
+ for (const page of pages) {
+ expect(page.body.byteRange!.offset).toBe(expected)
+ expected += page.body.byteRange!.length
+ }
+ expect(expected).toBe(bytes.length)
+ expect(pages[pages.length - 1]!.body.truncated).toBe(false)
+ })
+
+ it('a split forced by the page budget does not leak the tail', async () => {
+ // Dense GitHub-shaped tokens separated by single spaces: a budget-bound
+ // page end almost always lands inside one. The budget measures the
+ // redacted preview (each token costs about 11 bytes), so the file needs
+ // well over a page of tokens.
+ const tokens = Array.from(
+ { length: 1_500 },
+ (_, i) => 'ghp_' + createHash('sha256').update(`token-${i}`).digest('hex')
+ )
+ const bytes = Buffer.from(tokens.join(' '))
+ const tool = toolFor(admitted('file-1', bytes), 20_000)
+ const first = await readPage(tool, { attachmentId: 'file-1' })
+ expect(first.body).toMatchObject({ kind: 'text', truncated: true })
+ expect(first.body.limit).not.toBe('max_bytes')
+ // Unmasked, the fit ended inside a token and the next page started with
+ // its unredacted tail. Masked, a token costs the same however much of it
+ // a page holds, so the fit ends where a token starts; the assertions
+ // below hold either way, and the vacuity mutation shows the leak.
+ const boundary = first.body.nextOffset!
+
+ const second = await readPage(tool, { attachmentId: 'file-1', offset: boundary })
+ expect(second.body.kind).toBe('text')
+ expect(second.body.byteRange!.length).toBeGreaterThan(0)
+ for (const page of [first, second]) {
+ // No run of token characters long enough to be a token piece survives.
+ expect(page.body.text).toBeDefined()
+ expect(JSON.parse(page.visible).text).not.toMatch(/[a-zA-Z0-9]{12,}/)
+ }
+ })
+})
diff --git a/mcp-host/src/core/tools/__tests__/attachmentRead.test.ts b/mcp-host/src/core/tools/__tests__/attachmentRead.test.ts
index 9b2766458..8d76878a2 100644
--- a/mcp-host/src/core/tools/__tests__/attachmentRead.test.ts
+++ b/mcp-host/src/core/tools/__tests__/attachmentRead.test.ts
@@ -71,6 +71,7 @@ function toolFor(attachments: Attachment[], limit = READ_LIMIT): AttachmentReadT
return new AttachmentReadTool(message, limit, {
contextWindowTokens: WINDOW_TOKENS,
ledger: new AttachmentReadLedger(),
+ redactor: new BasicSafety(),
})
}
diff --git a/mcp-host/src/core/tools/attachmentRead.ts b/mcp-host/src/core/tools/attachmentRead.ts
index 1611b26a9..65decfe3f 100644
--- a/mcp-host/src/core/tools/attachmentRead.ts
+++ b/mcp-host/src/core/tools/attachmentRead.ts
@@ -14,6 +14,11 @@
* page — after JSON escaping and the sanitized wrapper — into the
* current-turn page/turn budgets, shrinking by whole code points with
* measurement only; the tool is never re-executed to fit.
+ * Redaction ranges are computed once over the whole decoded text and
+ * every page masks the part of each range it holds before it is
+ * measured, so a secret split by `maxBytes`, by the budget fit or by a
+ * model-chosen `offset` is masked on both sides (jozer-rami M2). The
+ * loop's per-page sanitizer still runs on the result.
* - `reader:'none'`: a typed binary result; the bytes are never decoded.
*
* The text-or-binary rule is the one `clerum__gfs_read` applies
@@ -32,6 +37,7 @@ import type {
ToolEmissionContext,
ToolTraceDescriptor,
} from '../interfaces'
+import type { RedactionRange } from '../safety/safety'
import type { ToolOutput, ToolResult } from '../types'
export type AttachmentReadErrorCode =
@@ -44,6 +50,12 @@ export interface AttachmentReadToolOptions {
contextWindowTokens: number
/** Turn-owned ledger; the registry wires one per turn. */
ledger: AttachmentReadLedger
+ /** The tool-output redaction rules, applied to the whole decoded text. */
+ redactor: AttachmentReadRedactor
+}
+
+export interface AttachmentReadRedactor {
+ toolOutputRedactionRanges(toolName: string, content: string): RedactionRange[]
}
export type AttachmentReadLimit = 'max_bytes' | 'page_budget' | 'turn_budget'
@@ -94,6 +106,69 @@ function isUtf8Continuation(byte: number): boolean {
return (byte & 0xc0) === 0x80
}
+/** A byte range of the decoded file that every overlapping page replaces. */
+interface ByteRedaction {
+ start: number
+ end: number
+ replacement: string
+}
+
+// The replacement `applyRedactionRanges` uses when overlapping ranges carry
+// different replacements.
+const MIXED_REDACTION = '[REDACTED]'
+
+const isHighSurrogate = (code: number): boolean => code >= 0xd800 && code <= 0xdbff
+const isLowSurrogate = (code: number): boolean => code >= 0xdc00 && code <= 0xdfff
+
+// True when UTF-16 index `i` falls between the two halves of one code point.
+function splitsSurrogatePair(text: string, i: number): boolean {
+ return (
+ i > 0 &&
+ i < text.length &&
+ isLowSurrogate(text.charCodeAt(i)) &&
+ isHighSurrogate(text.charCodeAt(i - 1))
+ )
+}
+
+/**
+ * Turns UTF-16 redaction ranges over `text` into sorted, disjoint byte ranges
+ * of its UTF-8 encoding. Each range is widened to whole code points, and
+ * overlapping ranges are merged as `applyRedactionRanges` merges them.
+ */
+function toByteRedactions(text: string, ranges: RedactionRange[]): ByteRedaction[] {
+ const widened = ranges
+ .map(range => ({
+ start: splitsSurrogatePair(text, range.start) ? range.start - 1 : range.start,
+ end: splitsSurrogatePair(text, range.end) ? range.end + 1 : range.end,
+ replacement: range.replacement,
+ }))
+ .filter(range => range.end > range.start)
+ .sort((a, b) => a.start - b.start || b.end - a.end)
+ const merged: ByteRedaction[] = []
+ for (const range of widened) {
+ const last = merged[merged.length - 1]
+ if (last && range.start < last.end) {
+ if (range.end > last.end) last.end = range.end
+ if (range.replacement !== last.replacement) last.replacement = MIXED_REDACTION
+ continue
+ }
+ merged.push({ ...range })
+ }
+ // The bounds are now ascending, so one pass maps every index to its byte.
+ let index = 0
+ let byte = 0
+ const toByte = (target: number): number => {
+ byte += Buffer.byteLength(text.slice(index, target), 'utf8')
+ index = target
+ return byte
+ }
+ return merged.map(range => ({
+ start: toByte(range.start),
+ end: toByte(range.end),
+ replacement: range.replacement,
+ }))
+}
+
const EXHAUSTED_MESSAGE =
'The current-turn attachment read budget is exhausted. Reattach the file in a new message to resume at the reported offset; earlier pages are not stored for re-reading.'
@@ -108,8 +183,14 @@ interface PendingEmission {
}
export class AttachmentReadTool implements Tool {
- /** Decoded bytes and the whole-file text check, per attachmentId. */
- private readonly decoded = new Map<string, { bytes: Buffer; isText: boolean }>()
+ /**
+ * Decoded bytes and the whole-file text check, per attachmentId, plus the
+ * byte redaction ranges of a text file once a page needs them.
+ */
+ private readonly decoded = new Map<
+ string,
+ { bytes: Buffer; isText: boolean; redactions?: ByteRedaction[] }
+ >()
/** @param maxBytesPerCall the per-call ceiling and the default page. */
constructor(
@@ -123,12 +204,17 @@ export class AttachmentReadTool implements Tool {
// Reuses the ledger's validation: positive safe integer or throw here,
// before any read can execute.
attachmentReadBudgets(options.contextWindowTokens)
+ if (typeof options.redactor?.toolOutputRedactionRanges !== 'function') {
+ throw new Error('Attachment read options require a redactor')
+ }
this.contextWindowTokens = options.contextWindowTokens
this.ledger = options.ledger
+ this.redactor = options.redactor
}
private readonly contextWindowTokens: number
private readonly ledger: AttachmentReadLedger
+ private readonly redactor: AttachmentReadRedactor
private pending: PendingEmission | null = null
name(): string {
@@ -425,6 +511,57 @@ export class AttachmentReadTool implements Tool {
return entry
}
+ // Computed once per text attachment, over the whole decoded text.
+ private redactions(attachmentId: string): ByteRedaction[] {
+ const entry = this.decoded.get(attachmentId)
+ if (!entry?.isText) {
+ throw new Error('Attachment redactions requested before the text was decoded')
+ }
+ if (entry.redactions) return entry.redactions
+ // `ignoreBOM: true` keeps a leading U+FEFF, so every UTF-16 index of the
+ // text maps to a byte of the file.
+ const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(entry.bytes)
+ entry.redactions = toByteRedactions(
+ text,
+ this.redactor.toolOutputRedactionRanges(this.name(), text)
+ )
+ return entry.redactions
+ }
+
+ /**
+ * The text of bytes `[offset, end)` with the part of every redaction range
+ * that falls inside it replaced. Range and page bounds are code point
+ * boundaries, so every decoded segment is whole UTF-8.
+ */
+ private pageText(bytes: Buffer, attachmentId: string, offset: number, end: number): string {
+ const redactions = this.redactions(attachmentId)
+ // A byte order mark is dropped only at the start of the file; further in,
+ // U+FEFF is file content and stays.
+ const decode = (from: number, to: number): string =>
+ new TextDecoder('utf-8', { fatal: true, ignoreBOM: from > 0 }).decode(
+ bytes.subarray(from, to)
+ )
+ let lo = 0
+ let hi = redactions.length
+ while (lo < hi) {
+ const mid = (lo + hi) >>> 1
+ if (redactions[mid]!.end <= offset) lo = mid + 1
+ else hi = mid
+ }
+ const parts: string[] = []
+ let cursor = offset
+ for (let i = lo; i < redactions.length; i++) {
+ const range = redactions[i]!
+ const from = Math.max(range.start, offset)
+ const to = Math.min(range.end, end)
+ if (from >= to) break
+ parts.push(decode(cursor, from), range.replacement)
+ cursor = to
+ }
+ parts.push(decode(cursor, end))
+ return parts.join('')
+ }
+
private ok(
result: AttachmentReadResult,
start: number,
@@ -554,11 +691,7 @@ export class AttachmentReadTool implements Tool {
truncated: boolean,
limit: AttachmentReadLimit | null
): AttachmentReadResult {
- // A byte order mark is dropped only at the start of the file; further in,
- // U+FEFF is file content and stays.
- const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: offset > 0 }).decode(
- bytes.subarray(offset, end)
- )
+ const text = this.pageText(bytes, identity.attachmentId, offset, end)
return {
attachmentId: identity.attachmentId,
referenceId: identity.referenceId,
diff --git a/mcp-host/src/core/tools/nativeToolRegistry.ts b/mcp-host/src/core/tools/nativeToolRegistry.ts
index 061a33101..aace92804 100644
--- a/mcp-host/src/core/tools/nativeToolRegistry.ts
+++ b/mcp-host/src/core/tools/nativeToolRegistry.ts
@@ -23,6 +23,7 @@ import { ScopedWorkspace } from '../../workspace/scopedWorkspace'
import type { Workspace } from '../../workspace/service'
import type { AttachmentReadLedger } from '../attachments/attachmentReadBudget'
import { type ExecutionContext, NativeToolConfig, Tool, ToolRegistry } from '../interfaces'
+import { BasicSafety } from '../safety/safety'
import type { SessionSearchService } from '../sessionSearch'
import type { SpilloverStorage } from '../spillover'
import { ToolDefinition, ToolOutput } from '../types'
@@ -321,8 +322,11 @@ export class NativeToolRegistry implements ToolRegistry {
// The tool declares itself spillover-exempt: a page is bounded by
// `maxBytes`, so the loop ships it inline whether or not this turn has
// spillover storage (#678).
+ // Pages are redacted against the whole text with the same rules and
+ // ConfigStore secrets the loop's tool-output sanitizer applies.
+ const redactor = new BasicSafety(attachmentOptions?.secretEntriesProvider)
this.register(
- new AttachmentReadTool(sourceMessage, maxBytes, { contextWindowTokens, ledger })
+ new AttachmentReadTool(sourceMessage, maxBytes, { contextWindowTokens, ledger, redactor })
)
}