@parcha/agentrun-harness-claude 0.1.0-beta.29 → 0.1.0-beta.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,36 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.31 (2026-11-06)
6
+
7
+ - Agents call a saved MCP server's tools on pi and claude-agent: grant `mcp:<server>/<tool>` in `definition.tools`. A save checks the name against the server's saved tools (`422` naming them). A run's first launch pins the granted tools as saved and the server's URL; its credential reaches only runs that grant one of its tools, over the run's secrets pipe. pi binds each tool in the run's process; claude-agent's own MCP client calls it at the session's model proxy (`/mcp/<server>`, behind the session key), so the CLI never holds the credential. A call follows no redirect, a crash-cut call is answered interrupted and never sent again, a moved server is sent nothing, and the timeline reads `<server> · <tool>`. `features.mcp_client.harnesses` lists the harnesses that run them. Every call passes the run's tool gate and its spend cap.
8
+
9
+ ## 0.1.0-beta.30 (2026-11-05)
10
+
11
+ - A run whose model provider stops the answer on its content filter now ends `failed` with `error.code` `moderated` and
12
+ says so in plain words: "The model provider stopped this answer (its content filter). Rephrase the request, or try
13
+ another model." Before, it ended `run_failed` with the provider's jargon ("Response incomplete: content_filter"). The
14
+ Timeline's error row keeps the harness's words for the stop (pi-ai's on pi, the kernel's on claude-agent and codex). On pi the run reads pi-ai's words for the stop on each API. On
15
+ claude-agent and codex the session's model proxy reads the provider's stop (Anthropic's `refusal`, an OpenAI answer
16
+ `incomplete` for `content_filter`) and the harness ends the turn at once: the CLI no longer asks for the refused answer
17
+ again, turn after turn. Only the turn's own answer request ends it: a side call the CLI makes beside the turn (one
18
+ without the session's tools) that the provider stops is logged and left to the CLI. The refused request is booked at
19
+ the usage its end reports. The kernel exports `CONTENT_FILTERED`, the text such a turn ends with; a provider policy may
20
+ say a stop through `filtered` and a side call through `answers`, and the model proxy tells its machine through
21
+ `onFiltered`.
22
+ - A request you stop under a cap counts the reasoning it never streamed. A model whose reasoning streams only as a summary (the Responses API's reasoning, Claude 4-class thinking) is billed for far more than the summary's bytes. A stop after about 10,000 hidden reasoning tokens on a gpt-5-class model with a 20 KB context cost about $0.106 and counted $0.038, so deliberate stops could pass a cap. A stopped request that reasons now also counts the part of its reasoning budget that did not stream: input + streamed + 1,024 + max(0, reasoning budget - reasoning streamed), never more than its hold. Real usage still replaces the figure when it comes.
23
+ - **On pi:** a reasoning model's stopped request counts its thinking level's budget (on Anthropic's API, the `budget_tokens` it was sent with, for a model whose thinking takes one). A Claude model that thinks adaptively (every current one on Anthropic's API) is sent no budget, and its thinking is bounded only by its output limit, so it counts that limit less 1,024 tokens: in practice its hold. A stop after a 300-byte thinking summary on Sonnet 5.5 with a 20 KB context under a $1 cap counted $0.142 at medium and $0.224 at high, against about $0.45 for 40,000 adaptive thinking tokens. The request's output limit is now the one actually sent: the cap had taken a thinking budget out of it that pi-ai never sends (8,192 tokens at medium), so the request was held at more than it was sent with. With no level, on an API whose model reasons at its own default, it counts its whole output limit. With thinking off on Anthropic's API, on a model whose thinking can be off, nothing more.
24
+ - **Adaptive thinking counts up to the hold.** On every current Claude model, on pi and on `claude-agent`, the provider is given no thinking budget, so a stopped request counts up to the hold the cap took for it. Under a cap with little left beside that hold, the request after the stop can be refused.
25
+ - **On `codex`:** the effort's budget (minimal 1,024, low 2,048, medium 8,192, high 16,384), none at effort `none`, and the output limit when the body names no effort.
26
+ - **On `opencode`:** the same as `codex` (the same Responses API): what a stop counts as streamed is the content its deltas carried, not the wire, plus the unstreamed part of its effort's budget. On the walk through OpenCode's proxy (a request at $100 a million output tokens under a $0.50 cap, stopped after 1,146 characters of answer text after the stream's echo of the request) the stop booked 106,831 bytes, its whole $0.50 hold, and refused "Go on."; it now counts $0.217, and "Go on." goes.
27
+ - **On `claude-agent`:** the thinking budget, or `max_tokens` when thinking is adaptive, for every request that thinks; none with thinking off. Thinking that streamed is subtracted, so a stop after a budget's worth of visible thinking counts nothing on top.
28
+ - **Kernel:** a provider policy may read a request's hidden reasoning from its body (`reasoningHidden`). It may also read the reasoning in each streamed event (`reasoningBytesOf`). The model proxy books a stopped response with both (`stoppedHiddenTokens`, `stoppedReasoningBytes`), and the runner counts all it sent plus the part of the budget its reasoning did not cover.
29
+ - **What streamed is the content, not the wire.** On `claude-agent` and `codex` a stop counted the response's bytes as sent, the provider's framing included: about 11.7 bytes a character of text on the Responses API and 24 on the Messages API. A codex request at $100 a million output under a $0.50 cap, stopped after 1,146 characters, booked its whole hold and refused "Go on.". It now counts each text, reasoning and tool-argument delta's UTF-8 bytes, as pi counts its streamed blocks: $0.217, and the next request goes. A provider policy reads them (`contentBytesOf`).
30
+ - **A stop before the provider's first header** on `claude-agent` and `codex` now counts as a stop with nothing streamed (its input and 1,024 tokens, as on pi), not its whole hold. A response the provider answered with an error status still counts at its hold.
31
+ - A message the person stopped the instant it was sent is no longer lost on claude-agent, and the same window is closed on Codex and OpenCode. Asked "Reply with exactly this code and nothing else: CARRY-CLAUDE-7", stopped within its first second, then told "Go on.", a claude-agent run answered "There's nothing earlier in this conversation for me to continue from": Claude takes a message within its first second, so the stop landed after the harness placed it and before the CLI was handed it, and nothing carried it. Now a stop's settle carries a placed message its CLI never took into the next one, as it carries one stopped before it was placed. On claude-agent that is a message the CLI's own transcript, as the session keeps it, does not hold: that transcript is the history a resumed CLI is given, so a carried message is never sent twice. On Codex it is a message Codex's own rollout, as the session keeps it, does not hold. OpenCode marks a message just before it sends it (`prompt_async`), and a marked message is never carried: a crash between the mark and the send loses it rather than sending it twice. After a stop, no new turn is started.
32
+ - **A recovered message is not carried again.** After a crash between a message's placement and its CLI's record, the recovery message carries its words. It now records which messages it carries, before it goes (a kernel effect by its id on claude-agent, its `PROMPT_STREAM` record on OpenCode). Once the CLI holds the recovery message, a stop's settle and a later recovery both count those messages sent, so nothing is sent twice, even after a second crash. Codex's recovery already did this through its client id.
33
+ - **A follow-up's own prompt** (the host's, named to the settle) is withdrawn and never carried into the person's next message, as the follow-up says: a host prompt that never ran is not sent. A person's message waiting beside it is left as it is.
34
+
5
35
  ## 0.1.0-beta.29 (2026-11-04)
6
36
 
7
37
  - `ClaudeAgentNotInstalled` says, in one line, what is missing and how to install it: the message keeps its prefix ("Claude Agent SDK not installed"), names the SDK, its platform package with the CLI, or the MCP library it brings as a peer, and ends with `; install it with: npm install --save-exact @anthropic-ai/claude-agent-sdk@0.3.286`, which is also on the error as `install` (and exported as `CLAUDE_AGENT_SDK_INSTALL`). A `cliPath` that holds nothing keeps its own message, with no install line. A host that matched the whole message exactly now matches its prefix.
package/dist/adapter.d.ts CHANGED
@@ -93,6 +93,12 @@ export interface ClaudeAgentAdapterOptions {
93
93
  export type ClaudeAgentThinking = "low" | "medium" | "high" | "xhigh" | "max";
94
94
  /** A session's level: the node's thinking, else its effort (minimal thinks at low, never at nothing), else the adapter's. */
95
95
  export declare function thinkingOf(spec: Pick<SessionSpec, "thinking" | "effort">, fallback: ClaudeAgentThinking): ClaudeAgentThinking;
96
+ /**
97
+ * The SDK that is handed no message once the drive is stopped: its prompt stream ends instead, so no turn starts after a
98
+ * stop. Whether a placed message reached the CLI is the CLI's own record, not this hand-over: the SDK writes a message to
99
+ * the CLI's stdin at once, and a stop can kill the CLI before it reads it (settleOpenTurn reads the transcript).
100
+ */
101
+ export declare function withStopEndingPrompts(sdk: ClaudeAgentSdk, signal: () => AbortSignal): ClaudeAgentSdk;
96
102
  /** The pins a CLI is checked against: its sha256 on this platform (where one is recorded) and its version. */
97
103
  export declare function claudeAgentCliPins(): {
98
104
  sha256?: string;
package/dist/adapter.js CHANGED
@@ -15,13 +15,15 @@ import { dirname, join } from "node:path";
15
15
  import { READ_SKILL_FILE, readSkillFileTool, skillProblems } from "@parcha/agentrun-kernel";
16
16
  import { abortedOutcome, openDrive, pendingSubmissions, Restart, SessionHalt } from "@parcha/agentrun-kernel/kernel";
17
17
  import { toolSchemaProblems } from "@parcha/agentrun-kernel";
18
- import { recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
19
- import { checkedOnce, hostHeaderProblems, sha256OfFile } from "@parcha/agentrun-kernel/host";
18
+ import { NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
19
+ import { checkedOnce, hostHeaderProblems, mcpRoute, sha256OfFile } from "@parcha/agentrun-kernel/host";
20
20
  import { findClaudeExecutable, platformSuffix } from "./binary.js";
21
21
  import { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
22
- import { claudeCodeHarness } from "./harness.js";
22
+ import { claudeCodeHarness, lostPrompts } from "./harness.js";
23
+ import { JournalSessionStore } from "./store.js";
23
24
  import { localMachine } from "./host/machine.js";
24
25
  import { serialWriter } from "./serial.js";
26
+ import { MCP_SERVER } from "./transcript.js";
25
27
  import { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION, installedVersion } from "./versions.js";
26
28
  export { CLAUDE_AGENT_CLI_SKILL_NAMES } from "./cli-names.js";
27
29
  /** The pinned CLI's tools the copied harness leaves undecided, off by name in every session (WebSearch unless `webSearch`). */
@@ -64,6 +66,24 @@ export function thinkingOf(spec, fallback) {
64
66
  return "low";
65
67
  return asked && THINKING.has(asked) ? asked : fallback;
66
68
  }
69
+ /**
70
+ * The SDK that is handed no message once the drive is stopped: its prompt stream ends instead, so no turn starts after a
71
+ * stop. Whether a placed message reached the CLI is the CLI's own record, not this hand-over: the SDK writes a message to
72
+ * the CLI's stdin at once, and a stop can kill the CLI before it reads it (settleOpenTurn reads the transcript).
73
+ */
74
+ export function withStopEndingPrompts(sdk, signal) {
75
+ const until = async function* (prompt) {
76
+ for await (const message of prompt) {
77
+ if (signal().aborted)
78
+ return;
79
+ yield message;
80
+ }
81
+ };
82
+ return {
83
+ ...sdk,
84
+ query: ((args) => sdk.query({ ...args, prompt: (typeof args.prompt === "string" ? args.prompt : until(args.prompt)) })),
85
+ };
86
+ }
67
87
  /** The SDK with every query thinking at `level`: adaptive thinking, at that effort. */
68
88
  function thinkingAt(sdk, level) {
69
89
  return {
@@ -288,6 +308,18 @@ export function claudeAgentAdapter(options) {
288
308
  const common = toolSchemaProblems(tool.name, tool.inputSchema);
289
309
  problems.push(...common, ...(common.length ? [] : claudeSchemaProblems(tool.name, tool.inputSchema)));
290
310
  }
311
+ for (const server of spec.mcp?.servers ?? []) {
312
+ if (server.name === MCP_SERVER)
313
+ problems.push(`the MCP server name ${MCP_SERVER} is the adapter's own`);
314
+ for (const tool of server.tools) {
315
+ const name = `mcp__${server.name}__${tool.name}`;
316
+ if (!TOOL_NAME.test(name))
317
+ problems.push(`the MCP tool ${name.slice(0, 80)} is not a name the Claude Agent CLI takes (letters, digits, _ and -, at most 64)`);
318
+ // A remote tool's schema meets the same checks as the host's: the CLI would drop it without a word.
319
+ const common = toolSchemaProblems(name, tool.inputSchema);
320
+ problems.push(...common, ...(common.length ? [] : claudeSchemaProblems(name, tool.inputSchema)));
321
+ }
322
+ }
291
323
  return problems;
292
324
  },
293
325
  async open(spec, io) {
@@ -300,6 +332,9 @@ export function claudeAgentAdapter(options) {
300
332
  // With skills, the model also reads their files (read_skill_file), from the session's own copy of them.
301
333
  const tools = skills.length ? [...spec.tools, readSkillFileTool(join(dir, "plugin", "skills"), skills.map((skill) => ({ name: skill.name, files: Object.keys(skill.files) })))] : spec.tools;
302
334
  const calls = new CallsInFlight();
335
+ // The remote MCP servers' granted tools, as the CLI names them: its own MCP client calls them at the proxy.
336
+ const mcpServers = spec.mcp?.servers ?? [];
337
+ const mcpNames = new Set(mcpServers.flatMap((server) => server.tools.map((tool) => `mcp__${server.name}__${tool.name}`)));
303
338
  // The CLI's own tools offered to the model: Skill only when the session has skills, WebSearch only when it is on.
304
339
  const builtins = [...(skills.length ? ["Skill"] : []), ...(webSearch ? ["WebSearch"] : [])];
305
340
  const acquire = localMachine({
@@ -318,11 +353,13 @@ export function claudeAgentAdapter(options) {
318
353
  ...(options.provider.headers ? { headers: options.provider.headers } : {}),
319
354
  ...(options.log ? { log: options.log } : {}),
320
355
  ...(options.fetch ? { fetch: options.fetch } : {}),
356
+ ...(spec.mcp ? { mcp: { handler: mcpRoute(spec.mcp), tools: [...mcpNames] } } : {}),
321
357
  },
322
358
  });
323
359
  // The SDK this session runs on (the host's, or the one installed beside this package, checked above), thinking at
324
360
  // the session's level.
325
- const sdk = thinkingAt(options.sdk ?? (await import("@anthropic-ai/claude-agent-sdk")), thinkingOf(spec, thinking));
361
+ // Handed nothing once the drive of the moment is stopped (withStopEndingPrompts).
362
+ const sdk = withStopEndingPrompts(thinkingAt(options.sdk ?? (await import("@anthropic-ai/claude-agent-sdk")), thinkingOf(spec, thinking)), () => drive.signal);
326
363
  const harness = claudeCodeHarness({
327
364
  name: CLAUDE_AGENT_ID,
328
365
  sandbox: {
@@ -338,6 +375,7 @@ export function claudeAgentAdapter(options) {
338
375
  // decide (test/tool-off.test.mjs pins the CLI's whole tool set against these lists), but WebSearch when it is on.
339
376
  disallowedTools: CLAUDE_AGENT_ALSO_OFF.filter((name) => !(webSearch && name === "WebSearch")),
340
377
  ...(webSearch ? { providerTools: ["web_search"] } : {}),
378
+ ...(mcpServers.length ? { mcpServers: mcpServers.map((server) => ({ name: server.name, tools: server.tools.map((tool) => tool.name) })) } : {}),
341
379
  model: modelFor(spec),
342
380
  ...(skills.length ? { skills: { plugin: join(dir, "plugin"), names: writeSkillsPlugin(join(dir, "plugin"), skills) } } : {}),
343
381
  ...(options.smallModel ? { smallModel: options.smallModel } : {}),
@@ -352,6 +390,11 @@ export function claudeAgentAdapter(options) {
352
390
  const e = event;
353
391
  if (e?.type === "text" && typeof e.delta === "string")
354
392
  io.onEvent({ type: "text", delta: e.delta });
393
+ // An MCP call, recorded as a built-in's: the host hears of it once its intent is in the session's records.
394
+ if (e?.type === "tool_start" && typeof e.callId === "string" && typeof e.name === "string" && mcpNames.has(e.name)) {
395
+ calls.begin(e.callId);
396
+ io.onEvent({ type: "tool_start", callId: e.callId, name: e.name, args: e.args ?? {} });
397
+ }
355
398
  // The tool bridge's `tool_end` comes once the call's outcome is in the session's records: only then does the host
356
399
  // hear the call ended, with the text recorded.
357
400
  if (e?.type === "tool_end" && typeof e.callId === "string" && typeof e.name === "string") {
@@ -437,13 +480,20 @@ export function claudeAgentAdapter(options) {
437
480
  await ready();
438
481
  void run();
439
482
  },
440
- async settleOpenTurn() {
483
+ async settleOpenTurn(options = {}) {
441
484
  if (state !== "open_turn")
442
485
  throw new Error("agentrun-harness-claude: there is no turn to settle");
443
486
  await ready();
444
487
  // The turn's end in the session's own transcript, as a turn that ends writes it: the next open finds no open turn,
445
- // and the next turn carries no recovery of this one. Nothing is sent.
446
- await settleTurn(drive);
488
+ // and the next turn carries no recovery of this one. Nothing is sent. A prompt the turn placed that the CLI never
489
+ // recorded (the stop came before the CLI read it) is carried into the next message, as an unplaced one is; a
490
+ // follow-up's own is not. The record is the CLI's transcript as the session keeps it (lostPrompts over the
491
+ // journal's transcript store), the history a resumed CLI is given: a message it lacks the next turn's model never
492
+ // saw, so carrying it never sends it twice.
493
+ const folded = drive.state();
494
+ const transcript = new JournalSessionStore(new NativeJournal(drive), { records: await new NativeJournal(drive).read() });
495
+ const unsent = lostPrompts(folded, recoveryNote(folded)?.turn.placed ?? [], transcript);
496
+ await settleTurn(drive, { unsent, ...(options.opening === undefined ? {} : { host: options.opening }) });
447
497
  state = "idle";
448
498
  },
449
499
  async turnEnd() {
package/dist/harness.d.ts CHANGED
@@ -170,6 +170,18 @@ export interface ClaudeCodeHarnessOptions {
170
170
  * `claudeBuiltinReplay` (reads safe).
171
171
  */
172
172
  builtinReplay?: Record<string, ReplayPolicy> | ((name: string) => ReplayPolicy);
173
+ /**
174
+ * Remote MCP servers the CLI's own MCP client calls, each at the session's
175
+ * model proxy (`<modelUrl>/mcp/<name>`, behind the session's key), with the
176
+ * tools granted on each: those are allowed by name (`mcp__<name>__<tool>`)
177
+ * and each call is recorded as a built-in's. They are set over the CLI's
178
+ * stdin (`setMcpServers`), never in its argv. A server that does not
179
+ * connect fails the turn. Default none.
180
+ */
181
+ mcpServers?: readonly {
182
+ readonly name: string;
183
+ readonly tools: readonly string[];
184
+ }[];
173
185
  /** Provider-hosted tools the model may use; default none. `web_search` turns the CLI's WebSearch on, built-ins off or
174
186
  * not: each call recorded as a built-in's (the session's model proxy decides what the provider may run). */
175
187
  providerTools?: readonly ProviderTool[];
@@ -226,6 +238,8 @@ export declare const DEFAULT_MODEL = "claude-sonnet-4-5";
226
238
  export declare const TOOLS_NOTE = "Your only tools are this app's, the mcp__hands__ tools; you have no shell, file, search or web tools of your own.";
227
239
  /** `TOOLS_NOTE` with WebSearch on (`providerTools: ['web_search']`) and the other built-ins off. */
228
240
  export declare const WEB_SEARCH_NOTE = "Your only tools are this app's (the mcp__hands__ tools, if it has any) and WebSearch; you have no shell, file or fetch tools of your own.";
241
+ /** `TOOLS_NOTE` with the app's remote MCP servers (`mcpServers`) and the built-ins off. */
242
+ export declare const MCP_NOTE = "Your only tools are this app's: the mcp__hands__ tools, if it has any, and those of its MCP servers (the other mcp__ tools); you have no shell, file, search or web tools of your own.";
229
243
  /** `TOOLS_NOTE` for a session with no tools at all (built-ins off, no `tools`). */
230
244
  export declare const NO_TOOLS_NOTE = "You have no tools in this session: no shell, file, search or web tools. Answer from the conversation.";
231
245
  /** With the built-ins on (docs/workspaces.md §5.6 "Workspace note"): what `/workspace` is. */
package/dist/harness.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-claude-code/src/harness.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, imports rewritten for AgentRun; patches: 001-gate-always-on, 002-names, 003-comments, 008-tool-description-max, 009-tool-result-barrier-and-refusals, 010-served-tools-with-images, 011-session-skills, 013-recovery-note-system-prompt, 015-web-search, 016-mcp-output-tokens, 017-key-refused
3
+ // Changed by Parcha, imports rewritten for AgentRun; patches: 001-gate-always-on, 002-names, 003-comments, 008-tool-description-max, 009-tool-result-barrier-and-refusals, 010-served-tools-with-images, 011-session-skills, 013-recovery-note-system-prompt, 015-web-search, 016-mcp-output-tokens, 017-key-refused, 019-recovery-covers, 020-mcp-servers
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import { mkdtemp, rm } from 'node:fs/promises';
@@ -23,6 +23,8 @@ export const DEFAULT_MODEL = 'claude-sonnet-4-5';
23
23
  export const TOOLS_NOTE = `Your only tools are this app's, the mcp__${MCP_SERVER}__ tools; you have no shell, file, search or web tools of your own.`;
24
24
  /** `TOOLS_NOTE` with WebSearch on (`providerTools: ['web_search']`) and the other built-ins off. */
25
25
  export const WEB_SEARCH_NOTE = `Your only tools are this app's (the mcp__${MCP_SERVER}__ tools, if it has any) and WebSearch; you have no shell, file or fetch tools of your own.`;
26
+ /** `TOOLS_NOTE` with the app's remote MCP servers (`mcpServers`) and the built-ins off. */
27
+ export const MCP_NOTE = `Your only tools are this app's: the mcp__${MCP_SERVER}__ tools, if it has any, and those of its MCP servers (the other mcp__ tools); you have no shell, file, search or web tools of your own.`;
26
28
  /** `TOOLS_NOTE` for a session with no tools at all (built-ins off, no `tools`). */
27
29
  export const NO_TOOLS_NOTE = 'You have no tools in this session: no shell, file, search or web tools. Answer from the conversation.';
28
30
  /** With the built-ins on (docs/workspaces.md §5.6 "Workspace note"): what `/workspace` is. */
@@ -141,6 +143,23 @@ async function bwrapWorks(machine, signal) {
141
143
  return false;
142
144
  }
143
145
  }
146
+ /**
147
+ * The session's remote MCP servers, each an http entry at the model proxy's
148
+ * `/mcp/<name>` with the session's key, sent over the CLI's stdin (an entry
149
+ * in `options.mcpServers` would be in its argv). The in-process server
150
+ * (`own`) goes with them, since the call replaces the dynamic set. A server
151
+ * that did not connect throws: the turn fails rather than run without its
152
+ * tools. Each call may take `timeoutMs`, what is left of the invocation.
153
+ */
154
+ async function connectMcp(q, machine, names, own, timeoutMs) {
155
+ const entry = (name) => ({ type: 'http', url: `${machine.modelUrl}/mcp/${name}`, headers: { authorization: `Bearer ${machine.modelKey}` }, timeout: Math.floor(timeoutMs), alwaysLoad: true });
156
+ const set = await q.setMcpServers({ ...own, ...Object.fromEntries(names.map((name) => [name, entry(name)])) });
157
+ const status = new Map((await q.mcpServerStatus()).map((server) => [server.name, server]));
158
+ const error = (name) => (set.errors && Object.hasOwn(set.errors, name) ? set.errors[name] : undefined);
159
+ const failed = names.filter((name) => error(name) !== undefined || status.get(name)?.status !== 'connected');
160
+ if (failed.length)
161
+ throw new Error(`the MCP server${failed.length > 1 ? 's' : ''} ${failed.join(', ')} did not connect: ${failed.map((name) => error(name) ?? status.get(name)?.error ?? status.get(name)?.status ?? 'no status').join('; ').slice(0, 300)}`);
162
+ }
144
163
  export function claudeCodeHarness(options = {}) {
145
164
  const tools = options.tools ?? [];
146
165
  const allowed = builtinTools(options.builtins);
@@ -153,6 +172,8 @@ export function claudeCodeHarness(options = {}) {
153
172
  const replay = typeof options.builtinReplay === 'function' ? options.builtinReplay : options.builtinReplay ? (name) => options.builtinReplay[name] ?? claudeBuiltinReplay(name) : claudeBuiltinReplay;
154
173
  const providerTools = options.providerTools ?? [];
155
174
  const webSearch = providerTools.includes('web_search');
175
+ const mcpServers = options.mcpServers ?? [];
176
+ const mcpNames = new Set(mcpServers.flatMap((server) => server.tools.map((tool) => `mcp__${server.name}__${tool}`)));
156
177
  const log = options.log ?? (() => { });
157
178
  let sdk;
158
179
  const loadSdk = () => {
@@ -349,7 +370,8 @@ export function claudeCodeHarness(options = {}) {
349
370
  return name === asked ? allow() : allow({ ...input, skill: name });
350
371
  }
351
372
  // WebSearch, when on, takes the built-ins' path below: its intent recorded before it runs.
352
- if (!builtinsOn && !(webSearch && hook.tool_name === 'WebSearch'))
373
+ // WebSearch and a granted MCP tool too.
374
+ if (!builtinsOn && !(webSearch && hook.tool_name === 'WebSearch') && !mcpNames.has(hook.tool_name))
353
375
  return deny("Not run: this session's only tools are its own.");
354
376
  if (ctx.signal.aborted)
355
377
  return deny('the session stopped');
@@ -446,6 +468,9 @@ export function claudeCodeHarness(options = {}) {
446
468
  // A host tool's result within the host's bound reaches the model whole (each tool is listed with it, too).
447
469
  mcpOutputTokens: MCP_OUTPUT_TOKENS,
448
470
  });
471
+ // MCP tools are offered whole, never deferred behind the CLI's tool search, which the session's proxy does not carry.
472
+ if (mcpServers.length)
473
+ vmEnv.ENABLE_TOOL_SEARCH = 'false';
449
474
  const sdkEnv = { ...vmEnv, CLAUDE_CONFIG_DIR: configDir };
450
475
  const disallowed = [...CLAUDE_BUILTINS_OFF, ...(providerTools.includes('web_search') ? [] : ['WebSearch']), ...(options.disallowedTools ?? [])].filter((name) => !(skills && name === 'Skill'));
451
476
  const sessionId = uuidFrom(ctx.runId);
@@ -468,7 +493,7 @@ export function claudeCodeHarness(options = {}) {
468
493
  hooks,
469
494
  ...(ownSandbox ? { sandbox: claudeSandboxSettings(machine, sandbox.network) } : {}),
470
495
  ...(bridge.tools.length ? { mcpServers: { [MCP_SERVER]: server } } : {}),
471
- allowedTools: bridge.tools.map((t) => `mcp__${MCP_SERVER}__${t.name}`),
496
+ allowedTools: [...bridge.tools.map((t) => `mcp__${MCP_SERVER}__${t.name}`), ...mcpNames],
472
497
  permissionMode: 'dontAsk',
473
498
  strictMcpConfig: true,
474
499
  // No user, project or local settings (and so no CLAUDE.md): a model-planted .claude/ on the Drive is ignored.
@@ -480,7 +505,7 @@ export function claudeCodeHarness(options = {}) {
480
505
  systemPrompt: {
481
506
  type: 'preset',
482
507
  preset: 'claude_code',
483
- append: [builtinsOn ? DRIVE_NOTE : webSearch ? WEB_SEARCH_NOTE : bridge.tools.length ? TOOLS_NOTE : NO_TOOLS_NOTE, options.instructions, recovered].filter(Boolean).join('\n\n'),
508
+ append: [builtinsOn ? DRIVE_NOTE : webSearch ? WEB_SEARCH_NOTE : mcpServers.length ? MCP_NOTE : bridge.tools.length ? TOOLS_NOTE : NO_TOOLS_NOTE, options.instructions, recovered].filter(Boolean).join('\n\n'),
484
509
  snapshot: !recovered,
485
510
  },
486
511
  ...(store.hasSession ? { resume: sessionId } : { sessionId }),
@@ -502,6 +527,8 @@ export function claudeCodeHarness(options = {}) {
502
527
  };
503
528
  const q = query({ prompt: input, options: queryOptions });
504
529
  const messages = q[Symbol.asyncIterator]();
530
+ if (mcpServers.length)
531
+ await connectMcp(q, machine, mcpServers.map((server) => server.name), bridge.tools.length ? { [MCP_SERVER]: server } : {}, Math.max(1_000, deadline - Date.now()));
505
532
  const send = async (text, placed, how = {}) => {
506
533
  // The drive's first message says, once, what the sandbox told it (a lost Drive).
507
534
  if (notes) {
@@ -526,6 +553,9 @@ export function claudeCodeHarness(options = {}) {
526
553
  if (first && how.priority !== 'next' && !how.synthetic)
527
554
  ledger.turn(first);
528
555
  const uuid = !first ? randomUUID() : how.synthetic ? uuidFrom(`note:${first}`) : uuidFrom(first);
556
+ // A recovery message carries placed prompts' words: which, under its uuid, before it goes (lostPrompts reads it).
557
+ if (how.covers?.length)
558
+ await ctx.effect(`covers:${uuid}`, { name: 'covers', replay: 'safe', input: { ids: how.covers } }, async () => true);
529
559
  outstanding.add(uuid);
530
560
  input.push({
531
561
  type: 'user',
@@ -658,7 +688,8 @@ export function claudeCodeHarness(options = {}) {
658
688
  ledger.turn(open.placed[0] ?? `open:${open.since}`);
659
689
  // The CLI answers again from the interrupted step: what a reader saw of its reply is replaced by what the log kept.
660
690
  ctx.live(restartEvent(note.turn));
661
- await send(recoveryUserTurn(ctx.state(), store, note.pending), note.pending, { synthetic: 'recovery' });
691
+ const covers = [...(open ? lostPrompts(ctx.state(), open.placed, store) : []), ...note.pending.map((s) => s.id)];
692
+ await send(recoveryUserTurn(ctx.state(), store, note.pending), note.pending, { synthetic: 'recovery', covers });
662
693
  await runTurn();
663
694
  }
664
695
  // The inbox, one submission per turn.
@@ -810,8 +841,10 @@ const RECOVERY_STATUS = {
810
841
  */
811
842
  export function lostPrompts(state, placed, store) {
812
843
  const said = new Set(state.submissions.filter((s) => s.kind === 'prompt' || s.kind === 'steer' || s.kind === 'followUp').map((s) => s.id));
844
+ // A prompt a recovery message carried (its cover, by the message's uuid) is recorded once the transcript holds that message.
845
+ const covered = new Set(state.effectOrder.filter((e) => e.name === 'covers' && e.key.startsWith('covers:') && store.hasUser(e.key.slice('covers:'.length))).flatMap((e) => e.input?.ids ?? []));
813
846
  return placed.filter((id) => {
814
- if (!said.has(id))
847
+ if (!said.has(id) || covered.has(id))
815
848
  return false;
816
849
  const placement = state.effectOrder.find((e) => e.name === 'place' && e.key.startsWith('place:') && e.placed.includes(id));
817
850
  const first = placement ? placement.key.slice('place:'.length) : id;
@@ -1,5 +1,5 @@
1
1
  import { type ChildProcess } from "node:child_process";
2
- import { type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
2
+ import { type McpHandler, type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
3
3
  import type { AcquireMachine, MachineSpawn, SessionMachine, SessionProcess } from "./process.js";
4
4
  import { type AnthropicPolicyOptions } from "./policy.js";
5
5
  /** The variables a child takes from this process, when they are set. */
@@ -32,6 +32,11 @@ export interface LocalMachineOptions {
32
32
  builtins?: readonly string[];
33
33
  /** Admit Anthropic's web search server tool, the one the CLI's WebSearch asks for. */
34
34
  webSearch?: boolean;
35
+ /** The session's remote MCP servers, served at `/mcp/<server>`, and their granted tools as the CLI names them. */
36
+ mcp?: {
37
+ handler: McpHandler;
38
+ tools: readonly string[];
39
+ };
35
40
  /** The input a request carrying it may read in beyond its body, for its input bound (anthropicPolicy). */
36
41
  webSearchAllowance?: number;
37
42
  /** The tokens' price; each web search a response reports is added to it (`withWebSearches`). */
@@ -130,6 +130,7 @@ export function localMachine(options) {
130
130
  ...(route.models.smallModel ? { smallModel: route.models.smallModel } : {}),
131
131
  tools: options.proxy.tools,
132
132
  ...(options.proxy.builtins?.length ? { builtins: options.proxy.builtins } : {}),
133
+ ...(options.proxy.mcp ? { mcpTools: options.proxy.mcp.tools } : {}),
133
134
  ...(options.proxy.maxOutputTokens ? { maxOutputTokens: options.proxy.maxOutputTokens } : {}),
134
135
  ...(options.proxy.webSearch ? { webSearch: true, ...(options.proxy.webSearchAllowance !== undefined ? { webSearchAllowance: options.proxy.webSearchAllowance } : {}) } : {}),
135
136
  ...(options.proxy.auth ? { auth: options.proxy.auth } : {}),
@@ -141,7 +142,10 @@ export function localMachine(options) {
141
142
  credential: async () => (await route.credential()) ?? "",
142
143
  ...(options.proxy.price ? { price: withWebSearches(options.proxy.price) } : {}),
143
144
  ...(options.proxy.headers ? { headers: options.proxy.headers } : {}),
145
+ ...(options.proxy.mcp ? { mcp: options.proxy.mcp.handler } : {}),
144
146
  ...(options.proxy.log ? { log: options.proxy.log } : {}),
147
+ // The provider stopped the turn's answer on its content filter: no retry of it can pass, so the turn ends at once.
148
+ onFiltered: (message) => ctx.halt?.(new Error(message)),
145
149
  onResponse: ({ path, status }) => {
146
150
  if (path !== "/v1/messages/count_tokens" || counted)
147
151
  return;
@@ -28,6 +28,8 @@ export interface AnthropicPolicyOptions {
28
28
  tools: readonly string[];
29
29
  /** The CLI's own tools the session has, offered by their own names beside its tools (`Skill`, when it has skills). */
30
30
  builtins?: readonly string[];
31
+ /** The granted tools of the session's remote MCP servers, as the CLI names them (`mcp__<server>__<tool>`). */
32
+ mcpTools?: readonly string[];
31
33
  /** The most output tokens one request may ask for. Default 128 000, what the pinned CLI asks for on current models. */
32
34
  maxOutputTokens?: number;
33
35
  /** Admit Anthropic's web search server tool (`CLAUDE_WEB_SEARCH_TOOL`), exactly as the pinned CLI asks for it; every
@@ -57,6 +59,17 @@ export declare function anthropicOutputAsked(body: Record<string, unknown>): num
57
59
  /** The least output a Messages body may be limited to and still answer: 1,024 tokens, and with extended thinking on (a
58
60
  * budget) the provider's least budget beside them. Adaptive thinking takes no budget, so it needs none. */
59
61
  export declare function anthropicOutputLeast(body: Record<string, unknown>): number;
62
+ /** The thinking tokens a Messages request may bill that its stream never shows: Claude 4-class models stream only a
63
+ * summary of their thinking (and a redacted block shows none of it), so a request that thinks counts its thinking
64
+ * budget, or its `max_tokens` when its thinking is adaptive (no budget); one with thinking off, none. A stopped request
65
+ * counts the part of it that did not stream (less `anthropicReasoningBytes` of what it sent), never past its hold. */
66
+ export declare function anthropicReasoningHidden(body: Record<string, unknown>): number;
67
+ /** The bytes of thinking one Messages stream event carries: a thinking delta's text, UTF-8; 0 for text, a tool call's
68
+ * JSON, a signature and every other event. */
69
+ export declare function anthropicReasoningBytes(event: string): number;
70
+ /** The bytes of content one Messages stream event carries: a text, thinking or tool-input delta's text, UTF-8, never
71
+ * the framing around it; 0 for a signature and every other event. */
72
+ export declare function anthropicContentBytes(event: string): number;
60
73
  /** A Messages body with its output limited to `max` tokens, thinking included: `max_tokens` at most `max`, never raised,
61
74
  * and a thinking budget squeezed under it so that 1,024 tokens stay for the answer, never below the provider's least
62
75
  * budget. Only numbers get smaller, so the body is never longer. */
@@ -77,6 +90,14 @@ export declare function withWebSearches(price: (model: string, usage: ProxyUsage
77
90
  * own and one that does not parse is skipped (the proxy keeps only the head and tail of a long answer). A stream that
78
91
  * never stopped, or an answer with no readable usage, is unknown. */
79
92
  export declare function anthropicUsage(text: string): AnthropicUsage | undefined;
93
+ /** Whether a Messages answer ended on the provider's refusal (`stop_reason: "refusal"`, its content filter): a whole body's
94
+ * `stop_reason`, or a stream's last `message_delta` stop. Read by parsing, never by matching text, each SSE `data:` line
95
+ * on its own, as anthropicUsage reads them. */
96
+ export declare function anthropicFiltered(text: string): boolean;
97
+ /** Whether a Messages body (as `apply` kept it) is the turn's answer request: it offers the model one of the session's
98
+ * tools. The CLI's side calls (a title, a summary, a web search's own request) offer none of them; in a session with no
99
+ * tools no request can be told from one, so each is the turn's. */
100
+ export declare function anthropicAnswers(body: Record<string, unknown>, options: Pick<AnthropicPolicyOptions, "tools" | "builtins">): boolean;
80
101
  /** The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources): the
81
102
  * tool-use system prompt when it has tools, and for each image the most it can be billed as, beyond its bytes. None
82
103
  * can be said for a body with the web search tool: the provider bills the pages it finds as input, on each of its
@@ -185,6 +185,42 @@ export function anthropicOutputAsked(body) {
185
185
  export function anthropicOutputLeast(body) {
186
186
  return isPlain(body.thinking) && body.thinking.type === "enabled" ? ANSWER_TOKENS_LEAST + THINKING_BUDGET_LEAST : ANSWER_TOKENS_LEAST;
187
187
  }
188
+ /** The thinking tokens a Messages request may bill that its stream never shows: Claude 4-class models stream only a
189
+ * summary of their thinking (and a redacted block shows none of it), so a request that thinks counts its thinking
190
+ * budget, or its `max_tokens` when its thinking is adaptive (no budget); one with thinking off, none. A stopped request
191
+ * counts the part of it that did not stream (less `anthropicReasoningBytes` of what it sent), never past its hold. */
192
+ export function anthropicReasoningHidden(body) {
193
+ const thinking = body.thinking;
194
+ if (!isPlain(thinking))
195
+ return 0;
196
+ if (thinking.type === "enabled")
197
+ return typeof thinking.budget_tokens === "number" && Number.isFinite(thinking.budget_tokens) && thinking.budget_tokens > 0 ? thinking.budget_tokens : anthropicOutputAsked(body) ?? 0;
198
+ if (thinking.type === "adaptive")
199
+ return anthropicOutputAsked(body) ?? 0;
200
+ return 0;
201
+ }
202
+ /** The bytes of thinking one Messages stream event carries: a thinking delta's text, UTF-8; 0 for text, a tool call's
203
+ * JSON, a signature and every other event. */
204
+ export function anthropicReasoningBytes(event) {
205
+ const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
206
+ if (!data.startsWith("{"))
207
+ return 0;
208
+ const parsed = JSON.parse(data);
209
+ return parsed.type === "content_block_delta" && parsed.delta?.type === "thinking_delta" && typeof parsed.delta.thinking === "string" ? Buffer.byteLength(parsed.delta.thinking, "utf8") : 0;
210
+ }
211
+ /** The bytes of content one Messages stream event carries: a text, thinking or tool-input delta's text, UTF-8, never
212
+ * the framing around it; 0 for a signature and every other event. */
213
+ export function anthropicContentBytes(event) {
214
+ const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
215
+ if (!data.startsWith("{"))
216
+ return 0;
217
+ const parsed = JSON.parse(data);
218
+ if (parsed.type !== "content_block_delta" || !parsed.delta)
219
+ return 0;
220
+ const { type, text, thinking, partial_json: json } = parsed.delta;
221
+ const piece = type === "text_delta" ? text : type === "thinking_delta" ? thinking : type === "input_json_delta" ? json : undefined;
222
+ return typeof piece === "string" ? Buffer.byteLength(piece, "utf8") : 0;
223
+ }
188
224
  /** A Messages body with its output limited to `max` tokens, thinking included: `max_tokens` at most `max`, never raised,
189
225
  * and a thinking budget squeezed under it so that 1,024 tokens stay for the answer, never below the provider's least
190
226
  * budget. Only numbers get smaller, so the body is never longer. */
@@ -219,7 +255,7 @@ export function applyAnthropic(body, route, options) {
219
255
  blocks(message.content, "a message's content");
220
256
  }
221
257
  blocks(body.system, "system");
222
- const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? [])]);
258
+ const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? []), ...(options.mcpTools ?? [])]);
223
259
  const tools = ownTools(body.tools, allowed, options.webSearch);
224
260
  const choice = body.tool_choice;
225
261
  const chosen = isPlain(choice) && typeof choice.name === "string" && (allowed.has(choice.name) || (options.webSearch === true && choice.name === "web_search"));
@@ -305,6 +341,43 @@ export function anthropicUsage(text) {
305
341
  const lastDelta = events.filter((e) => e.type === "message_delta").at(-1)?.usage;
306
342
  return bookedUsage({ ...startUsage, ...(isPlain(lastDelta) ? lastDelta : {}) });
307
343
  }
344
+ /** Whether a Messages answer ended on the provider's refusal (`stop_reason: "refusal"`, its content filter): a whole body's
345
+ * `stop_reason`, or a stream's last `message_delta` stop. Read by parsing, never by matching text, each SSE `data:` line
346
+ * on its own, as anthropicUsage reads them. */
347
+ export function anthropicFiltered(text) {
348
+ const lines = text.split(/\r?\n/);
349
+ if (!lines.some((line) => line.startsWith("data:") || line.startsWith("event:"))) {
350
+ let body;
351
+ try {
352
+ body = JSON.parse(text);
353
+ }
354
+ catch {
355
+ return false;
356
+ }
357
+ return isPlain(body) && body.stop_reason === "refusal";
358
+ }
359
+ let stop;
360
+ for (const line of lines) {
361
+ if (!line.startsWith("data:"))
362
+ continue;
363
+ try {
364
+ const event = JSON.parse(line.slice(5));
365
+ if (isPlain(event) && event.type === "message_delta" && isPlain(event.delta) && "stop_reason" in event.delta)
366
+ stop = event.delta.stop_reason;
367
+ }
368
+ catch { /* cut at the kept window's edge, or not JSON: skipped */ }
369
+ }
370
+ return stop === "refusal";
371
+ }
372
+ /** Whether a Messages body (as `apply` kept it) is the turn's answer request: it offers the model one of the session's
373
+ * tools. The CLI's side calls (a title, a summary, a web search's own request) offer none of them; in a session with no
374
+ * tools no request can be told from one, so each is the turn's. */
375
+ export function anthropicAnswers(body, options) {
376
+ const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? [])]);
377
+ if (allowed.size === 0)
378
+ return true;
379
+ return Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && typeof tool.name === "string" && allowed.has(tool.name));
380
+ }
308
381
  /** The Claude Agent CLI's provider policy for one session. */
309
382
  /** The image blocks in `value`, at any depth (a tool's result holds them). */
310
383
  function imagesIn(value) {
@@ -353,7 +426,12 @@ export function anthropicPolicy(options) {
353
426
  serverInputOverhead: options.webSearchAllowance === undefined ? anthropicServerInputOverhead : (body) => anthropicServerInputOverhead(body, options.webSearchAllowance),
354
427
  outputAsked: anthropicOutputAsked,
355
428
  outputLeast: anthropicOutputLeast,
429
+ reasoningHidden: anthropicReasoningHidden,
430
+ reasoningBytesOf: anthropicReasoningBytes,
431
+ contentBytesOf: anthropicContentBytes,
356
432
  limitOutput: limitAnthropicOutput,
357
433
  usageOf: anthropicUsage,
434
+ filtered: anthropicFiltered,
435
+ answers: (body) => anthropicAnswers(body, options),
358
436
  };
359
437
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-harness-claude",
3
- "version": "0.1.0-beta.29",
3
+ "version": "0.1.0-beta.31",
4
4
  "description": "The Claude Agent SDK as an AgentRun harness: the host's tools as its only tools, its model behind a loopback proxy, durable in AgentRun's own store.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -44,8 +44,8 @@
44
44
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
45
45
  },
46
46
  "dependencies": {
47
- "@parcha/agentrun-dsl": "0.1.0-beta.29",
48
- "@parcha/agentrun-kernel": "0.1.0-beta.29"
47
+ "@parcha/agentrun-dsl": "0.1.0-beta.31",
48
+ "@parcha/agentrun-kernel": "0.1.0-beta.31"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@anthropic-ai/claude-agent-sdk": "0.3.286",