Skip to content
TypeScript

fix(claude): ENABLE_TOOL_SEARCH=auto no longer costs 10x cache writes per session (#24654)

Theo Browne24c80f34a101
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 8f47399116a..9dc129c7aa0 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -272,6 +272,40 @@ describe("ClaudeAdapterV2 runtime query policy", () => {
);
});
+ it("pins Claude's auto tool search on through flag settings", () => {
+ const override = ClaudeAdapterV2.claudeToolSearchOverride;
+ for (const value of ["auto", "auto:10", "auto:99.5", "auto:x", "auto:Infinity"]) {
+ assert.equal(override(value), "true", value);
+ }
+ for (const value of [
+ undefined,
+ "true",
+ "false",
+ "auto:0",
+ "auto:-5",
+ "auto:100",
+ "auto:1e2",
+ "auto:1_000",
+ "auto:1,000",
+ "AUTO",
+ ]) {
+ assert.isUndefined(override(value), String(value));
+ }
+
+ const options = ClaudeAdapterV2.makeClaudeQueryOptions({
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
+ nativeThreadId: "native-tool-search",
+ resume: false,
+ cwd: "/workspace",
+ sdkSettings: { env: { OTHER: "kept" } },
+ toolSearchOverride: "true",
+ });
+ assert.deepEqual((options.settings as { env?: Record<string, string> }).env, {
+ OTHER: "kept",
+ ENABLE_TOOL_SEARCH: "true",
+ });
+ });
+
it("projects AskUserQuestion input with question text as the answer key", () => {
const preview = "\n **Proposed change**\n\n```ts\n\tconst enabled = true;\n```\n ";
assert.deepEqual(
@@ -2846,6 +2880,96 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
),
);
+
+ it.effect("pins tool search on when the user's Claude settings choose auto", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const home = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-claude-tool-search-",
+ });
+ const openedToolSearch = (
+ settingsJson: string,
+ cwd = CLAUDE_TEST_RUNTIME_POLICY.cwd,
+ environment?: NodeJS.ProcessEnv,
+ ) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ yield* fileSystem.writeFileString(path.join(home, "settings.json"), settingsJson);
+ const harness = yield* makeWakeHarnessWithOptions({
+ settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home },
+ ...(environment === undefined ? {} : { environment }),
+ });
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("attempt-tool-search"),
+ text: "Run git status.",
+ attachments: [],
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ ...CLAUDE_TEST_RUNTIME_POLICY,
+ cwd,
+ }),
+ }),
+ );
+ const settings = harness.getOpenedOptions()?.settings;
+ return typeof settings === "object" ? settings.env?.ENABLE_TOOL_SEARCH : undefined;
+ }),
+ );
+ assert.equal(yield* openedToolSearch('{"env":{"ENABLE_TOOL_SEARCH":"auto"}}'), "true");
+ assert.isUndefined(yield* openedToolSearch('{"env":{"ENABLE_TOOL_SEARCH":"false"}}'));
+ assert.isUndefined(yield* openedToolSearch("{}"));
+
+ // Claude Code keeps the local file at the repository root, the main checkout's root in a
+ // worktree, and that file beats the user's settings.
+ const repo = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-repo-" });
+ const worktree = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-wt-" });
+ const worktreeGitDir = path.join(repo, ".git", "worktrees", "wt");
+ yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true });
+ yield* fileSystem.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n");
+ yield* fileSystem.writeFileString(
+ path.join(worktree, ".git"),
+ `gitdir: ${worktreeGitDir}\n`,
+ );
+ yield* fileSystem.makeDirectory(path.join(repo, ".claude"));
+ yield* fileSystem.makeDirectory(path.join(repo, "packages", "app"), { recursive: true });
+ const rootLocal = (value: string) =>
+ fileSystem.writeFileString(
+ path.join(repo, ".claude", "settings.local.json"),
+ `{"env":{"ENABLE_TOOL_SEARCH":"${value}"}}`,
+ );
+ const userAuto = '{"env":{"ENABLE_TOOL_SEARCH":"auto"}}';
+ yield* rootLocal("auto");
+ assert.equal(yield* openedToolSearch("{}", worktree), "true");
+ yield* rootLocal("false");
+ assert.isUndefined(yield* openedToolSearch(userAuto, worktree));
+ assert.isUndefined(yield* openedToolSearch(userAuto, path.join(repo, "packages", "app")));
+
+ // Project settings beat user settings, and the process env applies only when no file sets it.
+ const project = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-project-" });
+ yield* fileSystem.makeDirectory(path.join(project, ".claude"));
+ yield* fileSystem.writeFileString(
+ path.join(project, ".claude", "settings.json"),
+ '{"env":{"ENABLE_TOOL_SEARCH":"auto"}}',
+ );
+ assert.equal(
+ yield* openedToolSearch('{"env":{"ENABLE_TOOL_SEARCH":"false"}}', project),
+ "true",
+ );
+ assert.equal(
+ yield* openedToolSearch("{}", CLAUDE_TEST_RUNTIME_POLICY.cwd, {
+ ENABLE_TOOL_SEARCH: "auto",
+ }),
+ "true",
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ );
});
describe("Plan-mode tool approval", () => {
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 4ec159aa54c..9dea43bf9e7 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -1273,6 +1273,35 @@ export function claudeQueryEnvironment(
return { ...environment, CLAUDE_CODE_PROMPT_CACHE_TTL: subagentPromptCacheTtl };
}
+// Claude Code's auto tool search sends every MCP schema in full while they fit under a share of the
+// context window, which T3's tools do on 1M models. auto:0 already means on and auto:100 off.
+export function claudeToolSearchOverride(value: string | undefined): "true" | undefined {
+ if (value === undefined) return undefined;
+ if (value === "auto") return "true";
+ if (!value.startsWith("auto:")) return undefined;
+ const percent = parseClaudeInteger(value.slice("auto:".length));
+ // Claude Code treats an unparsable auto:N as auto, and clamps N to 0..100.
+ if (Number.isNaN(percent)) return "true";
+ const clamped = Math.min(100, Math.max(0, percent));
+ return clamped > 0 && clamped < 100 ? "true" : undefined;
+}
+
+// Claude Code 2.1.310's integer parsing for auto:N. Scientific notation counts only when it is an
+// integer, grouped digits (1_000, 1,000, or 1 000) are joined, and anything else uses parseInt.
+const CLAUDE_SCIENTIFIC_INTEGER = /^[+-]?(\d+(\.\d*)?|\.\d+)[eE][+-]?\d+$/;
+const CLAUDE_GROUPED_INTEGER = /^[+-]?\d{1,3}([_,\u00A0\u202F ])\d{3}(?:\1\d{3})*$/;
+function parseClaudeInteger(text: string): number {
+ const value = text.trim();
+ if (value.length <= 32 && CLAUDE_SCIENTIFIC_INTEGER.test(value)) {
+ const number = Number(value);
+ return Number.isInteger(number) ? number : Number.NaN;
+ }
+ if (value.length <= 32 && CLAUDE_GROUPED_INTEGER.test(value)) {
+ return Number.parseInt(value.replace(/[_,\u00A0\u202F ]/g, ""), 10);
+ }
+ return Number.parseInt(value, 10);
+}
+
// Claude Code defers MCP tools behind ToolSearch, so the agent only finds
// t3_background_wait when the system prompt says when to reach for it.
const CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS = `
@@ -1302,6 +1331,8 @@ export function makeClaudeQueryOptions(input: {
readonly supportedDialogKinds?: ClaudeQueryOptions["supportedDialogKinds"];
readonly allowDangerouslySkipPermissions?: boolean;
readonly appendSystemPromptFileText?: string;
+ // Flag settings, because a user's settings.json env beats the process env in Claude Code.
+ readonly toolSearchOverride?: "true";
}): ClaudeAgentSdkQueryOptions {
const compiledSelection = compileClaudeModelSelection(input.modelSelection);
const {
@@ -1338,13 +1369,21 @@ export function makeClaudeQueryOptions(input: {
: typeof input.sdkSettings === "object" && input.sdkSettings !== null
? ({ ...input.sdkSettings, ...selectionSettings } as ClaudeSdkSettings)
: selectionSettings;
- const effectiveQuerySettings =
+ const compactQuerySettings =
input.settings?.autoCompactWindow === undefined || input.settings.autoCompactWindow.length === 0
? querySettings
: ({
...(typeof querySettings === "object" && querySettings !== null ? querySettings : {}),
autoCompactWindow: Number(input.settings.autoCompactWindow),
} as ClaudeSdkSettings);
+ // A settings file path cannot take extra keys, so it goes through unchanged.
+ const effectiveQuerySettings =
+ input.toolSearchOverride === undefined || typeof compactQuerySettings === "string"
+ ? compactQuerySettings
+ : ({
+ ...compactQuerySettings,
+ env: { ...compactQuerySettings?.env, ENABLE_TOOL_SEARCH: input.toolSearchOverride },
+ } as ClaudeSdkSettings);
const options: ClaudeAgentSdkQueryOptions = {
model: compiledSelection.apiModelId,
tools: claudeAgentSdkQueryToolsForSdk(selectedTools),
@@ -2160,6 +2199,14 @@ const decodeClaudeSubagentCacheSettings = Schema.decodeUnknownEffect(
),
),
);
+const decodeClaudeEnvSettings = Schema.decodeUnknownEffect(
+ fromLenientJson(
+ Schema.StructWithRest(
+ Schema.Struct({ env: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)) }),
+ [Schema.Record(Schema.String, Schema.Unknown)],
+ ),
+ ),
+);
function claudeBypassAvailability(
settings: typeof ClaudeBypassSettings.Type,
@@ -3946,6 +3993,73 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
},
);
+ const readToolSearchSetting = (filePath: string) =>
+ fileSystem.readFileString(filePath).pipe(
+ Effect.flatMap(decodeClaudeEnvSettings),
+ Effect.map((settings) => {
+ const value = settings.env?.ENABLE_TOOL_SEARCH;
+ return typeof value === "string" ? value : undefined;
+ }),
+ Effect.orElseSucceed(() => undefined),
+ );
+ // A worktree's .git file points at <main>/.git/worktrees/<name>, whose commondir leads back to
+ // <main>/.git. A bare repository has no main checkout, so its worktree keeps its own file.
+ const mainCheckoutRoot = (checkout: string) =>
+ fileSystem.readFileString(path.join(checkout, ".git")).pipe(
+ Effect.flatMap((pointer) => {
+ const gitDir = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim();
+ if (gitDir === undefined) return Effect.succeed(checkout);
+ const worktreeGitDir = path.resolve(checkout, gitDir);
+ return fileSystem.readFileString(path.join(worktreeGitDir, "commondir")).pipe(
+ Effect.map((commonDir) => {
+ const common = path.resolve(worktreeGitDir, commonDir.trim());
+ return path.basename(common) === ".git" ? path.dirname(common) : checkout;
+ }),
+ );
+ }),
+ Effect.orElseSucceed(() => checkout),
+ );
+ // Claude Code keeps .claude/settings.local.json at the repository root, or in cwd outside a
+ // repository, on Windows, or when the root is home. Its owner check is skipped: missing it only
+ // leaves tool search on, Claude Code's default.
+ const localSettingsDirectory = Effect.fn("ClaudeAdapterV2.localSettingsDirectory")(function* (
+ cwd: string,
+ ) {
+ if ((yield* HostProcess.Platform) === "win32") return cwd;
+ for (let directory = cwd; ; directory = path.dirname(directory)) {
+ const isCheckout = yield* fileSystem
+ .exists(path.join(directory, ".git"))
+ .pipe(Effect.orElseSucceed(() => false));
+ if (isCheckout) {
+ const root = yield* mainCheckoutRoot(directory);
+ return root === (yield* HostProcess.HomeDirectory) ? cwd : root;
+ }
+ if (path.dirname(directory) === directory) return cwd;
+ }
+ });
+ // Settings env beats the process env, local over project over user, and a local file an older
+ // Claude Code left in cwd applies under the root one. resolveSettings reads local from cwd only.
+ const resolveToolSearchOverride = Effect.fn("ClaudeAdapterV2.resolveToolSearchOverride")(
+ function* (cwd: string | null) {
+ const localDirectory = cwd === null ? null : yield* localSettingsDirectory(cwd);
+ const settingsFiles = [
+ ...(cwd === null || localDirectory === null
+ ? []
+ : [
+ path.join(localDirectory, ".claude", "settings.local.json"),
+ ...(localDirectory === cwd ? [] : [path.join(cwd, ".claude", "settings.local.json")]),
+ path.join(cwd, ".claude", "settings.json"),
+ ]),
+ path.join(homePath, "settings.json"),
+ ];
+ for (const settingsFile of settingsFiles) {
+ const value = yield* readToolSearchSetting(settingsFile);
+ if (value !== undefined) return claudeToolSearchOverride(value);
+ }
+ return claudeToolSearchOverride(adapterOptions.environment.ENABLE_TOOL_SEARCH);
+ },
+ );
+
const userInvocableSkills = (cwd: string | null) =>
discoverClaudeSkills(
adapterOptions.settings,
@@ -9220,6 +9334,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
turnInput.nativeThreadHasTurns ?? turnInput.providerTurnOrdinal > 1;
const shouldResume =
resumeSessionAt !== undefined || openedWithResume || hasPersistedProviderTurn;
+ const toolSearchOverride = yield* resolveToolSearchOverride(turnInput.runtimePolicy.cwd);
const queryOptions = makeClaudeQueryOptions({
modelSelection: turnInput.modelSelection,
nativeThreadId,
@@ -9252,6 +9367,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
onUserDialog,
supportedDialogKinds: ["resume_return"],
...(appendSystemPromptFileText === undefined ? {} : { appendSystemPromptFileText }),
+ ...(toolSearchOverride === undefined ? {} : { toolSearchOverride }),
});
const querySession = yield* queryRunner
.open({