Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix: preserve Claude Code tool-search deferral through the proxy (#746) (#753)

Tejas Chopra1c8c538780d5
diff --git a/docs/content/docs/troubleshooting.mdx b/docs/content/docs/troubleshooting.mdx
index 1ca58a852..0cfb613e5 100644
--- a/docs/content/docs/troubleshooting.mdx
+++ b/docs/content/docs/troubleshooting.mdx
@@ -109,6 +109,47 @@ config.smart_crusher.min_tokens_to_crush = 100 # Default is 200
</Tab>
</Tabs>
+## Claude Code context window is larger through the proxy
+
+**Symptom**: After pointing Claude Code at Headroom (`ANTHROPIC_BASE_URL`), `/context all`
+shows **more** tokens used than a direct session — the "System tools" and "MCP tools"
+lines grow by tens of thousands of tokens, before you send any message.
+
+**Cause**: Claude Code normally defers most tool schemas behind its server-side
+**Tool Search Tool** (it sends only tool *names* and loads full schemas on demand).
+It enables this only when it believes it is talking directly to `api.anthropic.com`.
+The moment `ANTHROPIC_BASE_URL` is a custom host, Claude Code can't assume the endpoint
+supports the feature, so it falls back to **eagerly** materializing every tool schema
+into the local context window. This is a Claude Code client-side decision made before
+the request reaches the proxy — no proxy header can reverse it.
+
+**Solution**: set `ENABLE_TOOL_SEARCH` so Claude Code keeps deferring tools through the
+proxy. The proxy forwards the `tool_reference` blocks correctly, so deferral works
+end-to-end (both streaming and non-streaming, subscription and API-key auth).
+
+```bash
+# Easiest: `headroom wrap claude` sets ENABLE_TOOL_SEARCH=true automatically.
+headroom wrap claude
+
+# Choose the mode (true = always defer, the default; auto / auto:N = defer only
+# when tool definitions exceed N% of the budget; false = off):
+headroom wrap claude --tool-search auto
+
+# Running `claude` manually instead of via wrap? Set it yourself:
+ENABLE_TOOL_SEARCH=true ANTHROPIC_BASE_URL=http://localhost:8787 claude
+```
+
+**Verify (before / after)** with `/context all` in a fresh session, no messages sent:
+
+| Section | Eager (no `ENABLE_TOOL_SEARCH`) | Deferred (`ENABLE_TOOL_SEARCH=true`) |
+| --- | --- | --- |
+| System tools | fully materialized | deferred subset |
+| MCP tools | every tool shows a token cost | `(loaded on-demand)`, 0 tokens |
+
+When deferral is off, the proxy log also prints a one-time hint naming the fix.
+
+See [issue #746](https://github.com/chopratejas/headroom/issues/746) for the full analysis.
+
## Compression Too Aggressive
**Symptom**: LLM responses are missing information that was in tool outputs.
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index b576b3c9e..0b2eb8971 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -88,6 +88,63 @@ _CONTEXT_TOOL_RTK = "rtk"
_CONTEXT_TOOL_LEAN_CTX = "lean-ctx"
_VALID_CONTEXT_TOOLS = {_CONTEXT_TOOL_RTK, _CONTEXT_TOOL_LEAN_CTX}
+# Issue #746: Claude Code disables on-demand tool loading (deferral) when
+# ANTHROPIC_BASE_URL is a custom host and ENABLE_TOOL_SEARCH is unset, which
+# inflates the local context window by tens of K tokens. Setting the env var
+# when we launch Claude Code keeps deferral on. Default to "true" — defer the
+# MCP/system tools for maximum context savings, matching native first-party
+# behaviour (core built-ins like Read/Edit/Bash are never deferred by Claude
+# Code, so the agent loop is unaffected).
+_TOOL_SEARCH_ENV = "ENABLE_TOOL_SEARCH"
+_TOOL_SEARCH_DEFAULT = "true"
+
+
+def _normalize_tool_search_mode(value: str) -> str:
+ """Validate an ``ENABLE_TOOL_SEARCH`` value and return it normalized.
+
+ Mirrors the values Claude Code accepts: truthy (``true``/``1``/``yes``/
+ ``on``), falsy (``false``/``0``/``no``/``off``), ``auto``, or ``auto:N``
+ where ``N`` is 0-100. Raises :class:`click.ClickException` on anything else
+ so a typo fails loudly instead of silently leaving deferral off.
+ """
+ normalized = value.strip().lower()
+ if normalized in {"true", "1", "yes", "on", "false", "0", "no", "off", "auto"}:
+ return normalized
+ if normalized.startswith("auto:"):
+ suffix = normalized[len("auto:") :]
+ if suffix.isdigit() and 0 <= int(suffix) <= 100:
+ return normalized
+ raise click.ClickException(
+ f"--tool-search must be one of: true, false, auto, auto:N (N 0-100); got {value!r}"
+ )
+
+
+def _configure_tool_search_env(env: dict[str, str], flag_value: str | None) -> str | None:
+ """Set ``ENABLE_TOOL_SEARCH`` in ``env`` so Claude Code keeps deferring tools.
+
+ Precedence:
+
+ 1. explicit ``--tool-search`` flag — wins (the user asked for it on the CLI),
+ 2. a pre-existing ``ENABLE_TOOL_SEARCH`` in the environment — respected and
+ left untouched (the user's own Claude Code knob),
+ 3. the built-in default (``true``).
+
+ Returns the value written, or ``None`` when an existing environment value
+ was deliberately left in place.
+ """
+ if flag_value is not None:
+ value = _normalize_tool_search_mode(flag_value)
+ env[_TOOL_SEARCH_ENV] = value
+ return value
+ # An empty / whitespace value counts as unset: Claude Code treats an empty
+ # ENABLE_TOOL_SEARCH as absent (so deferral would stay off), so we override
+ # it with the default rather than forwarding a no-op value.
+ existing = env.get(_TOOL_SEARCH_ENV)
+ if existing is not None and existing.strip():
+ return None
+ env[_TOOL_SEARCH_ENV] = _TOOL_SEARCH_DEFAULT
+ return _TOOL_SEARCH_DEFAULT
+
def _live_wrap_module() -> Any:
"""Return the current live wrap module instance."""
@@ -2178,6 +2235,19 @@ def unwrap() -> None:
"--learn", is_flag=True, help="Enable live traffic learning (patterns saved to MEMORY.md)"
)
@click.option("--memory", is_flag=True, help="Enable persistent cross-session memory")
+ "--tool-search",
+ "tool_search",
+ default=None,
+ metavar="MODE",
+ help=(
+ "Keep Claude Code's on-demand tool loading (deferral) active through the "
+ "proxy. MODE is true (default), auto, auto:N, or false. Without it, a "
+ "custom ANTHROPIC_BASE_URL makes Claude Code load every tool schema "
+ "eagerly, inflating local context (issue #746). A pre-set "
+ "ENABLE_TOOL_SEARCH env var is respected."
+ ),
+)
@click.option("--verbose", "-v", is_flag=True, help="Verbose output")
@click.option("--prepare-only", is_flag=True, hidden=True)
@click.argument("claude_args", nargs=-1, type=click.UNPROCESSED)
@@ -2190,6 +2260,7 @@ def claude(
no_proxy: bool,
learn: bool,
memory: bool,
+ tool_search: str | None,
verbose: bool,
prepare_only: bool,
claude_args: tuple,
@@ -2225,6 +2296,10 @@ def claude(
click.echo("Install Claude Code: https://docs.anthropic.com/en/docs/claude-code")
raise SystemExit(1)
+ # Validate --tool-search up front so a typo fails before we start the proxy.
+ if tool_search is not None:
+ tool_search = _normalize_tool_search_mode(tool_search)
+
# Setup rtk before launching (Claude-specific)
proxy_holder: list[subprocess.Popen | None] = [None]
cleanup = _make_cleanup(proxy_holder, port)
@@ -2343,6 +2418,20 @@ def claude(
else:
env["ANTHROPIC_BASE_URL"] = proxy_url
+ # Issue #746: keep Claude Code's on-demand tool loading on through the
+ # proxy so tool schemas are not eagerly materialized into local context.
+ _tool_search_value = _configure_tool_search_env(env, tool_search)
+ if _tool_search_value is not None:
+ click.echo(
+ f" {_TOOL_SEARCH_ENV}={_tool_search_value} "
+ "(on-demand tool loading kept on; issue #746)"
+ )
+ elif verbose:
+ click.echo(
+ f" {_TOOL_SEARCH_ENV}={env.get(_TOOL_SEARCH_ENV)} "
+ "(using your existing environment value)"
+ )
+
result = subprocess.run([claude_bin, *claude_args], env=env)
raise SystemExit(result.returncode)
diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.py
index df05de481..593a8c28e 100644
--- a/headroom/proxy/handlers/anthropic.py
+++ b/headroom/proxy/handlers/anthropic.py
@@ -1239,6 +1239,37 @@ class AnthropicHandlerMixin:
# `frozen_message_count > 0` guard below).
tools = body.get("tools")
_original_tools = tools # Preserve for diagnostic / future retry
+
+ # Issue #746: when Claude Code talks to a custom ANTHROPIC_BASE_URL
+ # with ENABLE_TOOL_SEARCH unset, it stops deferring tool schemas and
+ # loads them all into local context. That is a client-side decision
+ # we cannot reverse from here, so emit a single actionable hint for
+ # users who launch `claude` manually (the wrap path sets the env var).
+ # Gate on the cheap one-time flag first so the detection scan stops
+ # running once the hint has fired; never let it break a request.
+ from headroom.proxy.helpers import tool_search_hint_pending
+
+ if tool_search_hint_pending():
+ try:
+ from headroom.proxy.helpers import (
+ claude_code_tool_search_inactive,
+ format_tool_search_disabled_hint,
+ take_tool_search_hint_slot,
+ )
+
+ if (
+ claude_code_tool_search_inactive(
+ client=client,
+ tools=tools,
+ anthropic_beta=request.headers.get("anthropic-beta"),
+ )
+ and take_tool_search_hint_slot()
+ ):
+ logger.warning(
+ "[%s] %s", request_id, format_tool_search_disabled_hint(tools)
+ )
+ except Exception: # advisory hint only — must never fail a request
+ pass
if (
self.config.ccr_inject_tool or self.config.ccr_inject_system_instructions
) and not _bypass:
diff --git a/headroom/proxy/helpers.py b/headroom/proxy/helpers.py
index c8ebf122c..1930ec188 100644
--- a/headroom/proxy/helpers.py
+++ b/headroom/proxy/helpers.py
@@ -2827,3 +2827,112 @@ def compute_turn_id(
h.update(b"\0")
h.update(prefix_json.encode("utf-8", errors="replace"))
return h.hexdigest()[:16]
+
+
+# ---------------------------------------------------------------------------
+# Issue #746: Claude Code on-demand tool loading (deferral) detection
+#
+# When Claude Code points at a custom ``ANTHROPIC_BASE_URL`` (the proxy) with
+# ``ENABLE_TOOL_SEARCH`` unset, it stops deferring MCP/system tool schemas
+# behind the server-side Tool Search Tool and materializes them all into its
+# local context window — tens of K tokens. That decision is made client-side
+# before the request reaches us, so the proxy cannot reverse it; the only
+# remedy is the ``ENABLE_TOOL_SEARCH`` env var (set automatically by
+# ``headroom wrap claude``). For users who run ``claude`` manually we cannot
+# touch their environment, so the proxy emits a single actionable hint.
+# ---------------------------------------------------------------------------
+
+_TOOL_SEARCH_TOOL_TYPE_PREFIX = "tool_search_tool_"
+# Substrings of the ``anthropic-beta`` tokens that gate tool search:
+# ``advanced-tool-use-2025-11-20`` (firstParty/foundry) and
+# ``tool-search-tool-2025-10-19`` (vertex/bedrock/mantle/gateway).
+_TOOL_SEARCH_BETA_MARKERS = ("advanced-tool-use", "tool-search-tool")
+
+_tool_search_hint_lock = threading.Lock()
+_tool_search_hint_emitted = False
+
+
+def claude_code_tool_search_inactive(
+ *,
+ client: str | None,
+ tools: Any,
+ anthropic_beta: str | None,
+) -> bool:
+ """Return ``True`` when a Claude Code request is *not* deferring tools.
+
+ Detected from request shape alone — no token thresholds, so it scales to
+ any tool surface:
+
+ * the request is from Claude Code (``client == "claude-code"``),
+ * it carries one or more tool definitions, yet
+ * it includes neither a ``tool_search_tool_*`` tool nor a tool-search
+ ``anthropic-beta`` token.
+
+ In that combination Claude Code has eagerly materialized every tool schema
+ into its local context window (issue #746).
+ """
+ if client != "claude-code":
+ return False
+ if not isinstance(tools, list) or not tools:
+ return False
+ for tool in tools:
+ if isinstance(tool, dict) and str(tool.get("type", "")).startswith(
+ _TOOL_SEARCH_TOOL_TYPE_PREFIX
+ ):
+ return False
+ beta = (anthropic_beta or "").lower()
+ return not any(marker in beta for marker in _TOOL_SEARCH_BETA_MARKERS)
+
+
+def format_tool_search_disabled_hint(tools: list[Any]) -> str:
+ """Build the one-time, actionable hint for issue #746.
+
+ Reports factual, directional numbers (tool count and serialized schema
+ size) rather than a derived token estimate, which avoids implying a
+ precision the proxy cannot measure for the client's tokenizer.
+ """
+ try:
+ schema_kb = len(json.dumps(tools, separators=(",", ":"), default=str)) / 1024
+ except (TypeError, ValueError):
+ schema_kb = 0.0
+ return (
+ f"Claude Code is sending all {len(tools)} tool definitions eagerly "
+ f"(~{schema_kb:.0f} KB of tool schema in local context) because "
+ "ENABLE_TOOL_SEARCH is unset with a custom ANTHROPIC_BASE_URL. Set "
+ "ENABLE_TOOL_SEARCH=true (or auto) to keep on-demand tool loading active, "
+ "or launch via `headroom wrap claude` (which sets it automatically). "
+ "See https://github.com/chopratejas/headroom/issues/746"
+ )
+
+
+def tool_search_hint_pending() -> bool:
+ """Cheap, lock-free check of whether the one-time hint may still fire.
+
+ Lets the request hot path skip the (O(number-of-tools)) detection scan on
+ every request once the hint has already been emitted. A benign race here
+ only costs one extra detection scan, never a duplicate warning — the
+ actual one-shot guarantee lives in :func:`take_tool_search_hint_slot`.
+ """
+ return not _tool_search_hint_emitted
+
+
+def take_tool_search_hint_slot() -> bool:
+ """Return ``True`` exactly once per process, gating the one-time hint.
+
+ Thread-safe so concurrent requests cannot each emit the warning.
+ """
+ global _tool_search_hint_emitted
+ if _tool_search_hint_emitted:
+ return False
+ with _tool_search_hint_lock:
+ if _tool_search_hint_emitted:
+ return False
+ _tool_search_hint_emitted = True
+ return True
+
+
+def reset_tool_search_hint_state() -> None:
+ """Reset the one-time hint guard. Test helper only."""
+ global _tool_search_hint_emitted
+ with _tool_search_hint_lock:
+ _tool_search_hint_emitted = False
diff --git a/tests/test_issue_746_tool_search.py b/tests/test_issue_746_tool_search.py
new file mode 100644
index 000000000..e6ebd28f1
--- /dev/null
+++ b/tests/test_issue_746_tool_search.py
@@ -0,0 +1,168 @@
+"""Issue #746: keep Claude Code's on-demand tool loading active through the proxy.
+
+Covers the two halves of the fix:
+
+* ``headroom wrap claude`` injects ``ENABLE_TOOL_SEARCH`` into the launched
+ Claude Code environment (with correct precedence / validation), and
+* the proxy detects a Claude Code request that is *not* deferring tools and
+ emits a single actionable hint for users who run ``claude`` manually.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from headroom.cli.wrap import (
+ _TOOL_SEARCH_DEFAULT,
+ _TOOL_SEARCH_ENV,
+ _configure_tool_search_env,
+ _normalize_tool_search_mode,
+)
+from headroom.proxy.helpers import (
+ claude_code_tool_search_inactive,
+ format_tool_search_disabled_hint,
+ reset_tool_search_hint_state,
+ take_tool_search_hint_slot,
+ tool_search_hint_pending,
+)
+
+# ---------------------------------------------------------------------------
+# wrap: ENABLE_TOOL_SEARCH value normalization
+# ---------------------------------------------------------------------------
+
+
+ "value,expected",
+ [
+ ("true", "true"),
+ ("TRUE", "true"),
+ (" on ", "on"),
+ ("1", "1"),
+ ("false", "false"),
+ ("off", "off"),
+ ("auto", "auto"),
+ ("auto:0", "auto:0"),
+ ("auto:50", "auto:50"),
+ ("auto:100", "auto:100"),
+ ],
+)
+def test_normalize_tool_search_mode_accepts_valid(value: str, expected: str) -> None:
+ assert _normalize_tool_search_mode(value) == expected
+
+
[email protected]("value", ["yep", "auto:", "auto:101", "auto:-1", "auto:abc", ""])
+def test_normalize_tool_search_mode_rejects_invalid(value: str) -> None:
+ import click
+
+ with pytest.raises(click.ClickException):
+ _normalize_tool_search_mode(value)
+
+
+# ---------------------------------------------------------------------------
+# wrap: ENABLE_TOOL_SEARCH injection precedence
+# ---------------------------------------------------------------------------
+
+
+def test_configure_injects_default_when_unset() -> None:
+ env: dict[str, str] = {}
+ result = _configure_tool_search_env(env, None)
+ assert result == _TOOL_SEARCH_DEFAULT
+ assert env[_TOOL_SEARCH_ENV] == _TOOL_SEARCH_DEFAULT
+
+
+def test_configure_respects_existing_env_value() -> None:
+ env = {_TOOL_SEARCH_ENV: "auto:30"}
+ result = _configure_tool_search_env(env, None)
+ # None signals "left the user's value untouched".
+ assert result is None
+ assert env[_TOOL_SEARCH_ENV] == "auto:30"
+
+
+def test_configure_flag_overrides_existing_env_value() -> None:
+ env = {_TOOL_SEARCH_ENV: "false"}
+ result = _configure_tool_search_env(env, "auto")
+ assert result == "auto"
+ assert env[_TOOL_SEARCH_ENV] == "auto"
+
+
[email protected]("blank", ["", " ", "\t"])
+def test_configure_overrides_blank_env_value(blank: str) -> None:
+ # Claude Code treats an empty ENABLE_TOOL_SEARCH as unset, so a blank value
+ # must be replaced with the default rather than forwarded as a no-op.
+ env = {_TOOL_SEARCH_ENV: blank}
+ result = _configure_tool_search_env(env, None)
+ assert result == _TOOL_SEARCH_DEFAULT
+ assert env[_TOOL_SEARCH_ENV] == _TOOL_SEARCH_DEFAULT
+
+
+def test_configure_flag_validated() -> None:
+ import click
+
+ with pytest.raises(click.ClickException):
+ _configure_tool_search_env({}, "nonsense")
+
+
+# ---------------------------------------------------------------------------
+# proxy: detect a Claude Code request that is not deferring tools
+# ---------------------------------------------------------------------------
+
+_TOOLS = [
+ {"name": "Read", "description": "read a file", "input_schema": {"type": "object"}},
+ {"name": "Bash", "description": "run a command", "input_schema": {"type": "object"}},
+]
+
+
+def test_inactive_true_for_eager_claude_code() -> None:
+ assert claude_code_tool_search_inactive(client="claude-code", tools=_TOOLS, anthropic_beta=None)
+
+
+def test_inactive_false_when_tool_search_tool_present() -> None:
+ tools = [*_TOOLS, {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"}]
+ assert not claude_code_tool_search_inactive(
+ client="claude-code", tools=tools, anthropic_beta=None
+ )
+
+
+def test_inactive_false_when_beta_header_present() -> None:
+ assert not claude_code_tool_search_inactive(
+ client="claude-code",
+ tools=_TOOLS,
+ anthropic_beta="context-1m-2025-08-07,advanced-tool-use-2025-11-20",
+ )
+
+
+def test_inactive_false_for_other_clients() -> None:
+ assert not claude_code_tool_search_inactive(client="codex", tools=_TOOLS, anthropic_beta=None)
+ assert not claude_code_tool_search_inactive(client=None, tools=_TOOLS, anthropic_beta=None)
+
+
+def test_inactive_false_when_no_tools() -> None:
+ assert not claude_code_tool_search_inactive(client="claude-code", tools=[], anthropic_beta=None)
+ assert not claude_code_tool_search_inactive(
+ client="claude-code", tools=None, anthropic_beta=None
+ )
+
+
+# ---------------------------------------------------------------------------
+# proxy: hint content + one-time guard
+# ---------------------------------------------------------------------------
+
+
+def test_hint_message_is_actionable() -> None:
+ msg = format_tool_search_disabled_hint(_TOOLS)
+ assert "ENABLE_TOOL_SEARCH=true" in msg
+ assert "746" in msg
+ assert str(len(_TOOLS)) in msg
+
+
+def test_hint_slot_fires_once() -> None:
+ reset_tool_search_hint_state()
+ try:
+ assert tool_search_hint_pending() is True
+ assert take_tool_search_hint_slot() is True
+ # Once consumed, the cheap gate flips so the hot path stops scanning.
+ assert tool_search_hint_pending() is False
+ assert take_tool_search_hint_slot() is False
+ assert take_tool_search_hint_slot() is False
+ finally:
+ reset_tool_search_hint_state()