Skip to content

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

TypeScript

fix(mcp-host): stop the turn when attachment notices pass the overdraft

Alfredo Lopezafbf505397d0
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 6baf4becf..e83d96b19 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.510",
+ "version": "0.1.511",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.510",
+ "version": "0.1.511",
"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 3fca8f975..46792557b 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.510",
+ "version": "0.1.511",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/agent/__tests__/attachmentRead.integration.test.ts b/mcp-host/src/agent/__tests__/attachmentRead.integration.test.ts
index a2b05f2d3..5260584bd 100644
--- a/mcp-host/src/agent/__tests__/attachmentRead.integration.test.ts
+++ b/mcp-host/src/agent/__tests__/attachmentRead.integration.test.ts
@@ -6,10 +6,19 @@
*/
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createHash } from 'node:crypto'
+import { mkdtemp, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { config as appConfig } from '../../config'
+import {
+ type AttachmentReadLedger,
+ type AttachmentReadLedgerSnapshot,
+ attachmentReadBudgets,
+} from '../../core/attachments/attachmentReadBudget'
import { ConversationManager } from '../../core/conversation/conversation'
import { SimpleEventEmitter } from '../../core/orchestration/eventEmitter'
import { ATTACHED_FILES_INSTRUCTION } from '../../core/orchestration/turnContext'
+import { ATTACHMENT_READ_TURN_STOP_MESSAGE } from '../../core/tools/attachmentRead'
import { type ChatMessage, FinishReason, type ToolCall } from '../../core/types'
import { TaskLifecycle } from '../../lifecycle/taskLifecycle'
import type { SingleTurnProvider } from '../../llm/types'
@@ -48,20 +57,38 @@ function lastUserText(messages: ChatMessage[]): string {
return user.content ?? ''
}
+interface TaskOptions {
+ contextWindowTokens?: number
+ /** The double asks for the next page (or the same offset) on every response. */
+ readEveryResponse?: boolean
+ /** The first response asks for an approval-gated shell command instead. */
+ approvalFirst?: boolean
+}
+
async function runTask(
filename: string,
mimeType: string,
bytes: Buffer,
- options: { contextWindowTokens?: number } = {}
+ options: TaskOptions = {}
) {
const attachment = admittedFile(filename, mimeType, bytes)
return { ...(await runTaskWith(attachment, options)), attachment }
}
+/** The offset the double asks for next: the page's nextOffset, else the notice's resumeOffset. */
+function nextReadOffset(messages: ChatMessage[]): number {
+ const last = [...messages].reverse().find(message => message.role === 'tool')
+ if (!last || last.name !== 'clerum__attachment_read') return 0
+ const payload = toolPayload(last.content ?? '')
+ if (typeof payload.nextOffset === 'number') return payload.nextOffset
+ if (typeof payload.resumeOffset === 'number') return payload.resumeOffset
+ throw new Error(`unexpected attachment read payload kind ${String(payload.kind)}`)
+}
+
/** Without an attachment the double answers directly; with one it reads it first. */
async function runTaskWith(
attachment: ReturnType<typeof admittedFile> | undefined,
- options: { contextWindowTokens?: number } = {}
+ options: TaskOptions = {}
) {
const call: ToolCall = {
id: 'read-1',
@@ -69,6 +96,7 @@ async function runTaskWith(
arguments: { attachmentId: 'file-1' },
}
const providerCalls: Array<{ messages: ChatMessage[]; toolNames: string[] }> = []
+ let reads = 0
const provider: SingleTurnProvider = {
getProviderType: () => 'openai',
classifyError: () => {
@@ -82,6 +110,23 @@ async function runTaskWith(
messages: structuredClone(messages),
toolNames: tools.map(tool => tool.name),
})
+ if (options.approvalFirst && providerCalls.length === 1) {
+ const shell: ToolCall = {
+ id: 'shell-1',
+ name: 'shell_exec',
+ arguments: { command: "printf 'approved\\n' >> effects.txt" },
+ }
+ return { content: null, tool_calls: [shell], usage, finish_reason: FinishReason.ToolUse }
+ }
+ if (options.readEveryResponse && attachment) {
+ reads += 1
+ const read: ToolCall = {
+ id: `read-${reads}`,
+ name: 'clerum__attachment_read',
+ arguments: { attachmentId: 'file-1', offset: nextReadOffset(messages) },
+ }
+ return { content: null, tool_calls: [read], usage, finish_reason: FinishReason.ToolUse }
+ }
if (providerCalls.length === 1 && attachment) {
return { content: null, tool_calls: [call], usage, finish_reason: FinishReason.ToolUse }
}
@@ -119,6 +164,11 @@ async function runTaskWith(
}
const lifecycle = new TaskLifecycle()
lifecycle.register(task)
+ const coreEvents = new SimpleEventEmitter()
+ const toolRuns: string[] = []
+ coreEvents.on('tool:completed', event => {
+ toolRuns.push(`${String(event.data.toolName)}:${String(event.data.toolCallId)}`)
+ })
const deps: TaskExecutorDeps = {
conversationManager: new ConversationManager(),
llmProvider: provider,
@@ -131,12 +181,12 @@ async function runTaskWith(
approvalConfig: undefined,
config: {
maxTaskDuration: 300000,
- maxToolCallsPerTask: 10,
+ maxToolCallsPerTask: options.readEveryResponse ? 100 : 10,
autoStart: true,
taskDelay: 0,
approvalTimeout: 300000,
},
- coreEvents: new SimpleEventEmitter(),
+ coreEvents,
cronScheduler: null,
taskLifecycle: lifecycle,
onApprovalNeeded: vi.fn(),
@@ -146,7 +196,13 @@ async function runTaskWith(
}
const executor = new TaskExecutor(task, deps)
await executor.run()
- return { attachment, call, deps, executor, providerCalls, task }
+ return { attachment, call, deps, executor, providerCalls, task, toolRuns }
+}
+
+function ledgerOf(executor: TaskExecutor): AttachmentReadLedgerSnapshot {
+ return (
+ executor as unknown as { attachmentReadLedger: AttachmentReadLedger }
+ ).attachmentReadLedger.snapshot()
}
/** The tool message content is the `<tool_output>` wrapper around the page JSON. */
@@ -313,4 +369,113 @@ describe('clerum__attachment_read through a complete task (#666)', () => {
expect(lastUserText(providerCalls[0]!.messages)).toBe('Analyze the attached file')
expect(providerCalls[0]!.toolNames).not.toContain('clerum__attachment_read')
})
+
+ describe('notice overdraft ceiling (A15 U1)', () => {
+ const WINDOW = 8_192
+ const { turnTokens } = attachmentReadBudgets(WINDOW)
+ const ceiling = turnTokens + Math.floor(turnTokens / 2)
+ const reads = (from: number, to: number): string[] =>
+ Array.from({ length: to - from + 1 }, (_, i) => `clerum__attachment_read:read-${from + i}`)
+ /** The kind of read-k's result as the model received it on the following call. */
+ const kindSeenAfter = (
+ providerCalls: Array<{ messages: ChatMessage[] }>,
+ index: number,
+ k: number
+ ) => {
+ const message = providerCalls[index]!.messages.find(
+ entry => entry.role === 'tool' && entry.tool_call_id === `read-${k}`
+ )
+ if (!message) throw new Error(`the model never received read-${k}`)
+ return toolPayload(message.content ?? '').kind
+ }
+
+ it('ends the task with a stop message instead of failing it when the model keeps reading', async () => {
+ Object.assign(appConfig, {
+ enableApproval: false,
+ dynamicToolsEnabled: false,
+ promptCacheEnabled: true,
+ })
+ const { deps, executor, providerCalls, task, toolRuns } = await runTask(
+ 'long.txt',
+ 'text/plain',
+ Buffer.alloc(400_000, 'q'),
+ { contextWindowTokens: WINDOW, readEveryResponse: true }
+ )
+
+ expect(deps.onFail).not.toHaveBeenCalled()
+ expect(executor.executorState).toBe('completed')
+ expect(deps.onComplete).toHaveBeenCalledTimes(1)
+ expect(vi.mocked(task.responseCallback!).mock.calls.map(([arg]) => arg.response)).toEqual([
+ ATTACHMENT_READ_TURN_STOP_MESSAGE,
+ ])
+ // Measured: 19 reads ran and the model was called once per read before
+ // the stop, never after it (two pages, then 16 charged notices).
+ expect(toolRuns).toEqual(reads(1, 19))
+ expect(providerCalls).toHaveLength(19)
+ // Witness: reads 1-18 reached the model as a page or a plain notice.
+ const kinds = Array.from({ length: 18 }, (_, i) => kindSeenAfter(providerCalls, i + 1, i + 1))
+ expect(kinds.slice(0, 2)).toEqual(['text', 'text'])
+ expect(kinds.slice(2).every(kind => kind === 'read_budget_exhausted')).toBe(true)
+ expect(ledgerOf(executor).spentTokens).toBeGreaterThan(turnTokens)
+ expect(ledgerOf(executor).spentTokens).toBeLessThanOrEqual(ceiling)
+ })
+
+ it('ends the task the same way after a resume that cannot prove the earlier spend', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'a15-turn-stop-'))
+ const savedWorkspace = appConfig.nativeTool.workspacePath
+ try {
+ Object.assign(appConfig, {
+ enableApproval: true,
+ dynamicToolsEnabled: false,
+ promptCacheEnabled: true,
+ })
+ appConfig.nativeTool.workspacePath = dir
+ const { deps, executor, providerCalls, task, toolRuns } = await runTask(
+ 'long.txt',
+ 'text/plain',
+ Buffer.alloc(400_000, 'q'),
+ { contextWindowTokens: WINDOW, readEveryResponse: true, approvalFirst: true }
+ )
+ expect(executor.executorState).toBe('waiting_approval')
+ const approval = executor.pendingApproval!
+ expect(approval.task_budget?.attachmentReadLedger).toEqual({
+ reads: 0,
+ spentTokens: 0,
+ bytesRead: 0,
+ })
+ // A missing carrier makes the resume exhaust the ledger (fail closed).
+ delete approval.task_budget!.attachmentReadLedger
+ await executor.resumeAfterApproval(false)
+
+ expect(deps.onFail).not.toHaveBeenCalled()
+ expect(executor.executorState).toBe('completed')
+ expect(deps.onComplete).toHaveBeenCalledTimes(1)
+ expect(vi.mocked(task.responseCallback!).mock.calls.map(([arg]) => arg.response)).toEqual([
+ ATTACHMENT_READ_TURN_STOP_MESSAGE,
+ ])
+ // Measured: the exhausted ledger pays 8 notices from the overdraft and
+ // the 9th read stops the turn.
+ expect(toolRuns).toEqual(['shell_exec:shell-1', ...reads(1, 9)])
+ // The shell call, then one model call after the shell result and after
+ // each of reads 1-8.
+ expect(providerCalls).toHaveLength(10)
+ // Witness: reads 1-8 reached the model as notices, never as text.
+ for (let k = 1; k <= 8; k++) {
+ expect(kindSeenAfter(providerCalls, k + 1, k)).toBe('read_budget_exhausted')
+ }
+ const ledger = ledgerOf(executor)
+ expect(ledger.reads).toBe(32)
+ expect(ledger.bytesRead).toBe(0)
+ expect(ledger.spentTokens).toBeGreaterThan(turnTokens)
+ expect(ledger.spentTokens).toBeLessThanOrEqual(ceiling)
+ // The stop is the ceiling's: the room left is less than one notice.
+ const noticeCost = (ledger.spentTokens - turnTokens) / 8
+ expect(Number.isInteger(noticeCost)).toBe(true)
+ expect(ceiling - ledger.spentTokens).toBeLessThan(noticeCost)
+ } finally {
+ appConfig.nativeTool.workspacePath = savedWorkspace
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+ })
})
diff --git a/mcp-host/src/agent/__tests__/taskExecutor.test.ts b/mcp-host/src/agent/__tests__/taskExecutor.test.ts
index 676e8b7db..1b39589cc 100644
--- a/mcp-host/src/agent/__tests__/taskExecutor.test.ts
+++ b/mcp-host/src/agent/__tests__/taskExecutor.test.ts
@@ -2191,6 +2191,78 @@ describe('TaskExecutor exhaustion and cancellation contracts', () => {
})
expect(deps.onFail).not.toHaveBeenCalled()
})
+ it('completes a turn stopped by a tool result with its message (A15 U1)', async () => {
+ const deps = createDeps(),
+ task = createTask()
+ vi.mocked(runToolUseLoop).mockResolvedValue({
+ type: 'exhaustion',
+ reason: 'turn_stop',
+ message: 'Stopped reading for this turn',
+ iterations: 3,
+ })
+ const executor = new TaskExecutor(task, deps)
+ await executor.run()
+ // Witness: the loop ran and its result was delivered.
+ expect(runToolUseLoop).toHaveBeenCalledTimes(1)
+ expect(task.responseCallback).toHaveBeenCalledWith({
+ response: 'Stopped reading for this turn',
+ attachments: undefined,
+ })
+ expect(deps.onComplete).toHaveBeenCalledTimes(1)
+ expect(executor.executorState).toBe('completed')
+ expect(deps.onFail).not.toHaveBeenCalled()
+ })
+ it('ends a resumed turn when the approved tool stops it, without another loop (A15 U1)', async () => {
+ vi.mocked(runToolUseLoop).mockResolvedValueOnce({
+ type: 'need_approval',
+ approval: {
+ request_id: 'req-stop',
+ tool_name: 'clerum__attachment_read',
+ parameters: { attachmentId: 'file-1' },
+ description: 'Guardrail requires approval (ask)',
+ tool_call_id: 'tc_read',
+ context_snapshot: [
+ { role: 'user', content: 'Read the file' },
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ {
+ id: 'tc_read',
+ name: 'clerum__attachment_read',
+ arguments: { attachmentId: 'file-1' },
+ },
+ ],
+ },
+ ],
+ },
+ } as any)
+ vi.mocked(executeSingleTool).mockResolvedValueOnce({
+ tool_call_id: 'tc_read',
+ name: 'clerum__attachment_read',
+ content: '{"kind":"read_budget_exhausted"}',
+ is_error: false,
+ stopTurn: { message: 'Stopped reading for this turn' },
+ })
+ const deps = createDeps()
+ const task = createTask('Read the file')
+ const executor = new TaskExecutor(task, deps)
+ await executor.run()
+ expect(executor.executorState).toBe('waiting_approval')
+
+ await executor.resumeAfterApproval(false)
+
+ // Witness: the approved call executed on resume.
+ expect(executeSingleTool).toHaveBeenCalledTimes(1)
+ expect(runToolUseLoop).toHaveBeenCalledTimes(1)
+ expect(task.responseCallback).toHaveBeenCalledWith({
+ response: 'Stopped reading for this turn',
+ attachments: undefined,
+ })
+ expect(executor.executorState).toBe('completed')
+ expect(deps.onComplete).toHaveBeenCalledTimes(1)
+ expect(deps.onFail).not.toHaveBeenCalled()
+ })
it('does not resurrect a cancelled legacy approval', async () => {
const task = createTask(),
deps = createDeps()
diff --git a/mcp-host/src/agent/taskExecutor.ts b/mcp-host/src/agent/taskExecutor.ts
index 8b846fc90..e9d971167 100644
--- a/mcp-host/src/agent/taskExecutor.ts
+++ b/mcp-host/src/agent/taskExecutor.ts
@@ -57,6 +57,7 @@ import {
collectToolAttachments,
mergeCollectedAttachments,
} from '../core/orchestration/toolUseLoopMessages'
+import { turnStopResult } from '../core/orchestration/toolUseLoopRuntime'
import {
type PreparedGfsFile,
attachedFilesForTurnContext,
@@ -871,7 +872,10 @@ export class TaskExecutor {
...(approval.attachments || []),
...this.collectAttachments([...(approval.completed_results || []), toolResult]),
]
- const result = await runToolUseLoop(loopConfig, messages)
+ // A15 U1 — the approved tool ended the turn: no further model call.
+ const result: LoopResult = toolResult.stopTurn
+ ? turnStopResult(loopConfig, 0, toolResult.stopTurn.message, [])
+ : await runToolUseLoop(loopConfig, messages)
// Preserve attachments
if (previousAttachments.length > 0) {
@@ -1307,7 +1311,11 @@ export class TaskExecutor {
switch (result.type) {
case 'response':
case 'exhaustion': {
- if (result.type === 'exhaustion' && result.reason !== 'task_budget')
+ if (
+ result.type === 'exhaustion' &&
+ result.reason !== 'task_budget' &&
+ result.reason !== 'turn_stop'
+ )
throw new TaskLimitError(
'TASK_ITERATION_LIMIT',
`Task stopped before completion after ${this.executionBudget.maxIterations} iterations. Continuation requires a new budget.`
diff --git a/mcp-host/src/core/attachments/__tests__/attachmentReadBudget.test.ts b/mcp-host/src/core/attachments/__tests__/attachmentReadBudget.test.ts
index d84be4df6..867a19369 100644
--- a/mcp-host/src/core/attachments/__tests__/attachmentReadBudget.test.ts
+++ b/mcp-host/src/core/attachments/__tests__/attachmentReadBudget.test.ts
@@ -15,11 +15,19 @@ describe('notice overdraft', () => {
const ledger = new AttachmentReadLedger()
ledger.restore({ reads: 32, spentTokens: 3_000, bytesRead: 77 })
expect(ledger.canEmit(WINDOW, 100)).toBe(false)
- ledger.debitNotice(WINDOW, 1_000)
- ledger.debitNotice(WINDOW, 500)
+ expect(ledger.debitNotice(WINDOW, 1_000)).toBe(true)
+ expect(ledger.debitNotice(WINDOW, 500)).toBe(true)
expect(ledger.snapshot()).toEqual({ reads: 32, spentTokens: 4_500, bytesRead: 77 })
- expect(() => ledger.debitNotice(WINDOW, 1)).toThrow(/notice cannot fit/)
+ })
+
+ it('reports the ceiling with false and leaves the ledger unchanged', () => {
+ const ledger = new AttachmentReadLedger()
+ ledger.restore({ reads: 32, spentTokens: 4_400, bytesRead: 77 })
+ // Witness: the last 100 tokens of overdraft are still charged.
+ expect(ledger.debitNotice(WINDOW, 100)).toBe(true)
expect(ledger.snapshot().spentTokens).toBe(4_500)
+ expect(ledger.debitNotice(WINDOW, 1)).toBe(false)
+ expect(ledger.snapshot()).toEqual({ reads: 32, spentTokens: 4_500, bytesRead: 77 })
})
it('refuses a notice larger than one page even with overdraft left', () => {
@@ -27,9 +35,25 @@ describe('notice overdraft', () => {
ledger.restore({ reads: 0, spentTokens: 3_000, bytesRead: 0 })
expect(() => ledger.debitNotice(WINDOW, 1_001)).toThrow(/notice cannot fit/)
// Witness: a page-sized notice is accepted on the same ledger.
- ledger.debitNotice(WINDOW, 1_000)
+ expect(ledger.debitNotice(WINDOW, 1_000)).toBe(true)
expect(ledger.snapshot().spentTokens).toBe(4_000)
})
+
+ it('still throws on an invalid cost or an unsafe spend, at or below the ceiling', () => {
+ const ledger = new AttachmentReadLedger()
+ ledger.restore({ reads: 0, spentTokens: 3_000, bytesRead: 0 })
+ for (const cost of [-1, 1.5, NaN]) {
+ expect(() => ledger.debitNotice(WINDOW, cost)).toThrow(/notice cannot fit/)
+ }
+ expect(ledger.snapshot().spentTokens).toBe(3_000)
+ // A spend that is no longer a safe integer is a corrupt ledger, not a ceiling.
+ const huge = 1_000_000_000_000
+ ledger.restore({ reads: 0, spentTokens: Number.MAX_SAFE_INTEGER - 10, bytesRead: 0 })
+ expect(() => ledger.debitNotice(huge, 100)).toThrow(/notice cannot fit/)
+ // Witness: a valid cost on the same ledger is answered, not thrown.
+ ledger.restore({ reads: 0, spentTokens: 3_000, bytesRead: 0 })
+ expect(ledger.debitNotice(WINDOW, 10)).toBe(true)
+ })
})
describe('attachment turn ledger', () => {
diff --git a/mcp-host/src/core/attachments/attachmentReadBudget.ts b/mcp-host/src/core/attachments/attachmentReadBudget.ts
index de4eb6fab..a5634cff9 100644
--- a/mcp-host/src/core/attachments/attachmentReadBudget.ts
+++ b/mcp-host/src/core/attachments/attachmentReadBudget.ts
@@ -143,20 +143,22 @@ export class AttachmentReadLedger {
* Charges a trusted exhausted notice that no longer fits the turn. Notices
* read no bytes and do not count as reads, so a model that keeps calling
* after the budget binds gets an answer instead of a failed task. The
- * overdraft stops at half a turn above the turn budget; past it the caller
- * stops the turn.
+ * overdraft stops at half a turn above the turn budget: past it nothing is
+ * charged and false tells the caller to stop the turn. An invalid cost, a
+ * cost above one page or an unsafe spend still throws.
*/
- debitNotice(windowTokens: number, cost: number): void {
+ debitNotice(windowTokens: number, cost: number): boolean {
const limits = attachmentReadBudgets(windowTokens)
const ceiling = limits.turnTokens + Math.floor(limits.turnTokens / 2)
if (
!boundedCount(cost) ||
cost > limits.pageTokens ||
- !Number.isSafeInteger(this.state.spentTokens + cost) ||
- this.state.spentTokens + cost > ceiling
+ !Number.isSafeInteger(this.state.spentTokens + cost)
) {
throw new Error('Attachment read notice cannot fit the remaining page/turn budget')
}
+ if (this.state.spentTokens + cost > ceiling) return false
this.state.spentTokens += cost
+ return true
}
}
diff --git a/mcp-host/src/core/orchestration/__tests__/toolUseLoop.turnStop.test.ts b/mcp-host/src/core/orchestration/__tests__/toolUseLoop.turnStop.test.ts
new file mode 100644
index 000000000..bdc3fb017
--- /dev/null
+++ b/mcp-host/src/core/orchestration/__tests__/toolUseLoop.turnStop.test.ts
@@ -0,0 +1,152 @@
+/**
+ * A15 U1 — a tool result that carries `stopTurn` ends the turn after its
+ * batch: the remaining calls are answered without running, no model call
+ * follows, and the loop returns `exhaustion` with reason `turn_stop`.
+ */
+import { describe, expect, it, vi } from 'vitest'
+import { makeFakeConversation } from '../../conversation/__testing__/makeFakeConversation'
+import type { ReasoningPort, Tool, ToolRegistry } from '../../interfaces'
+import { BasicSafety } from '../../safety/safety'
+import type { AgentEvent, ChatMessage, RespondResult, ToolCall, ToolOutput } from '../../types'
+import { SimpleEventEmitter } from '../eventEmitter'
+import { type LoopConfig, buildLoopConfig } from '../loopConfig'
+import { runToolUseLoop, validateToolLinkages } from '../toolUseLoop'
+import { executeToolCalls } from '../toolUseLoopToolBatch'
+
+const STOP_MESSAGE = 'The reading limit was reached for this turn.'
+
+function mockTool(toolName: string, stops: boolean): Tool {
+ return {
+ name: () => toolName,
+ description: () => `Mock ${toolName}`,
+ parametersSchema: () => ({ type: 'object', properties: {} }),
+ execute: vi.fn(
+ async (): Promise<ToolOutput> => ({
+ content: `${toolName} result`,
+ duration_ms: 1,
+ is_error: false,
+ })
+ ),
+ requiresSanitization: () => true,
+ requiresApproval: () => false,
+ finalizeResult: vi.fn((result, context) => ({
+ ...result,
+ emittedMessageCost: context.measureContent(result.content),
+ ...(stops ? { stopTurn: { message: STOP_MESSAGE } } : {}),
+ })),
+ }
+}
+
+function registry(tools: Tool[]): ToolRegistry {
+ const map = new Map(tools.map(t => [t.name(), t]))
+ return {
+ get: (name: string) => map.get(name) ?? null,
+ listDefinitions: () =>
+ tools.map(t => ({
+ name: t.name(),
+ description: t.description(),
+ parameters: t.parametersSchema(),
+ })),
+ register: vi.fn(),
+ }
+}
+
+const CALLS: ToolCall[] = [
+ { id: 'tc_stop', name: 'stopper', arguments: {} },
+ { id: 'tc_second', name: 'second', arguments: {} },
+ { id: 'tc_third', name: 'third', arguments: {} },
+]
+
+function setup(firstStops: boolean) {
+ const tools = [
+ mockTool('stopper', firstStops),
+ mockTool('second', false),
+ mockTool('third', false),
+ ]
+ const script: RespondResult[] = [
+ { type: 'tool_calls', calls: CALLS },
+ { type: 'text', content: 'after the batch' },
+ ]
+ let i = 0
+ const next = async (): Promise<RespondResult> => script[i++]!
+ const reasoning: ReasoningPort = {
+ respondWithTools: vi.fn(next),
+ continueWithToolResults: vi.fn(next),
+ }
+ const events = new SimpleEventEmitter()
+ const completed: AgentEvent[] = []
+ events.on('loop:completed', event => completed.push(event))
+ const config: LoopConfig = buildLoopConfig({
+ reasoning,
+ toolRegistry: registry(tools),
+ safety: new BasicSafety(),
+ events,
+ conversation: makeFakeConversation(),
+ maxIterations: 10,
+ })
+ config.measureToolMessage = message => (message.content ?? '').length
+ return { tools, reasoning, config, completed }
+}
+
+describe('runToolUseLoop — turn stop from a tool result (A15 U1)', () => {
+ it('ends the turn after the batch without running the later calls or the model', async () => {
+ const { tools, reasoning, config, completed } = setup(true)
+
+ const result = await runToolUseLoop(config, [{ role: 'user', content: 'read it' }])
+
+ // Witness: the model asked once and the stopping tool really ran.
+ expect(reasoning.respondWithTools).toHaveBeenCalledTimes(1)
+ expect(tools[0]!.execute).toHaveBeenCalledTimes(1)
+ expect(tools[0]!.finalizeResult).toHaveBeenCalledTimes(1)
+ expect(tools[1]!.execute).not.toHaveBeenCalled()
+ expect(tools[2]!.execute).not.toHaveBeenCalled()
+ expect(reasoning.continueWithToolResults).not.toHaveBeenCalled()
+ expect(result).toEqual({
+ type: 'exhaustion',
+ reason: 'turn_stop',
+ message: STOP_MESSAGE,
+ iterations: 1,
+ })
+ expect(completed.map(event => event.data.resultType)).toEqual(['turn_stop'])
+ })
+
+ it('continues to the model when no result stops the turn', async () => {
+ const { tools, reasoning, config } = setup(false)
+
+ const result = await runToolUseLoop(config, [{ role: 'user', content: 'read it' }])
+
+ expect(tools.map(tool => vi.mocked(tool.execute).mock.calls.length)).toEqual([1, 1, 1])
+ expect(reasoning.continueWithToolResults).toHaveBeenCalledTimes(1)
+ expect(result.type).toBe('response')
+ })
+
+ it('answers every later call of the batch so the tool linkage holds', async () => {
+ const { tools, config } = setup(true)
+
+ const batch = await executeToolCalls(CALLS, config, 0)
+
+ expect(batch.stopTurn).toEqual({ message: STOP_MESSAGE })
+ expect(batch.toolResults.map(r => [r.tool_call_id, r.is_error])).toEqual([
+ ['tc_stop', false],
+ ['tc_second', true],
+ ['tc_third', true],
+ ])
+ for (const skipped of batch.toolResults.slice(1)) {
+ expect(skipped.content).toBe('Not executed — the turn stopped. Re-request if needed.')
+ }
+ expect(tools[1]!.execute).not.toHaveBeenCalled()
+ const messages: ChatMessage[] = [
+ { role: 'user', content: 'read it' },
+ { role: 'assistant', content: '', tool_calls: CALLS },
+ ...batch.toolResults.map(r => ({
+ role: 'tool' as const,
+ content: r.content,
+ tool_call_id: r.tool_call_id,
+ name: r.name,
+ })),
+ ]
+ expect(() => validateToolLinkages(messages)).not.toThrow()
+ // Witness: the same check rejects a batch that drops the later answers.
+ expect(() => validateToolLinkages(messages.slice(0, 3))).toThrow(/Tool linkage violated/)
+ })
+})
diff --git a/mcp-host/src/core/orchestration/toolUseLoop.ts b/mcp-host/src/core/orchestration/toolUseLoop.ts
index a1ed71c0d..2478f9f94 100644
--- a/mcp-host/src/core/orchestration/toolUseLoop.ts
+++ b/mcp-host/src/core/orchestration/toolUseLoop.ts
@@ -32,6 +32,7 @@ import {
manageMessagesForIteration,
responseResult,
taskBrakeResult,
+ turnStopResult,
} from './toolUseLoopRuntime'
import { executeToolCalls } from './toolUseLoopToolBatch'
import {
@@ -347,7 +348,7 @@ export async function runToolUseLoop(
config.visualInput?.budget.observeExternalImage(part.data)
}
}
- const { toolResults, pendingApproval, cancelled } = await executeToolCalls(
+ const { toolResults, pendingApproval, cancelled, stopTurn } = await executeToolCalls(
result.calls,
config,
iteration,
@@ -373,6 +374,17 @@ export async function runToolUseLoop(
}
return { type: 'need_approval', approval: projectGfsApproval(pendingApproval) }
}
+ if (stopTurn) {
+ // A15 U1 — a trusted tool ended the turn: keep the batch's results
+ // and attachments, make no further model call.
+ appendToolResults(
+ messages,
+ toolResults,
+ collectedAttachments,
+ config.imageSourceIdentity === true
+ )
+ return turnStopResult(config, iteration + 1, stopTurn.message, collectedAttachments)
+ }
const workflowFallbackResults = toolResults.filter(
tr => tr.is_error !== true && isWorkflowSuccessFallbackToolName(tr.name)
diff --git a/mcp-host/src/core/orchestration/toolUseLoopRuntime.ts b/mcp-host/src/core/orchestration/toolUseLoopRuntime.ts
index 68b6df85f..70ce1d933 100644
--- a/mcp-host/src/core/orchestration/toolUseLoopRuntime.ts
+++ b/mcp-host/src/core/orchestration/toolUseLoopRuntime.ts
@@ -210,6 +210,32 @@ export function taskBrakeResult(
}
}
+/**
+ * A15 U1 — a trusted tool result ended the turn (`ToolResult.stopTurn`). Like
+ * the task brake, the task completes normally: `message` is the reply and the
+ * attachments collected so far are kept. No further model call is made.
+ */
+export function turnStopResult(
+ config: LoopConfig,
+ iterations: number,
+ message: string,
+ attachments: Attachment[]
+): LoopResult {
+ logger.info({ iterations }, 'Turn stopped by a tool result')
+ config.events.emit({
+ type: 'loop:completed',
+ data: { iteration: iterations, resultType: 'turn_stop' },
+ timestamp: new Date(),
+ })
+ return {
+ type: 'exhaustion',
+ reason: 'turn_stop',
+ message,
+ iterations,
+ attachments: attachments.length > 0 ? attachments : undefined,
+ }
+}
+
export function exhaustionResult(
config: LoopConfig,
maxIterations: number,
diff --git a/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts b/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts
index c8e957521..8375b167c 100644
--- a/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts
+++ b/mcp-host/src/core/orchestration/toolUseLoopToolBatch.ts
@@ -169,6 +169,7 @@ export async function executeToolCalls(
toolResults: ToolResult[]
pendingApproval?: PendingApproval
cancelled?: boolean
+ stopTurn?: { message: string }
}> {
const { loopController, events } = config
const toolResults: ToolResult[] = []
@@ -335,6 +336,20 @@ export async function executeToolCalls(
)
usageEmitted = true
+ // A trusted tool ended the turn (A15 U1): answer the rest of the batch
+ // without running it, so the tool linkage holds and no model call follows.
+ if (toolResult.stopTurn) {
+ for (let k = i + 1; k < calls.length; k++) {
+ toolResults.push({
+ tool_call_id: calls[k].id,
+ name: calls[k].name,
+ content: 'Not executed — the turn stopped. Re-request if needed.',
+ is_error: true,
+ })
+ }
+ return { toolResults, stopTurn: toolResult.stopTurn }
+ }
+
if (isWorkflowTriggerNotFoundToolResult(toolResult)) {
for (let k = i + 1; k < calls.length; k++) {
toolResults.push({
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 c7e410e75..ae4d5d115 100644
--- a/mcp-host/src/core/tools/__tests__/attachmentRead.budget.test.ts
+++ b/mcp-host/src/core/tools/__tests__/attachmentRead.budget.test.ts
@@ -13,7 +13,7 @@ import { AttachmentReadLedger, attachmentReadBudgets } from '../../attachments/a
import { toolMessageBudgetTokens } from '../../extensions/contextManager'
import { BasicSafety } from '../../safety/safety'
import type { Attachment, ToolResult } from '../../types'
-import { AttachmentReadTool } from '../attachmentRead'
+import { ATTACHMENT_READ_TURN_STOP_MESSAGE, AttachmentReadTool } from '../attachmentRead'
const TOOL_NAME = 'clerum__attachment_read'
const READ_LIMIT = 65_536
@@ -309,31 +309,39 @@ describe('C16 small context windows under the production tool-message measuremen
const kinds: string[] = []
let offset = 0
- let stop: unknown = null
+ let stop: ToolResult | null = null
+ let spentAtStop = { before: -1, after: -1 }
for (let call = 0; call < 200 && stop === null; call++) {
const before = ledger.snapshot().spentTokens
- try {
- const { body } = await runMeasured(tool, { attachmentId: id, offset })
- kinds.push(body.kind as string)
- if (body.kind === 'text') offset += (body.byteRange as { length: number }).length
- // Every emitted message is charged. Pages stay inside the turn; only
- // notices may overdraw it, and never past half a turn more.
- expect(ledger.snapshot().spentTokens).toBeGreaterThan(before)
- if (body.kind === 'text')
- expect(ledger.snapshot().spentTokens).toBeLessThanOrEqual(turnTokens)
- expect(ledger.snapshot().spentTokens).toBeLessThanOrEqual(
- turnTokens + Math.floor(turnTokens / 2)
- )
- } catch (error) {
- stop = error
+ const { body, finalized } = await runMeasured(tool, { attachmentId: id, offset })
+ kinds.push(body.kind as string)
+ if (finalized.stopTurn) {
+ stop = finalized
+ spentAtStop = { before, after: ledger.snapshot().spentTokens }
+ break
}
+ if (body.kind === 'text') offset += (body.byteRange as { length: number }).length
+ // Every emitted message is charged. Pages stay inside the turn; only
+ // notices may overdraw it, and never past half a turn more.
+ expect(ledger.snapshot().spentTokens).toBeGreaterThan(before)
+ if (body.kind === 'text')
+ expect(ledger.snapshot().spentTokens).toBeLessThanOrEqual(turnTokens)
+ expect(ledger.snapshot().spentTokens).toBeLessThanOrEqual(
+ turnTokens + Math.floor(turnTokens / 2)
+ )
}
expect(kinds[0]).toBe('text')
const firstNotice = kinds.indexOf('read_budget_exhausted')
expect(firstNotice).toBeGreaterThan(0)
expect(kinds.slice(firstNotice).every(kind => kind === 'read_budget_exhausted')).toBe(true)
expect(kinds.length - firstNotice).toBeGreaterThanOrEqual(2)
- expect(String(stop)).toMatch(/notice cannot fit/)
+ // The call at the ceiling answers with the same notice and stops the turn,
+ // without charging the notice it could not afford.
+ expect(stop).not.toBeNull()
+ expect(stop!.is_error).toBe(false)
+ expect(stop!.stopTurn).toEqual({ message: ATTACHMENT_READ_TURN_STOP_MESSAGE })
+ expect(spentAtStop.after).toBe(spentAtStop.before)
+ expect(spentAtStop.after).toBeLessThanOrEqual(turnTokens + Math.floor(turnTokens / 2))
})
describe('bounded notice overdraft (jozer-rami M1)', () => {
@@ -419,18 +427,23 @@ describe('C16 small context windows under the production tool-message measuremen
const { turnTokens } = attachmentReadBudgets(LARGE_WINDOW)
let notices = 0
- let stop: unknown = null
+ let stop: ToolResult | null = null
for (let call = 0; call < 5_000 && stop === null; call++) {
- try {
- const { body } = await runMeasured(tool, { attachmentId: id })
- expect(body.kind).toBe('read_budget_exhausted')
+ const before = ledger.snapshot().spentTokens
+ const { body, finalized } = await runMeasured(tool, { attachmentId: id })
+ expect(body.kind).toBe('read_budget_exhausted')
+ expect(finalized.content).not.toContain('stop page')
+ if (finalized.stopTurn) {
+ stop = finalized
+ // The stopping notice is not charged.
+ expect(ledger.snapshot().spentTokens).toBe(before)
+ } else {
notices += 1
- } catch (error) {
- stop = error
+ expect(ledger.snapshot().spentTokens).toBeGreaterThan(before)
}
}
expect(notices).toBeGreaterThanOrEqual(2)
- expect(String(stop)).toMatch(/notice cannot fit/)
+ expect(stop?.stopTurn?.message).toBe(ATTACHMENT_READ_TURN_STOP_MESSAGE)
expect(ledger.snapshot().spentTokens).toBeLessThanOrEqual(
turnTokens + Math.floor(turnTokens / 2)
)
@@ -504,20 +517,47 @@ describe('C16 finalize fence', () => {
expect(ledger.snapshot().spentTokens).toBeGreaterThan(turnTokens)
})
- it('fails closed when the notice would pass half a turn of overdraft', async () => {
+ it('stops the turn with the notice when it would pass half a turn of overdraft', async () => {
const [file] = admitted([
rawFile('file-over', 'over.txt', 'text/plain', Buffer.from('over page body')),
])
const ledger = new AttachmentReadLedger()
const turnTokens = Math.floor(WINDOW_TOKENS * 0.3)
- ledger.restore({
- reads: 1,
- spentTokens: turnTokens + Math.floor(turnTokens / 2) - 1,
- bytesRead: 0,
- })
+ const spent = turnTokens + Math.floor(turnTokens / 2) - 1
+ ledger.restore({ reads: 1, spentTokens: spent, bytesRead: 0 })
const { tool } = toolFor([file!], { ledger })
- await expect(runRead(tool, { attachmentId: 'file-over' })).rejects.toThrow(/notice cannot fit/)
+ const { finalized } = await runRead(tool, { attachmentId: 'file-over' })
+ // Witness: the result is the trusted notice, measured like any other.
+ const body = JSON.parse(finalized.rawContent as string) as Record<string, unknown>
+ expect(body.kind).toBe('read_budget_exhausted')
+ expect(finalized.is_error).toBe(false)
+ expect(finalized.emittedMessageCost).toBe(measureContent(finalized.content))
+ expect(finalized.content).not.toContain('over page body')
+ expect(finalized.stopTurn).toEqual({ message: ATTACHMENT_READ_TURN_STOP_MESSAGE })
+ expect(ATTACHMENT_READ_TURN_STOP_MESSAGE).toBe(
+ 'I stopped reading the attached file for this turn because it reached its reading limit. Send another message to continue, or ask about a specific part of the file.'
+ )
+ // execute counted the call; the stopping notice itself is not charged.
+ expect(ledger.snapshot()).toEqual({ reads: 2, spentTokens: spent, bytesRead: 0 })
+ })
+
+ it('leaves stopTurn unset on a page and on a notice the overdraft still covers', async () => {
+ const [file] = admitted([
+ rawFile('file-cover', 'cover.txt', 'text/plain', Buffer.from('cover page body')),
+ ])
+ const page = await runRead(toolFor([file!]).tool, { attachmentId: 'file-cover' })
+ expect(page.finalized.content).toContain('cover page body')
+ expect(page.finalized).not.toHaveProperty('stopTurn')
+
+ const ledger = new AttachmentReadLedger()
+ const turnTokens = Math.floor(WINDOW_TOKENS * 0.3)
+ ledger.restore({ reads: 1, spentTokens: turnTokens, bytesRead: 0 })
+ const notice = await runRead(toolFor([file!], { ledger }).tool, { attachmentId: 'file-cover' })
+ // Witness: this call took the overdraft path and was charged.
+ expect(JSON.parse(notice.finalized.rawContent as string).kind).toBe('read_budget_exhausted')
+ expect(ledger.snapshot().spentTokens).toBeGreaterThan(turnTokens)
+ expect(notice.finalized).not.toHaveProperty('stopTurn')
})
it('finalizes exactly once without another tool execution', async () => {
diff --git a/mcp-host/src/core/tools/attachmentRead.ts b/mcp-host/src/core/tools/attachmentRead.ts
index 65decfe3f..63e8c7f4d 100644
--- a/mcp-host/src/core/tools/attachmentRead.ts
+++ b/mcp-host/src/core/tools/attachmentRead.ts
@@ -172,6 +172,10 @@ function toByteRedactions(text: string, ranges: RedactionRange[]): ByteRedaction
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.'
+/** The reply of a turn stopped once the notice overdraft is spent. */
+export const ATTACHMENT_READ_TURN_STOP_MESSAGE =
+ 'I stopped reading the attached file for this turn because it reached its reading limit. Send another message to continue, or ask about a specific part of the file.'
+
/** Execute-time reservation consumed exactly once by finalizeResult. */
interface PendingEmission {
attachmentId: string
@@ -452,8 +456,9 @@ export class AttachmentReadTool implements Tool {
* and any result transform. If the final message outgrew the reservation,
* replace it with the trusted exhausted notice at the ORIGINAL offset. A
* notice that no longer fits the turn is charged to the bounded notice
- * overdraft; once that is spent too, throw so publication stops without a
- * rerun.
+ * overdraft; once that is spent too, the same notice is returned uncharged
+ * with `stopTurn`, so the loop ends the turn after this batch and no model
+ * call ever receives it.
*/
finalizeResult(result: ToolResult, context: ToolEmissionContext): ToolResult {
const pending = this.pending
@@ -475,14 +480,16 @@ export class AttachmentReadTool implements Tool {
)
const noticeContent = context.renderContent(noticeRaw)
const noticeCost = context.measureContent(noticeContent)
+ let charged = true
if (this.ledger.canEmit(this.contextWindowTokens, noticeCost)) {
this.ledger.debit(this.contextWindowTokens, noticeCost, 0)
} else {
- // Throws once the notice overdraft is spent, which stops the turn.
- this.ledger.debitNotice(this.contextWindowTokens, noticeCost)
+ // False once the notice overdraft is spent: the turn stops here.
+ charged = this.ledger.debitNotice(this.contextWindowTokens, noticeCost)
}
return {
...result,
+ ...(charged ? {} : { stopTurn: { message: ATTACHMENT_READ_TURN_STOP_MESSAGE } }),
content: noticeContent,
rawContent: noticeRaw,
is_error: false,
diff --git a/mcp-host/src/core/types.ts b/mcp-host/src/core/types.ts
index 5eb44919b..58532b35e 100644
--- a/mcp-host/src/core/types.ts
+++ b/mcp-host/src/core/types.ts
@@ -328,6 +328,12 @@ export interface ToolResult {
* resume time. Undefined for inline results.
*/
spillover_ref?: string
+ /**
+ * Set only by a trusted tool's `finalizeResult` (after the safety transform):
+ * the turn ends after this batch with `message` as the reply, and no further
+ * model call is made. Later calls of the batch are answered without running.
+ */
+ stopTurn?: { message: string }
}
export interface ToolOutput {
@@ -702,7 +708,7 @@ export type LoopResult =
| { type: 'error'; error: Error }
| {
type: 'exhaustion'
- reason?: 'iteration_limit' | 'task_budget'
+ reason?: 'iteration_limit' | 'task_budget' | 'turn_stop'
message: string
iterations: number
attachments?: Attachment[]