@parcha/agentrun-harness-claude 0.1.0-beta.37 → 0.1.0-beta.38

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,32 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.38 (2026-11-14)
6
+
7
+ - A run's MCP tools are host tools on every harness: each call passes the run's one tool gate before anything is sent, and the runner calls the server with the credential, books the call and records it, as it does any host tool. opencode now runs MCP tools (`features.mcp_client.harnesses` lists it, and an opencode agent granted `mcp:<server>/<tool>` saves and runs). claude-agent offers a granted tool as `mcp__hands__mcp__<server>__<tool>` and codex as `mcp_<server>__<tool>` (Codex refuses a dynamic tool named `mcp__*`); the Timeline, tool settings and approvals still name it `mcp:<server>/<tool>`. A call set to ask on claude-agent, codex or opencode holds the CLI's call while the run waits (no "waits for a person's approval" result row while it is parked); on the person's allow the resumed session gets the call's own result, no `[tool approval]` message. A codex run no longer fails at its start when a granted server can't be reached: the server's error shows at the first call, as on pi. On a code-mode Codex model, a script's tool call held for a person's approval runs once on their allow, under its own call id, and the script's cut-off `exec` reads its result (or, when the `exec` had yielded, the model's `wait` on its cell); before, the resume told the model the call may have run, and the call the model made again asked again, so the allow never reached a call.
8
+
9
+ Who breaks: a run parked on an MCP call at the MCP door before this version does not resume its call: cancel it and start it again. A Codex thread started before this version loses its MCP tools when it resumes (Codex resumes a thread with the dynamic tools it started with): start a new run. Code built on the kernel's MCP door breaks too. Removed: `SessionSpec.mcp`, `SessionMcp`, `McpClient`, `AdapterCapabilities` and `AgentAdapter.capabilities()`, `AdapterFacts.mcp`, `ModelProxyOptions.mcp`, `mcpRoute`, `McpHandler` and `McpRouteOptions` (`@parcha/agentrun-kernel/host`), and `McpCallResult.parked`. Hand a session its MCP tools as host tools in `SessionSpec.tools` instead.
10
+ - A provider-native web search's fee is one constant, `NATIVE_SEARCH_USD` ($0.01, $10 per 1,000), instead of three copies. The price does not change.
11
+ - Kernel: `@parcha/agentrun-kernel/host` exports `NATIVE_SEARCH_USD`. The Claude and Codex proxy policies and the runner's hosted search all read it.
12
+ - `@parcha/agentrun-harness-claude` no longer exports `CLAUDE_WEB_SEARCH_USD`; read `NATIVE_SEARCH_USD` from `@parcha/agentrun-kernel/host`.
13
+ - One discovery system. A run lists every tool until its catalog tools (MCP and monid) pass 20; then they are deferred, found with `tools_search` and run with `tools_call`. Under 20 there is no search or call, and Claude Agent's own tool search follows the same threshold and gets neither of ours. `codemode`, `tools_search` and `tools_call` each have a tool-settings key (allow by default); a tool set to deny is not offered at all.
14
+ - Every harness (pi, Claude Agent, OpenCode and Codex) now offers three host tools over the run's own tools: `tools_search`, `tools_call` and `codemode`. Codex gets the first two and keeps its own code mode. With MCP servers on a Claude Agent run, the CLI's own tool search is on.
15
+ - `tools_search {query, limit?}` ranks the run's tools by what they do (BM25 over each tool's description and argument words) and answers each match's name, description and input schema. It lists only tools the run may call: never one set to deny, and never the three tools themselves.
16
+ - `tools_call {name, args}` calls one of the run's tools by name. The call is asked about, recorded and booked as that tool's own call, under `<callId>/call`. An ask parks the run, and once approved the call runs once. A deny refuses it in the gate's words. A call of an unknown name, of `tools_call` itself, of `tools_search` or of `codemode` is refused in words, and nothing runs.
17
+ - `codemode {script}` runs a JavaScript script in a QuickJS sandbox. Its `await tools.<name>(args)` calls are each the run's own call, gated, recorded and booked under `<callId>/s<n>`. The sandbox has the tools and nothing else of the run: no environment, keys, files, network or timers.
18
+ - A call inside a script that needs approval follows Codex's rule. The run parks. Once a person answers, the script runs again: recorded calls answer from their records, the parked call runs once (or is refused), its outcome is the script's answer, and the rest of the script does not run.
19
+ - A call made through `tools_call` or a script answers what a direct call answers: its text and images to the model, and in a script its value (a tool's structured result, else its text). On pi the harness's own tools (an extension's, the browser's) are found and called the same way as the host's.
20
+ - A refused call inside a script ends the script with the refusal's words.
21
+ - After a crash, a call that was cut off is told as possibly done, and it is not run again.
22
+ - A paid call made through `tools_call` or a script books exactly as a direct call does: held before it is sent, under the cap, and settled once. The cap's wrap-up still refuses the model's own next call.
23
+ - The three tools' definitions ride on every model request: about 2,000 bytes, 639 tokens on Sonnet. So the smallest caps the README measures rise. A pi desktop run on Sonnet through a gateway now needs $0.07 for its first request and $0.13 for five steps in `strict` mode, or $0.07 in `expected` mode (it was $0.06, $0.12 and $0.06). Straight to Anthropic, it needs $0.04 for its first request, and five steps still need $0.09 in `strict` mode and $0.06 in `expected` mode.
24
+ - Claude Agent: with an MCP server's tools on the run, the CLI runs with `ENABLE_TOOL_SEARCH=true` and its ToolSearch. The run's MCP tools reach the model through `hands` only once ToolSearch finds them, and every other tool of the session loads as before. The session's proxy admits the tool search's beta (`advanced-tool-use-2025-11-20`), ToolSearch and its placeholder. It also admits a `tool_reference` block, inside a tool result only, that names one of the session's own tools. Without MCP tools, all of these stay refused.
25
+ - A server started by `agentrun-serve` (and so by `npx agentrun`) can start a worker thread from a file. The launcher no longer passes Node `--input-type`, which a worker inherits and Node refuses. Before this, a `codemode` script there failed with "--input-type can only be used with string input via --eval, --print, or STDIN", and so did pi's code mode on a desktop or a phone.
26
+ - Three follow-ups to the tools_search / tools_call / codemode rule, found in a live walk.
27
+ - Claude Agent now follows the same switch as every other harness. With `tools_search` or `tools_call` set to deny, its own tool search is off and every tool is listed; before, it deferred a run's catalog tools behind its own ToolSearch whatever the setting said. The server makes the one decision (`SessionSpec.deferCatalog`) and Claude Agent's adapter obeys it.
28
+ - Settings → Tools lists `tools_search`, `tools_call` and `codemode`, each allow or deny, allow by default. They are in `capabilities.tools` with `meta: true` (no grant: the agent editor does not offer them) and a one-line blurb.
29
+ - codemode's description names real functions of the run (`tools.<name>`, the first three) and says to leave off the prefix a harness shows in the model's own tool list (`hands_`, `mcp__hands__`). On OpenCode a script wrote `tools.hands_mcp__hn__…` five times in five runs and failed.
30
+
5
31
  ## 0.1.0-beta.37 (2026-11-13)
6
32
 
7
33
  - A web_search setting of deny or ask now applies to a Claude Agent or Codex run's own web search at its next search, including a run that started while it was allow. Before, the setting was read only when the run started, so a run that started with native search kept searching after the setting changed.
package/README.md CHANGED
@@ -35,7 +35,7 @@ const runNode = createHarnessRunner(
35
35
  of them: nothing runs, writes or fetches.
36
36
  - **Claude's own WebSearch, by option.** `webSearch: true` turns on the CLI's WebSearch and nothing else of its own: the
37
37
  proxy then admits Anthropic's web search server tool exactly as the pinned CLI sends it, every other hosted tool stays
38
- refused, and each search the provider reports is booked at $10 per 1,000 (`CLAUDE_WEB_SEARCH_USD`) beside the tokens,
38
+ refused, and each search the provider reports is booked at $10 per 1,000 (`NATIVE_SEARCH_USD`) beside the tokens,
39
39
  into the session's cost and spend cap. A search request has no input bound unless `webSearchAllowance` gives the input
40
40
  tokens it may read in beyond its body. WebFetch stays off. Default off.
41
41
  - **The model behind a proxy.** The CLI talks to a model proxy on the loopback interface with a key of its session's
package/dist/adapter.d.ts CHANGED
@@ -60,7 +60,7 @@ export interface ClaudeAgentAdapterOptions {
60
60
  skills?: readonly ClaudeAgentSkill[];
61
61
  /** Claude's own WebSearch, and nothing else of the CLI's: the model may call it, and the CLI runs each call as a request
62
62
  * of its own through the session's model proxy with Anthropic's web search server tool, the one hosted tool that proxy
63
- * then admits. Each search the provider reports is booked at `CLAUDE_WEB_SEARCH_USD` on top of `price`, into the
63
+ * then admits. Each search the provider reports is booked at `NATIVE_SEARCH_USD` (kernel/host) on top of `price`, into the
64
64
  * session's cost and so its spend cap. WebFetch stays off (it would fetch from the CLI's own process). Default off. */
65
65
  webSearch?: boolean;
66
66
  /** With `webSearch`: the input tokens a search request may read in beyond its body, added to its input bound, so a cap
package/dist/adapter.js CHANGED
@@ -19,11 +19,10 @@ import { checkedOnce, checkedOnceAsync, hostHeaderProblems, startModelProxy } fr
19
19
  import { anthropicPolicy, withWebSearches } from "./host/policy.js";
20
20
  import { findClaudeExecutable, platformSuffix } from "./binary.js";
21
21
  import { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
22
- import { claudeCodeHarness, lostPrompts } from "./harness.js";
22
+ import { claudeCodeHarness, claudeToolSearch, lostPrompts } from "./harness.js";
23
23
  import { JournalSessionStore } from "./store.js";
24
- import { CLAUDE_MCP_CLIENT, localMachine } from "./host/machine.js";
24
+ import { localMachine } from "./host/machine.js";
25
25
  import { serialWriter } from "./serial.js";
26
- import { MCP_SERVER } from "./transcript.js";
27
26
  import { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION, installedVersion } from "./versions.js";
28
27
  export { CLAUDE_AGENT_CLI_SKILL_NAMES } from "./cli-names.js";
29
28
  /** The pinned CLI's tools the copied harness leaves undecided, off by name in every session (WebSearch unless `webSearch`). */
@@ -231,6 +230,7 @@ function kernelTool(tool, io, maxImageBytes, calls) {
231
230
  description: tool.description,
232
231
  inputSchema: tool.inputSchema,
233
232
  replay: tool.replay,
233
+ ...(tool.nests ? { nests: true } : {}),
234
234
  async execute(input, effect) {
235
235
  // The effect's step is `tool:<the CLI's tool_use id>#<attempt>`: the host sees the CLI's call id.
236
236
  const callId = (effect.stepId ?? "").replace(/^tool:/, "").replace(/#\d+$/, "");
@@ -238,21 +238,27 @@ function kernelTool(tool, io, maxImageBytes, calls) {
238
238
  const attempt = Number(/#(\d+)$/.exec(effect.stepId ?? "")?.[1] ?? 0);
239
239
  // In flight, and past the pause's check, before the host hears of it: a pause the host starts on this tool_start
240
240
  // waits for this call rather than refusing it.
241
- calls.begin(callId);
241
+ // A tool that nests calls has no intent of its own to wait for (each of its calls begins here as its own): a pause
242
+ // never waits on it, so a nested call that parks the run does not hold the pause.
243
+ if (!tool.nests)
244
+ calls.begin(callId);
242
245
  // A guard: a call begun during a pause is not run; the bridge's per-drive mutex keeps it unreachable while calls are serial, and its test lands with the fan-out PR.
243
246
  if (calls.draining)
244
247
  throw new Error(`${tool.name} was not run: the session is pausing`);
245
248
  io.onEvent({ type: "tool_start", callId, name: tool.name, args: input });
246
- const result = await tool.call(input, { callId, signal: effect.signal, attempt });
249
+ // A tool that nests calls (tools_call, codemode) gets the session's tools as its nested calls, through the bridge.
250
+ const result = await tool.call(input, { callId, signal: effect.signal, attempt, ...(effect.nested ? { nested: effect.nested } : {}) });
247
251
  if (result.isError)
248
252
  throw new Error(result.text);
253
+ // Its value, recorded with the outcome: a script's nested call is answered it (meta-tools.ts), as Codex's adapter keeps it.
254
+ const structured = result.structured !== undefined ? { structured: result.structured } : {};
249
255
  if (!result.images?.length)
250
- return result.text;
256
+ return result.structured === undefined ? result.text : { text: result.text, ...structured };
251
257
  // An image the model can't be sent is the call's error, by the tool's name and the image, not a request refused later.
252
258
  const wrong = toolImageProblems(tool.name, result.images, maxImageBytes);
253
259
  if (wrong)
254
260
  throw new Error(wrong);
255
- return { text: result.text, images: result.images.map((image) => ({ mimeType: image.mimeType, data: image.data })) };
261
+ return { text: result.text, images: result.images.map((image) => ({ mimeType: image.mimeType, data: image.data })), ...structured };
256
262
  },
257
263
  };
258
264
  }
@@ -299,7 +305,6 @@ export function claudeAgentAdapter(options) {
299
305
  };
300
306
  return {
301
307
  id: CLAUDE_AGENT_ID,
302
- capabilities: () => ({ mcpClient: CLAUDE_MCP_CLIENT }),
303
308
  check(spec) {
304
309
  const problems = [];
305
310
  if (spec.context === "fork")
@@ -317,18 +322,6 @@ export function claudeAgentAdapter(options) {
317
322
  const common = toolSchemaProblems(tool.name, tool.inputSchema);
318
323
  problems.push(...common, ...(common.length ? [] : claudeSchemaProblems(tool.name, tool.inputSchema)));
319
324
  }
320
- for (const server of spec.mcp?.servers ?? []) {
321
- if (server.name === MCP_SERVER)
322
- problems.push(`the MCP server name ${MCP_SERVER} is the adapter's own`);
323
- for (const tool of server.tools) {
324
- const name = `mcp__${server.name}__${tool.name}`;
325
- if (!TOOL_NAME.test(name))
326
- problems.push(`the MCP tool ${name.slice(0, 80)} is not a name the Claude Agent CLI takes (letters, digits, _ and -, at most 64)`);
327
- // A remote tool's schema meets the same checks as the host's: the CLI would drop it without a word.
328
- const common = toolSchemaProblems(name, tool.inputSchema);
329
- problems.push(...common, ...(common.length ? [] : claudeSchemaProblems(name, tool.inputSchema)));
330
- }
331
- }
332
325
  return problems;
333
326
  },
334
327
  async open(spec, io) {
@@ -341,9 +334,6 @@ export function claudeAgentAdapter(options) {
341
334
  // With skills, the model also reads their files (read_skill_file), from the session's own copy of them.
342
335
  const tools = skills.length ? [...spec.tools, hostedTool(io, readSkillFileTool(join(dir, "plugin", "skills"), skills.map((skill) => ({ name: skill.name, files: Object.keys(skill.files) }))))] : spec.tools;
343
336
  const calls = new CallsInFlight();
344
- // The remote MCP servers' granted tools, as the CLI names them: its own MCP client calls them at the proxy.
345
- const mcpServers = spec.mcp?.servers ?? [];
346
- const mcpNames = new Set(mcpServers.flatMap((server) => server.tools.map((tool) => `mcp__${server.name}__${tool.name}`)));
347
337
  // The CLI's own tools offered to the model: Skill only when the session has skills, WebSearch only when it is on.
348
338
  const builtins = [...(skills.length ? ["Skill"] : []), ...(webSearch ? ["WebSearch"] : [])];
349
339
  const acquire = localMachine({
@@ -356,13 +346,14 @@ export function claudeAgentAdapter(options) {
356
346
  tools: tools.map((t) => t.name),
357
347
  ...(builtins.length ? { builtins } : {}),
358
348
  ...(webSearch ? { webSearch: true, ...(options.webSearchAllowance !== undefined ? { webSearchAllowance: options.webSearchAllowance } : {}) } : {}),
349
+ // What the CLI sends with its own tool search on, which the harness turns on as this does (claudeToolSearch).
350
+ ...(claudeToolSearch(tools.map((t) => t.name), spec.deferCatalog) === "true" ? { toolSearch: true } : {}),
359
351
  ...(options.price ? { price: options.price } : {}),
360
352
  ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
361
353
  ...(options.provider.auth ? { auth: options.provider.auth } : {}),
362
354
  ...(options.provider.headers ? { headers: options.provider.headers } : {}),
363
355
  ...(options.log ? { log: options.log } : {}),
364
356
  ...(options.fetch ? { fetch: options.fetch } : {}),
365
- ...(spec.mcp ? { mcp: { session: spec.mcp, tools: [...mcpNames] } } : {}),
366
357
  },
367
358
  });
368
359
  // The SDK this session runs on (the host's, or the one installed beside this package, checked above), thinking at
@@ -377,12 +368,12 @@ export function claudeAgentAdapter(options) {
377
368
  network: "deny-all",
378
369
  },
379
370
  tools: tools.map((tool) => kernelTool(tool, io, maxImageBytes, calls)),
371
+ ...(spec.deferCatalog === undefined ? {} : { deferCatalog: spec.deferCatalog }),
380
372
  builtins: false,
381
373
  // Off by name too, besides tools: []: the pinned CLI's tools that neither the harness's allowlist nor its off list
382
374
  // decide (test/tool-off.test.mjs pins the CLI's whole tool set against these lists), but WebSearch when it is on.
383
375
  disallowedTools: CLAUDE_AGENT_ALSO_OFF.filter((name) => !(webSearch && name === "WebSearch")),
384
376
  ...(webSearch ? { providerTools: ["web_search"] } : {}),
385
- ...(mcpServers.length ? { mcpServers: mcpServers.map((server) => ({ name: server.name, tools: server.tools.map((tool) => tool.name) })) } : {}),
386
377
  model: modelFor(spec),
387
378
  ...(skills.length ? { skills: { plugin: join(dir, "plugin"), names: writeSkillsPlugin(join(dir, "plugin"), skills) } } : {}),
388
379
  ...(options.smallModel ? { smallModel: options.smallModel } : {}),
@@ -404,11 +395,6 @@ export function claudeAgentAdapter(options) {
404
395
  // The model's message ended inside the turn (the CLI resumes a cut answer itself): what it said so far is one message.
405
396
  if (e?.type === "text_end")
406
397
  io.onEvent({ type: "text_end" });
407
- // An MCP call, recorded as a built-in's: the host hears of it once its intent is in the session's records.
408
- if (e?.type === "tool_start" && typeof e.callId === "string" && typeof e.name === "string" && mcpNames.has(e.name)) {
409
- calls.begin(e.callId);
410
- io.onEvent({ type: "tool_start", callId: e.callId, name: e.name, args: e.args ?? {} });
411
- }
412
398
  // The tool bridge's `tool_end` comes once the call's outcome is in the session's records: only then does the host
413
399
  // hear the call ended, with the text recorded.
414
400
  if (e?.type === "tool_end" && typeof e.callId === "string" && typeof e.name === "string") {
package/dist/facts.js CHANGED
@@ -12,13 +12,13 @@ export const facts = Object.freeze({
12
12
  steer: false,
13
13
  // A call that started is never run again (the CLI answers it "[Tool call interrupted]"); only the model calls again.
14
14
  rerunsStarted: false,
15
+ // Its own tool search defers an MCP server's tools (ENABLE_TOOL_SEARCH, on under the kernel's defersCatalog), so the host offers no tools_search or tools_call beside it.
16
+ ownToolSearch: true,
15
17
  // An answer its output limit cut, the CLI resumes itself in the same turn ("Output token limit hit. Resume directly"),
16
18
  // up to 3 times; only a cut it no longer resumes ends the turn cut.
17
19
  recoversCutAnswers: 3,
18
20
  // One run's memory, measured with the server's (serve's host.ts): the CLI and its SDK beside the run's process.
19
21
  runMib: 288,
20
- // Its own MCP client binds the session's remote MCP servers.
21
- mcp: true,
22
22
  thinking: Object.freeze(["low", "medium", "high", "xhigh", "max"]),
23
23
  // Anthropic's web search, through the session's proxy, as the pinned CLI's WebSearch asks for it.
24
24
  webSearch: "native",
package/dist/harness.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { GateAnswer, GateCall } from '@parcha/agentrun-kernel';
1
+ import { type GateAnswer, type GateCall } from '@parcha/agentrun-kernel';
2
2
  import { type DriveContext, type Harness, type HostTool, type ReplayPolicy, type SessionState, type Submission } from './host/kernel.js';
3
3
  import { type GatewayHandler, type ProviderTool, type SessionMachine } from './host/process.js';
4
4
  import { toolServer } from './host/tool-server.js';
@@ -142,6 +142,9 @@ export interface ClaudeCodeHarnessOptions {
142
142
  * none.
143
143
  */
144
144
  tools?: HostTool[];
145
+ /** The host's verdict on whether the catalog tools are deferred (SessionSpec.deferCatalog), which turns the CLI's own
146
+ * tool search on or off; absent, the tools' names decide (claudeToolSearch). */
147
+ deferCatalog?: boolean;
145
148
  /**
146
149
  * Claude Code's own tools, in the VM, on `/workspace`. Default false
147
150
  * (tool-less: `tools` are the CLI's only tools). `true`: the pinned
@@ -169,18 +172,6 @@ export interface ClaudeCodeHarnessOptions {
169
172
  * `claudeBuiltinReplay` (reads safe).
170
173
  */
171
174
  builtinReplay?: Record<string, ReplayPolicy> | ((name: string) => ReplayPolicy);
172
- /**
173
- * Remote MCP servers the CLI's own MCP client calls, each at the session's
174
- * model proxy (`<modelUrl>/mcp/<name>`, behind the session's key), with the
175
- * tools granted on each: those are allowed by name (`mcp__<name>__<tool>`)
176
- * and each call is recorded as a built-in's. They are set over the CLI's
177
- * stdin (`setMcpServers`), never in its argv. The proxy answers the
178
- * handshake: an unreachable server shows at its first call. Default none.
179
- */
180
- mcpServers?: readonly {
181
- readonly name: string;
182
- readonly tools: readonly string[];
183
- }[];
184
175
  /**
185
176
  * The MCP library the session's tool server is built with, as the host
186
177
  * loaded it from where it installed the Agent SDK. Default: imported by
@@ -258,8 +249,6 @@ export declare const DEFAULT_MODEL = "claude-sonnet-5-5";
258
249
  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.";
259
250
  /** `TOOLS_NOTE` with WebSearch on (`providerTools: ['web_search']`) and the other built-ins off. */
260
251
  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.";
261
- /** `TOOLS_NOTE` with the app's remote MCP servers (`mcpServers`) and the built-ins off. */
262
- 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.";
263
252
  /** `TOOLS_NOTE` for a session with no tools at all (built-ins off, no `tools`). */
264
253
  export declare const NO_TOOLS_NOTE = "You have no tools in this session: no shell, file, search or web tools. Answer from the conversation.";
265
254
  /** With the built-ins on (docs/workspaces.md §5.6 "Workspace note"): what `/workspace` is. */
@@ -283,6 +272,19 @@ export declare const CLAUDE_BUILTINS_OFF: string[];
283
272
  export declare const CLAUDE_BUILTINS: readonly ["Bash", "Read", "Edit", "Write", "NotebookEdit", "WebFetch"];
284
273
  /** Built-ins that only read: "safe to repeat" after a crash, and no flush before their outcome. Everything else: "may have taken effect". */
285
274
  export declare const CLAUDE_SAFE_BUILTINS: string[];
275
+ /**
276
+ * ENABLE_TOOL_SEARCH for a session whose tools are `toolNames` (the host's names): when the run's catalog tools are
277
+ * deferred (the kernel's defersCatalog: more than DEFER_CATALOG_OVER of them; the host's own tools_search and tools_call
278
+ * are never offered beside it), `true`: the CLI's own tool search is on, its ToolSearch among its tools, and those tools are
279
+ * deferred (served through `hands`, the rest of the session's tools listed to load always: tool-server.ts listedTools),
280
+ * each sent to the model once ToolSearch finds it. Without, `false`. The pinned CLI (2.1.286) leaves it off behind a
281
+ * proxy unless told, and its `auto` defers only past a tenth of the model's context (on a 1M-token model, never in
282
+ * practice); set either way, so a CLI that changes that default changes nothing here. The session's proxy admits what the
283
+ * CLI sends with it on (anthropicPolicy `toolSearch`).
284
+ */
285
+ export declare const claudeToolSearch: (toolNames: readonly string[], deferCatalog?: boolean) => "true" | "false";
286
+ /** The CLI's own tool that finds a deferred tool: it only reads the CLI's list of the session's tools. */
287
+ export declare const CLAUDE_TOOL_SEARCH = "ToolSearch";
286
288
  /** The default `builtinReplay`. */
287
289
  export declare const claudeBuiltinReplay: (name: string) => ReplayPolicy;
288
290
  /** The `builtins` option, resolved: the `tools` option for `query()` (undefined: the preset, all of them). */
package/dist/harness.js CHANGED
@@ -6,6 +6,7 @@ import { randomUUID } from 'node:crypto';
6
6
  import { mkdtemp, rm } from 'node:fs/promises';
7
7
  import { tmpdir } from 'node:os';
8
8
  import { dirname, join, posix } from 'node:path';
9
+ import { defersCatalog } from '@parcha/agentrun-kernel';
9
10
  import { Restart, Unavailable } from './host/kernel.js';
10
11
  import { askGate, BuiltinCalls, CLAUDE_ROUTES, gatewayCredential, gatewayHandler, gatewayUrl, isBrandedMachine, NativeJournal, openTurn, placeSubmissions, recoveryNote, restartEvent, replayBy, toolBridge, toolKey, waitForSubmissions, } from './host/process.js';
11
12
  import { durableEnv, nativeModelId } from './env.js';
@@ -39,8 +40,6 @@ export const DEFAULT_MODEL = 'claude-sonnet-5-5';
39
40
  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.`;
40
41
  /** `TOOLS_NOTE` with WebSearch on (`providerTools: ['web_search']`) and the other built-ins off. */
41
42
  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.`;
42
- /** `TOOLS_NOTE` with the app's remote MCP servers (`mcpServers`) and the built-ins off. */
43
- 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.`;
44
43
  /** `TOOLS_NOTE` for a session with no tools at all (built-ins off, no `tools`). */
45
44
  export const NO_TOOLS_NOTE = 'You have no tools in this session: no shell, file, search or web tools. Answer from the conversation.';
46
45
  /** With the built-ins on (docs/workspaces.md §5.6 "Workspace note"): what `/workspace` is. */
@@ -90,6 +89,19 @@ export const CLAUDE_BUILTINS_OFF = [
90
89
  export const CLAUDE_BUILTINS = ['Bash', 'Read', 'Edit', 'Write', 'NotebookEdit', 'WebFetch'];
91
90
  /** Built-ins that only read: "safe to repeat" after a crash, and no flush before their outcome. Everything else: "may have taken effect". */
92
91
  export const CLAUDE_SAFE_BUILTINS = ['Read', 'Glob', 'Grep', 'LS', 'NotebookRead', 'WebFetch', 'WebSearch', 'ToolSearch', 'Skill'];
92
+ /**
93
+ * ENABLE_TOOL_SEARCH for a session whose tools are `toolNames` (the host's names): when the run's catalog tools are
94
+ * deferred (the kernel's defersCatalog: more than DEFER_CATALOG_OVER of them; the host's own tools_search and tools_call
95
+ * are never offered beside it), `true`: the CLI's own tool search is on, its ToolSearch among its tools, and those tools are
96
+ * deferred (served through `hands`, the rest of the session's tools listed to load always: tool-server.ts listedTools),
97
+ * each sent to the model once ToolSearch finds it. Without, `false`. The pinned CLI (2.1.286) leaves it off behind a
98
+ * proxy unless told, and its `auto` defers only past a tenth of the model's context (on a 1M-token model, never in
99
+ * practice); set either way, so a CLI that changes that default changes nothing here. The session's proxy admits what the
100
+ * CLI sends with it on (anthropicPolicy `toolSearch`).
101
+ */
102
+ export const claudeToolSearch = (toolNames, deferCatalog) => ((deferCatalog ?? defersCatalog(toolNames)) ? 'true' : 'false');
103
+ /** The CLI's own tool that finds a deferred tool: it only reads the CLI's list of the session's tools. */
104
+ export const CLAUDE_TOOL_SEARCH = 'ToolSearch';
93
105
  /** The default `builtinReplay`. */
94
106
  export const claudeBuiltinReplay = replayBy(CLAUDE_SAFE_BUILTINS);
95
107
  /** What a Bash command keeps of the invocation for its outcome to be recorded and the drive to end (the kernel's end-of-drive margin is 15 s). */
@@ -159,23 +171,6 @@ async function bwrapWorks(machine, signal) {
159
171
  return false;
160
172
  }
161
173
  }
162
- /**
163
- * The session's remote MCP servers, each an http entry at the model proxy's
164
- * `/mcp/<name>` with the session's key, sent over the CLI's stdin (an entry
165
- * in `options.mcpServers` would be in its argv). The in-process server
166
- * (`own`) goes with them, since the call replaces the dynamic set. A server
167
- * that did not connect throws: the turn fails rather than run without its
168
- * tools. Each call may take `timeoutMs`, what is left of the invocation.
169
- */
170
- async function connectMcp(q, machine, names, own, timeoutMs) {
171
- const entry = (name) => ({ type: 'http', url: `${machine.modelUrl}/mcp/${name}`, headers: { authorization: `Bearer ${machine.modelKey}` }, timeout: Math.floor(timeoutMs), alwaysLoad: true });
172
- const set = await q.setMcpServers({ ...own, ...Object.fromEntries(names.map((name) => [name, entry(name)])) });
173
- const status = new Map((await q.mcpServerStatus()).map((server) => [server.name, server]));
174
- const error = (name) => (set.errors && Object.hasOwn(set.errors, name) ? set.errors[name] : undefined);
175
- const failed = names.filter((name) => error(name) !== undefined || status.get(name)?.status !== 'connected');
176
- if (failed.length)
177
- 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)}`);
178
- }
179
174
  export function claudeCodeHarness(options = {}) {
180
175
  const tools = options.tools ?? [];
181
176
  const allowed = builtinTools(options.builtins);
@@ -188,8 +183,8 @@ export function claudeCodeHarness(options = {}) {
188
183
  const replay = typeof options.builtinReplay === 'function' ? options.builtinReplay : options.builtinReplay ? (name) => options.builtinReplay[name] ?? claudeBuiltinReplay(name) : claudeBuiltinReplay;
189
184
  const providerTools = options.providerTools ?? [];
190
185
  const webSearch = providerTools.includes('web_search');
191
- const mcpServers = options.mcpServers ?? [];
192
- const mcpNames = new Set(mcpServers.flatMap((server) => server.tools.map((tool) => `mcp__${server.name}__${tool}`)));
186
+ /** The CLI's own tool search is on: a run's MCP servers' tools deferred behind its ToolSearch (claudeToolSearch). */
187
+ const toolSearch = claudeToolSearch(tools.map((tool) => tool.name), options.deferCatalog) === 'true';
193
188
  const log = options.log ?? (() => { });
194
189
  let sdk;
195
190
  const loadSdk = () => {
@@ -295,14 +290,17 @@ export function claudeCodeHarness(options = {}) {
295
290
  // The host's gate before the intent, so a refused or parked call leaves nothing of its own written. The assistant
296
291
  // line that made the call is in the log before the gate is asked: a park ends the claim, and the resume finds the
297
292
  // call it held dangling in the transcript, under the same id (resumeDanglingCalls, resumeDanglingSearches).
298
- const gated = gate ? async (call) => (await store.barrier(call.callId, barrierMs), gate(call)) : undefined;
293
+ // A call a tool makes inside its own (tools_call, codemode) has the id `<tool_use id>/<key>`: no line of the
294
+ // transcript names it, so it waits on the line that made the call it runs inside.
295
+ const logged = (callId) => store.barrier(callId.split('/')[0], barrierMs);
296
+ const gated = gate ? async (call) => (await logged(call.callId), gate(call)) : undefined;
299
297
  /** The WebSearch calls the gate held and a person let run that no search has taken up yet (releasedSearches, read
300
298
  * from the transcript at the resume): the model's next search with one's input is put to the gate under its id. */
301
299
  const released = [];
302
300
  const bridge = toolBridge(ctx, tools, {
303
301
  ...(gated ? { gate: gated } : {}),
304
302
  // A `never` tool runs only once the assistant entry that asked for it is in the log.
305
- beforeNever: ({ callId }) => store.barrier(callId, barrierMs),
303
+ beforeNever: ({ callId }) => logged(callId),
306
304
  });
307
305
  // The built-ins: each call an intent before it runs, its outcome after (the hooks below).
308
306
  const builtins = new BuiltinCalls(ctx, { replay, beforeNever: ({ callId }) => store.barrier(callId, barrierMs), live: true });
@@ -381,9 +379,9 @@ export function claudeCodeHarness(options = {}) {
381
379
  return deny(`Not run: ${JSON.stringify(String(asked).slice(0, 80))} is not one of this session's skills.`);
382
380
  return name === asked ? allow() : allow({ ...input, skill: name });
383
381
  }
384
- // WebSearch, when on, takes the built-ins' path below: its intent recorded before it runs.
385
- // WebSearch and a granted MCP tool too.
386
- if (!builtinsOn && !(webSearch && hook.tool_name === 'WebSearch') && !mcpNames.has(hook.tool_name))
382
+ // WebSearch, when on, takes the built-ins' path below: its intent recorded before it runs. So does
383
+ // ToolSearch with the tool search on: it reads only the CLI's list of the session's own tools.
384
+ if (!builtinsOn && !(webSearch && hook.tool_name === 'WebSearch') && !(toolSearch && hook.tool_name === CLAUDE_TOOL_SEARCH))
387
385
  return deny("Not run: this session's only tools are its own.");
388
386
  if (ctx.signal.aborted)
389
387
  return deny('the session stopped');
@@ -493,9 +491,8 @@ export function claudeCodeHarness(options = {}) {
493
491
  // A host tool's result within the host's bound reaches the model whole (each tool is listed with it, too).
494
492
  mcpOutputTokens: MCP_OUTPUT_TOKENS,
495
493
  });
496
- // MCP tools are offered whole, never deferred behind the CLI's tool search, which the session's proxy does not carry.
497
- if (mcpServers.length)
498
- vmEnv.ENABLE_TOOL_SEARCH = 'false';
494
+ // The CLI's own tool search: on with MCP servers among the session's tools, off without (claudeToolSearch).
495
+ vmEnv.ENABLE_TOOL_SEARCH = toolSearch ? 'true' : 'false';
499
496
  const sdkEnv = { ...vmEnv, CLAUDE_CONFIG_DIR: configDir };
500
497
  const disallowed = [...CLAUDE_BUILTINS_OFF, ...(providerTools.includes('web_search') ? [] : ['WebSearch']), ...(options.disallowedTools ?? [])].filter((name) => !(skills && name === 'Skill'));
501
498
  const sessionId = uuidFrom(ctx.runId);
@@ -530,14 +527,14 @@ export function claudeCodeHarness(options = {}) {
530
527
  // Built-ins on: the allowed ones (less those whose state the log does not carry), each let through by
531
528
  // the PreToolUse hook once its intent is in the log. Off: the bridged tools are the only ones. Either
532
529
  // way nothing is asked of a user, and nothing else is permitted.
533
- ...(allowed !== undefined ? { tools: [...allowed, ...(skills ? ['Skill'] : []), ...(webSearch && !allowed.includes('WebSearch') ? ['WebSearch'] : [])] } : {}),
530
+ ...(allowed !== undefined ? { tools: [...allowed, ...(skills ? ['Skill'] : []), ...(webSearch && !allowed.includes('WebSearch') ? ['WebSearch'] : []), ...(toolSearch && !allowed.includes(CLAUDE_TOOL_SEARCH) ? [CLAUDE_TOOL_SEARCH] : [])] } : {}),
534
531
  // The session's skills, from its own plugin: listed to the model and loadable, and no other.
535
532
  ...(skills ? { plugins: [{ type: 'local', path: skills.plugin }], skills: [...skills.names] } : {}),
536
533
  disallowedTools: disallowed,
537
534
  hooks,
538
535
  ...(ownSandbox ? { sandbox: claudeSandboxSettings(machine, sandbox.network) } : {}),
539
536
  ...(bridge.tools.length ? { mcpServers: { [MCP_SERVER]: server } } : {}),
540
- allowedTools: [...bridge.tools.map((t) => `mcp__${MCP_SERVER}__${t.name}`), ...mcpNames],
537
+ allowedTools: bridge.tools.map((t) => `mcp__${MCP_SERVER}__${t.name}`),
541
538
  permissionMode: 'dontAsk',
542
539
  strictMcpConfig: true,
543
540
  // No user, project or local settings (and so no CLAUDE.md): a model-planted .claude/ on the Drive is ignored.
@@ -549,7 +546,7 @@ export function claudeCodeHarness(options = {}) {
549
546
  systemPrompt: {
550
547
  type: 'preset',
551
548
  preset: 'claude_code',
552
- 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'),
549
+ append: [builtinsOn ? DRIVE_NOTE : webSearch ? WEB_SEARCH_NOTE : bridge.tools.length ? TOOLS_NOTE : NO_TOOLS_NOTE, options.instructions, recovered].filter(Boolean).join('\n\n'),
553
550
  snapshot: !recovered,
554
551
  },
555
552
  ...(store.hasSession ? { resume: sessionId } : { sessionId }),
@@ -571,8 +568,6 @@ export function claudeCodeHarness(options = {}) {
571
568
  };
572
569
  const q = query({ prompt: input, options: queryOptions });
573
570
  const messages = q[Symbol.asyncIterator]();
574
- if (mcpServers.length)
575
- await connectMcp(q, machine, mcpServers.map((server) => server.name), bridge.tools.length ? { [MCP_SERVER]: server } : {}, Math.max(1_000, deadline - Date.now()));
576
571
  const send = async (text, placed, how = {}) => {
577
572
  // The drive's first message says, once, what the sandbox told it (a lost Drive).
578
573
  if (notes) {
@@ -1,10 +1,7 @@
1
1
  import { type ChildProcess } from "node:child_process";
2
2
  import { type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
3
- import type { McpClient, SessionMcp } from "@parcha/agentrun-kernel";
4
3
  import type { AcquireMachine, MachineSpawn, SessionMachine, SessionProcess } from "./process.js";
5
4
  import { type AnthropicPolicyOptions } from "./policy.js";
6
- /** Claude Code's own MCP client: it sends a call's tool use id in tools/call's `_meta["claudecode/toolUseId"]`. */
7
- export declare const CLAUDE_MCP_CLIENT: McpClient;
8
5
  /** The variables a child takes from this process, when they are set. */
9
6
  export declare const INHERITED_ENV: readonly ["PATH", "LANG", "TZ"];
10
7
  /** A command and its arguments, as the machine starts it. */
@@ -35,14 +32,10 @@ export interface LocalMachineOptions {
35
32
  builtins?: readonly string[];
36
33
  /** Admit Anthropic's web search server tool, the one the CLI's WebSearch asks for. */
37
34
  webSearch?: boolean;
38
- /** The session's remote MCP servers, which the kernel's proxy serves at `/mcp/<server>` for the CLI's own MCP client
39
- * (CLAUDE_MCP_CLIENT), and their granted tools as the CLI names them. */
40
- mcp?: {
41
- session: SessionMcp;
42
- tools: readonly string[];
43
- };
44
35
  /** The input a request carrying it may read in beyond its body, for its input bound (anthropicPolicy). */
45
36
  webSearchAllowance?: number;
37
+ /** The CLI's own tool search is on: its beta, its tools and its tool references pass (anthropicPolicy). */
38
+ toolSearch?: boolean;
46
39
  /** The tokens' price; each web search a response reports is added to it (`withWebSearches`). */
47
40
  price?: ModelProxyOptions["price"];
48
41
  maxOutputTokens?: number;
@@ -17,8 +17,6 @@ import { dirname, isAbsolute, join, normalize, sep } from "node:path";
17
17
  import { parentWatched, startModelProxy } from "@parcha/agentrun-kernel/host";
18
18
  import { brandMachine } from "./process.js";
19
19
  import { anthropicPolicy, withWebSearches } from "./policy.js";
20
- /** Claude Code's own MCP client: it sends a call's tool use id in tools/call's `_meta["claudecode/toolUseId"]`. */
21
- export const CLAUDE_MCP_CLIENT = { callIdMeta: "claudecode/toolUseId" };
22
20
  /** The variables a child takes from this process, when they are set. */
23
21
  export const INHERITED_ENV = Object.freeze(["PATH", "LANG", "TZ"]);
24
22
  const DIRS = ["home", "config", "tmp", "cache"];
@@ -132,10 +130,10 @@ export function localMachine(options) {
132
130
  ...(route.models.smallModel ? { smallModel: route.models.smallModel } : {}),
133
131
  tools: options.proxy.tools,
134
132
  ...(options.proxy.builtins?.length ? { builtins: options.proxy.builtins } : {}),
135
- ...(options.proxy.mcp ? { mcpTools: options.proxy.mcp.tools } : {}),
136
133
  ...(options.proxy.maxOutputTokens ? { maxOutputTokens: options.proxy.maxOutputTokens } : {}),
137
134
  ...(options.proxy.webSearch ? { webSearch: true, ...(options.proxy.webSearchAllowance !== undefined ? { webSearchAllowance: options.proxy.webSearchAllowance } : {}) } : {}),
138
135
  ...(options.proxy.auth ? { auth: options.proxy.auth } : {}),
136
+ ...(options.proxy.toolSearch ? { toolSearch: true } : {}),
139
137
  onThinkingDisabled: ({ model: main }) => options.proxy.log?.("claude-agent: thinking.disabled", { model: main }),
140
138
  }),
141
139
  hooks: options.proxy.hooks,
@@ -144,7 +142,6 @@ export function localMachine(options) {
144
142
  credential: async () => (await route.credential()) ?? "",
145
143
  ...(options.proxy.price ? { price: withWebSearches(options.proxy.price) } : {}),
146
144
  ...(options.proxy.headers ? { headers: options.proxy.headers } : {}),
147
- ...(options.proxy.mcp ? { mcp: { session: options.proxy.mcp.session, client: CLAUDE_MCP_CLIENT } } : {}),
148
145
  ...(options.proxy.log ? { log: options.proxy.log } : {}),
149
146
  // The provider stopped the turn's answer on its content filter: no retry of it can pass, so the turn ends at once.
150
147
  onFiltered: (message) => ctx.halt?.(new Error(message)),
@@ -6,6 +6,12 @@ export declare const CLAUDE_MESSAGES_ROUTES: readonly ProxyRoute[];
6
6
  * and a probe of claude-sonnet-4-5, claude-sonnet-5-5, claude-opus-5-5 and claude-haiku-5-5): the set depends on the
7
7
  * model. Any other is refused, so a CLI or a model that starts sending a new one is seen before it is trusted. */
8
8
  export declare const CLAUDE_BETAS: ReadonlySet<string>;
9
+ /** The beta the pinned CLI (2.1.286) adds with its own tool search on (ENABLE_TOOL_SEARCH, `toolSearch`): its tools sent
10
+ * with `defer_loading`, and its ToolSearch's answer as `tool_reference` blocks naming them. Admitted only then. */
11
+ export declare const CLAUDE_TOOL_SEARCH_BETA = "advanced-tool-use-2025-11-20";
12
+ /** The CLI's own tools its tool search adds (recorded behind a local server, CLI 2.1.286): ToolSearch, which runs in the
13
+ * CLI and answers with the deferred tools it found, and a deferred placeholder it never calls. */
14
+ export declare const CLAUDE_TOOL_SEARCH_TOOLS: readonly string[];
9
15
  /** The content blocks the pinned CLI (2.1.286) sends in a session, recorded behind this proxy (the real-CLI test, with
10
16
  * a model that thinks): any other type is refused, so a block the provider runs or resolves on its own (a server
11
17
  * tool's call or result, an MCP block, a container upload, an image or document it would fetch) never passes, under
@@ -17,9 +23,6 @@ export declare const CLAUDE_BLOCKS: ReadonlySet<string>;
17
23
  * test/fixtures/web-search-request-cli-2.1.286.json): its type and name, `max_uses: 8`, and the domains the model named.
18
24
  * A later version (dynamic filtering runs code execution) or any other field is refused. */
19
25
  export declare const CLAUDE_WEB_SEARCH_TOOL = "web_search_20250305";
20
- /** What one web search costs on Anthropic's API, in USD, beside the tokens: $10 per 1,000 searches, "Web search tool" in
21
- * https://platform.claude.com/docs/en/about-claude/pricing (a search that errs is not billed). */
22
- export declare const CLAUDE_WEB_SEARCH_USD = 0.01;
23
26
  export interface AnthropicPolicyOptions {
24
27
  /** The session's model, and the one the CLI's small background calls use (default: the session's). */
25
28
  model: string;
@@ -28,8 +31,6 @@ export interface AnthropicPolicyOptions {
28
31
  tools: readonly string[];
29
32
  /** The CLI's own tools the session has, offered by their own names beside its tools (`Skill`, when it has skills). */
30
33
  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[];
33
34
  /** The most output tokens one request may ask for. Default 128 000, what the pinned CLI asks for on current models. */
34
35
  maxOutputTokens?: number;
35
36
  /** Admit Anthropic's web search server tool (`CLAUDE_WEB_SEARCH_TOOL`), exactly as the pinned CLI asks for it; every
@@ -40,6 +41,10 @@ export interface AnthropicPolicyOptions {
40
41
  * pages each search feeds the model, billed as input), added to that request's input bound. Absent, such a request
41
42
  * has no input bound, so a cap that holds each request's worst case refuses it. */
42
43
  webSearchAllowance?: number;
44
+ /** The CLI's own tool search is on (its MCP tools deferred until it finds them): its beta, its two tools
45
+ * (CLAUDE_TOOL_SEARCH_TOOLS) and, inside a tool result, a `tool_reference` block naming one of the session's own tools
46
+ * pass. A reference names a tool the request offers; the provider resolves it to nothing else. Default off. */
47
+ toolSearch?: boolean;
43
48
  /** How the provider takes its credential. Default `x-api-key` (Anthropic's API). */
44
49
  auth?: "x-api-key" | "bearer";
45
50
  /** Told when a request on the session's main model carries no thinking and no effort: the model would answer without
@@ -82,7 +87,7 @@ export declare function applyAnthropic(body: unknown, route: ProxyRoute, options
82
87
  export interface AnthropicUsage extends ProxyUsage {
83
88
  webSearches?: number;
84
89
  }
85
- /** `price` with each web search a response reports added at `CLAUDE_WEB_SEARCH_USD`: the host prices the tokens, the
90
+ /** `price` with each web search a response reports added at `NATIVE_SEARCH_USD`: the host prices the tokens, the
86
91
  * searches are Anthropic's flat rate. An unknown price stays unknown. */
87
92
  export declare function withWebSearches(price: (model: string, usage: ProxyUsage) => number | null): (model: string, usage: ProxyUsage) => number | null;
88
93
  /** The usage a Messages response reports, read by parsing it, never by matching its text (the API nests objects in
@@ -96,9 +101,9 @@ export declare function anthropicUsage(text: string): AnthropicUsage | undefined
96
101
  * on its own, as anthropicUsage reads them. */
97
102
  export declare function anthropicFiltered(text: string): boolean;
98
103
  /** Whether a Messages body (as `apply` kept it) is the turn's answer request: it offers the model one of the session's
99
- * tools, its own, built-in or remote (a remote MCP server's). The CLI's side calls (a title, a summary, a web search's
104
+ * tools, its own (a run's remote MCP tools among them) or built-in. The CLI's side calls (a title, a summary, a web search's
100
105
  * own request) offer none of them; in a session with no tools no request can be told from one, so each is the turn's. */
101
- export declare function anthropicAnswers(body: Record<string, unknown>, options: Pick<AnthropicPolicyOptions, "tools" | "builtins" | "mcpTools">): boolean;
106
+ export declare function anthropicAnswers(body: Record<string, unknown>, options: Pick<AnthropicPolicyOptions, "tools" | "builtins">): boolean;
102
107
  /**
103
108
  * Anthropic's own count of a Messages request's input tokens: POST /v1/messages/count_tokens, free, on api.anthropic.com
104
109
  * only ("Token counting", https://platform.claude.com/docs/en/build-with-claude/token-counting). The proxy asks it before
@@ -18,7 +18,7 @@
18
18
  // is dropped, so the model is offered exactly the host's tools. With `webSearch`, one hosted tool passes: Anthropic's web
19
19
  // search, exactly as the pinned CLI asks for it in the request its WebSearch tool makes. Usage is read from the stream's
20
20
  // `message_start` (input and cache tokens) and its last `message_delta` (output, and the searches the provider ran).
21
- import { messagesImagesIn, providerInputOverhead, ProxyRefusal } from "@parcha/agentrun-kernel/host";
21
+ import { messagesImagesIn, providerInputOverhead, NATIVE_SEARCH_USD, ProxyRefusal } from "@parcha/agentrun-kernel/host";
22
22
  /** The prefix of the session's own tools, as the CLI names them (its in-process MCP server, `hands`). */
23
23
  export const OWN_TOOL_PREFIX = "mcp__hands__";
24
24
  const ANTHROPIC_HEADERS = ["anthropic-version", "anthropic-beta"];
@@ -41,6 +41,14 @@ export const CLAUDE_BETAS = new Set([
41
41
  "prompt-caching-scope-2026-01-05",
42
42
  "thinking-token-count-2026-05-13",
43
43
  ]);
44
+ /** The beta the pinned CLI (2.1.286) adds with its own tool search on (ENABLE_TOOL_SEARCH, `toolSearch`): its tools sent
45
+ * with `defer_loading`, and its ToolSearch's answer as `tool_reference` blocks naming them. Admitted only then. */
46
+ export const CLAUDE_TOOL_SEARCH_BETA = "advanced-tool-use-2025-11-20";
47
+ /** The CLI's own tools its tool search adds (recorded behind a local server, CLI 2.1.286): ToolSearch, which runs in the
48
+ * CLI and answers with the deferred tools it found, and a deferred placeholder it never calls. */
49
+ export const CLAUDE_TOOL_SEARCH_TOOLS = Object.freeze(["ToolSearch", "DeferredToolPlaceholder"]);
50
+ /** The keys of a `tool_reference` block, as the CLI's ToolSearch answers. */
51
+ const TOOL_REFERENCE_KEYS = new Set(["type", "tool_name"]);
44
52
  /** The keys a Messages request may carry, and a token count's. */
45
53
  const MESSAGES_KEYS = new Set(["model", "messages", "system", "max_tokens", "metadata", "stop_sequences", "stream", "temperature", "top_k", "top_p", "tools", "tool_choice", "thinking", "context_management", "output_config"]);
46
54
  const COUNT_TOKENS_KEYS = new Set(["model", "messages", "system", "tools", "tool_choice", "thinking", "context_management", "output_config"]);
@@ -59,9 +67,6 @@ export const CLAUDE_WEB_SEARCH_TOOL = "web_search_20250305";
59
67
  const WEB_SEARCH_KEYS = new Set(["type", "name", "max_uses", "allowed_domains", "blocked_domains"]);
60
68
  /** The most searches one request may ask the provider for: the pinned CLI's `max_uses`. */
61
69
  const WEB_SEARCH_MAX_USES = 8;
62
- /** What one web search costs on Anthropic's API, in USD, beside the tokens: $10 per 1,000 searches, "Web search tool" in
63
- * https://platform.claude.com/docs/en/about-claude/pricing (a search that errs is not billed). */
64
- export const CLAUDE_WEB_SEARCH_USD = 0.01;
65
70
  /** Whether a Messages body asks the model to think: thinking on (adaptive, or a budget), or an effort level. */
66
71
  export function thinks(body) {
67
72
  const thinking = body.thinking;
@@ -84,7 +89,7 @@ const LOCAL_IMAGE_NOTE = /^\[Image: source: [^\]\n]+\]$/;
84
89
  /** A content list (a message's, the system prompt's, a tool result's): only the block types this session sends. An
85
90
  * image only as a host tool answered it: inside its result, inline, of a type the API takes (never one the provider
86
91
  * would fetch). */
87
- function blocks(content, where, inResult = false) {
92
+ function blocks(content, where, inResult = false, references) {
88
93
  if (content === undefined || typeof content === "string")
89
94
  return;
90
95
  if (!Array.isArray(content))
@@ -92,6 +97,12 @@ function blocks(content, where, inResult = false) {
92
97
  for (const block of content) {
93
98
  if (!isPlain(block) || typeof block.type !== "string")
94
99
  return refuse(400, `a block in ${where} must be an object with a type`);
100
+ // With the CLI's tool search on: its ToolSearch's answer, a reference to one of the session's own tools, nothing else.
101
+ if (inResult && references && block.type === "tool_reference") {
102
+ if (!Object.keys(block).every((key) => TOOL_REFERENCE_KEYS.has(key)) || typeof block.tool_name !== "string" || !references.has(block.tool_name))
103
+ refuse(403, `${where} holds a tool reference to a tool this session does not have`);
104
+ continue;
105
+ }
95
106
  if (inResult && block.type === "image") {
96
107
  const source = block.source;
97
108
  if (!isPlain(source) || source.type !== "base64" || typeof source.media_type !== "string" || !IMAGE_TYPES.has(source.media_type) || typeof source.data !== "string")
@@ -101,7 +112,7 @@ function blocks(content, where, inResult = false) {
101
112
  if (!CLAUDE_BLOCKS.has(block.type))
102
113
  refuse(403, `${where} holds a block of a type this session does not send`);
103
114
  if (block.type === "tool_result")
104
- blocks(block.content, "a tool result's content", true);
115
+ blocks(block.content, "a tool result's content", true, references);
105
116
  }
106
117
  }
107
118
  /** A message with the CLI's note of its own image file left out of each tool result that holds the image itself: the
@@ -251,15 +262,19 @@ export function applyAnthropic(body, route, options, context = {}) {
251
262
  const count = route.path === "/v1/messages/count_tokens";
252
263
  onlyKeys(body, count ? COUNT_TOKENS_KEYS : MESSAGES_KEYS, count ? "count_tokens" : "messages");
253
264
  outputConfig(body.output_config);
265
+ const own = options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`);
266
+ const search = options.toolSearch === true && context.host === undefined;
267
+ // The tools a tool search's answer may name: the session's own (a reference names no built-in).
268
+ const references = search ? new Set(own) : undefined;
254
269
  if (!Array.isArray(body.messages))
255
270
  refuse(400, "messages must be a list");
256
271
  for (const message of body.messages) {
257
272
  if (!isPlain(message))
258
273
  refuse(400, "a message must be an object");
259
- blocks(message.content, "a message's content");
274
+ blocks(message.content, "a message's content", false, references);
260
275
  }
261
276
  blocks(body.system, "system");
262
- const allowed = context.host !== undefined ? new Set(clientToolNames(body.tools)) : new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? []), ...(options.mcpTools ?? [])]);
277
+ const allowed = context.host !== undefined ? new Set(clientToolNames(body.tools)) : new Set([...own, ...(options.builtins ?? []), ...(search ? CLAUDE_TOOL_SEARCH_TOOLS : [])]);
263
278
  const tools = ownTools(body.tools, allowed, options.webSearch);
264
279
  const choice = body.tool_choice;
265
280
  const chosen = isPlain(choice) && typeof choice.name === "string" && (allowed.has(choice.name) || (options.webSearch === true && choice.name === "web_search"));
@@ -301,13 +316,13 @@ function bookedUsage(usage) {
301
316
  return undefined;
302
317
  return { input, output, cacheRead: tokenCount(usage.cache_read_input_tokens) ?? 0, cacheWrite: tokenCount(usage.cache_creation_input_tokens) ?? 0, ...(webSearches ? { webSearches } : {}) };
303
318
  }
304
- /** `price` with each web search a response reports added at `CLAUDE_WEB_SEARCH_USD`: the host prices the tokens, the
319
+ /** `price` with each web search a response reports added at `NATIVE_SEARCH_USD`: the host prices the tokens, the
305
320
  * searches are Anthropic's flat rate. An unknown price stays unknown. */
306
321
  export function withWebSearches(price) {
307
322
  return (model, usage) => {
308
323
  const usd = price(model, usage);
309
324
  const count = usage.webSearches ?? 0;
310
- return usd === null || count === 0 ? usd : usd + count * CLAUDE_WEB_SEARCH_USD;
325
+ return usd === null || count === 0 ? usd : usd + count * NATIVE_SEARCH_USD;
311
326
  };
312
327
  }
313
328
  /** The usage a Messages response reports, read by parsing it, never by matching its text (the API nests objects in
@@ -374,10 +389,10 @@ export function anthropicFiltered(text) {
374
389
  return stop === "refusal";
375
390
  }
376
391
  /** Whether a Messages body (as `apply` kept it) is the turn's answer request: it offers the model one of the session's
377
- * tools, its own, built-in or remote (a remote MCP server's). The CLI's side calls (a title, a summary, a web search's
392
+ * tools, its own (a run's remote MCP tools among them) or built-in. The CLI's side calls (a title, a summary, a web search's
378
393
  * own request) offer none of them; in a session with no tools no request can be told from one, so each is the turn's. */
379
394
  export function anthropicAnswers(body, options) {
380
- const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? []), ...(options.mcpTools ?? [])]);
395
+ const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? [])]);
381
396
  if (allowed.size === 0)
382
397
  return true;
383
398
  return Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && typeof tool.name === "string" && allowed.has(tool.name));
@@ -459,7 +474,7 @@ export function anthropicPolicy(options) {
459
474
  header: (name, value) => {
460
475
  if (name !== "anthropic-beta")
461
476
  return value;
462
- const unknown = value.split(",").map((v) => v.trim()).filter((v) => v && !CLAUDE_BETAS.has(v));
477
+ const unknown = value.split(",").map((v) => v.trim()).filter((v) => v && !CLAUDE_BETAS.has(v) && !(options.toolSearch === true && v === CLAUDE_TOOL_SEARCH_BETA));
463
478
  if (unknown.length)
464
479
  refuse(403, "an anthropic-beta value is not one the pinned CLI sends");
465
480
  return value;
@@ -26,13 +26,17 @@ export declare const RESULT_SIZE_KEY = "anthropic/maxResultSizeChars";
26
26
  * images) is never counted, let alone saved or cut.
27
27
  */
28
28
  export declare const MCP_OUTPUT_TOKENS = 120000;
29
+ /** The `_meta` key of a listed tool by which the CLI never defers it behind its tool search. */
30
+ export declare const ALWAYS_LOAD_KEY = "anthropic/alwaysLoad";
29
31
  /** `tools` as the server lists them to the CLI (`tools/list`): each as the host gave it, with the host's result bound as
30
- * its result size. */
32
+ * its result size. With the CLI's tool search on (harness.ts claudeToolSearch), only a run's MCP servers' tools
33
+ * (`mcp__<server>__<tool>`) wait behind it: every other tool of the session is listed to load always. */
31
34
  export declare const listedTools: (tools: readonly ServedTool[]) => {
32
35
  name: string;
33
36
  description: string;
34
37
  inputSchema: Record<string, unknown>;
35
38
  _meta: {
39
+ "anthropic/alwaysLoad"?: boolean | undefined;
36
40
  "anthropic/maxResultSizeChars": number;
37
41
  };
38
42
  }[];
@@ -24,9 +24,12 @@ export const RESULT_SIZE_KEY = "anthropic/maxResultSizeChars";
24
24
  * images) is never counted, let alone saved or cut.
25
25
  */
26
26
  export const MCP_OUTPUT_TOKENS = HOST_RESULT_MAX_CHARS;
27
+ /** The `_meta` key of a listed tool by which the CLI never defers it behind its tool search. */
28
+ export const ALWAYS_LOAD_KEY = "anthropic/alwaysLoad";
27
29
  /** `tools` as the server lists them to the CLI (`tools/list`): each as the host gave it, with the host's result bound as
28
- * its result size. */
29
- export const listedTools = (tools) => tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema, _meta: { [RESULT_SIZE_KEY]: HOST_RESULT_MAX_CHARS } }));
30
+ * its result size. With the CLI's tool search on (harness.ts claudeToolSearch), only a run's MCP servers' tools
31
+ * (`mcp__<server>__<tool>`) wait behind it: every other tool of the session is listed to load always. */
32
+ export const listedTools = (tools) => tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema, _meta: { [RESULT_SIZE_KEY]: HOST_RESULT_MAX_CHARS, ...(t.name.startsWith("mcp__") ? {} : { [ALWAYS_LOAD_KEY]: true }) } }));
30
33
  /** The SDK's in-process server config for `tools`: `call(name, args, toolUseId)` answers each call. Built with `modules`,
31
34
  * else with the MCP library imported by name, beside this package. */
32
35
  export async function toolServer(name, tools, call, modules) {
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export type { ClaudeAgentPin } from "./errors.js";
4
4
  export type { ClaudeAgentAdapterOptions, ClaudeAgentProvider, ClaudeAgentSkill, ClaudeAgentThinking } from "./adapter.js";
5
5
  export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
6
6
  export { findClaudeExecutable as claudeAgentExecutable, platformSuffix as claudeAgentPlatform } from "./binary.js";
7
- export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, CLAUDE_WEB_SEARCH_USD, OWN_TOOL_PREFIX, thinks, withWebSearches } from "./host/policy.js";
7
+ export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, OWN_TOOL_PREFIX, thinks, withWebSearches } from "./host/policy.js";
8
8
  export type { AnthropicPolicyOptions, AnthropicUsage } from "./host/policy.js";
9
9
  export type { ChildCommand, ConfineChild } from "./host/machine.js";
10
10
  export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer, type ToolServerModules } from "./host/tool-server.js";
package/dist/index.js CHANGED
@@ -3,5 +3,5 @@ export { CLAUDE_AGENT_ALSO_OFF, CLAUDE_AGENT_CLI_SKILL_NAMES, CLAUDE_AGENT_DIGES
3
3
  export { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
4
4
  export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
5
5
  export { findClaudeExecutable as claudeAgentExecutable, platformSuffix as claudeAgentPlatform } from "./binary.js";
6
- export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, CLAUDE_WEB_SEARCH_USD, OWN_TOOL_PREFIX, thinks, withWebSearches } from "./host/policy.js";
6
+ export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, OWN_TOOL_PREFIX, thinks, withWebSearches } from "./host/policy.js";
7
7
  export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer } from "./host/tool-server.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-harness-claude",
3
- "version": "0.1.0-beta.37",
3
+ "version": "0.1.0-beta.38",
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",
@@ -48,7 +48,7 @@
48
48
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
49
49
  },
50
50
  "dependencies": {
51
- "@parcha/agentrun-kernel": "0.1.0-beta.37"
51
+ "@parcha/agentrun-kernel": "0.1.0-beta.38"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "@anthropic-ai/claude-agent-sdk": "0.3.286",
@@ -77,6 +77,6 @@
77
77
  },
78
78
  "devDependencies": {
79
79
  "@anthropic-ai/claude-agent-sdk": "0.3.286",
80
- "@parcha/agentrun-dsl": "0.1.0-beta.37"
80
+ "@parcha/agentrun-dsl": "0.1.0-beta.38"
81
81
  }
82
82
  }