Skip to content

The agent that grows with you

fix(anthropic): alias session_search/memory OAuth billing-classifier triggers

joaomarcos9d3f1de9943f
diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.py
index ebdb5cff23b..939ac91db42 100644
--- a/agent/anthropic_adapter.py
+++ b/agent/anthropic_adapter.py
@@ -15,6 +15,7 @@ import json
import logging
import os
import platform
+import re
import secrets
import stat
import subprocess
@@ -516,6 +517,55 @@ def _detect_claude_code_version() -> str:
_CLAUDE_CODE_SYSTEM_PREFIX = "You are Claude Code, Anthropic's official CLI for Claude."
_MCP_TOOL_PREFIX = "mcp__"
+# Anthropic's OAuth billing classifier fingerprints certain Hermes tool
+# schemas/prose as a third-party app and reroutes the request to the metered
+# extra-usage lane, surfacing as HTTP 400 "You're out of extra usage" on a
+# valid subscription token (#65365). Deterministic live A/B repros (issue
+# #65365 comments, replayed with the anthropic-ratelimit-unified-* response
+# headers as a lane oracle) isolated two independent triggers:
+# - the ``session_search`` tool schema/name/prose, alone
+# - the ``memory`` tool schema/name, alone
+# Both are aliased to neutral names on the OAuth wire only. normalize_response
+# reverses the mapping before dispatch, so tool behavior and API-key requests
+# are unchanged.
+_OAUTH_TOOL_NAME_ALIASES = {
+ "session_search": "chat_history_lookup",
+ "memory": "context_notes",
+}
+_OAUTH_TOOL_NAME_REVERSE_ALIASES = {
+ wire_name: name for name, wire_name in _OAUTH_TOOL_NAME_ALIASES.items()
+}
+
+# Aliases that are ALSO safe to substitute in free-form prose (system prompt
+# text, tool descriptions). Only unambiguous snake_case tool tokens qualify:
+# "memory" is ordinary English throughout the system prompt ("persistent
+# memory across sessions", "OS, CPU, memory, disk") and inside the memory
+# tool's own parameter docs (the ``target`` enum the model must still emit
+# verbatim), so rewriting it in prose would corrupt guidance the model has
+# to follow. Renaming a tool is a different operation from rewriting the
+# vocabulary that describes it — a model that follows unaliased "memory"
+# prose and calls ``memory`` still dispatches correctly: normalize_response
+# resolves the bare name through the tool registry regardless.
+_OAUTH_PROSE_ALIAS_NAMES = frozenset({"session_search"})
+
+# Word-boundary matchers so a prose substitution can't corrupt a longer
+# identifier that merely contains the token (project AGENTS.md / memory
+# snapshots can carry arbitrary text, e.g. a path like
+# ``tools/session_search_tool.py`` must not become
+# ``tools/chat_history_lookup_tool.py``). ``\b`` treats ``_`` as a word
+# char, so only the standalone token matches.
+_OAUTH_PROSE_ALIAS_PATTERNS = tuple(
+ (re.compile(rf"\b{re.escape(name)}\b"), _OAUTH_TOOL_NAME_ALIASES[name])
+ for name in sorted(_OAUTH_PROSE_ALIAS_NAMES)
+)
+
+
+def _apply_oauth_prose_aliases(text: str) -> str:
+ """Rewrite prose-safe tool-name tokens to their OAuth wire aliases."""
+ for pattern, wire_name in _OAUTH_PROSE_ALIAS_PATTERNS:
+ text = pattern.sub(wire_name, text)
+ return text
+
def _get_claude_code_version() -> str:
"""Lazily detect the installed Claude Code version when OAuth headers need it."""
@@ -936,6 +986,7 @@ def build_anthropic_kwargs(
text = text.replace("Hermes agent", "Claude Code")
text = text.replace("hermes-agent", "claude-code")
text = text.replace("Nous Research", "Anthropic")
+ text = _apply_oauth_prose_aliases(text)
block["text"] = text
# 3. Normalize tool names so NOTHING goes on the OAuth wire with a
@@ -956,7 +1007,27 @@ def build_anthropic_kwargs(
# so any session with an MCP server configured still tripped the
# classifier. normalize_response reverses both forms via registry
# lookup so the dispatcher still sees the original name. GH-25255.
- def _to_oauth_wire_name(name: str) -> str:
+ # Wire names owned by tools that are NOT alias sources. An alias must
+ # never collide with one: two identical tool names in a single
+ # request is a hard 400 from Anthropic, strictly worse than the bug
+ # being fixed. Mirrors the "registered tool wins" precedence in
+ # normalize_response so outbound and inbound agree on who owns a
+ # contested name.
+ _claimed_wire_names = {
+ (_MCP_TOOL_PREFIX + tool["name"][len("mcp_"):]
+ if tool["name"].startswith("mcp_") and not tool["name"].startswith("mcp__")
+ else tool["name"] if tool["name"].startswith("mcp__")
+ else _MCP_TOOL_PREFIX + tool["name"])
+ for tool in (anthropic_tools or [])
+ if isinstance(tool.get("name"), str)
+ and tool["name"] not in _OAUTH_TOOL_NAME_ALIASES
+ }
+
+ def _to_oauth_wire_name(name: str, *, allow_alias: bool = True) -> str:
+ if allow_alias and name in _OAUTH_TOOL_NAME_ALIASES:
+ aliased = _OAUTH_TOOL_NAME_ALIASES[name]
+ if _MCP_TOOL_PREFIX + aliased not in _claimed_wire_names:
+ name = aliased
if name.startswith("mcp__"):
return name # already correct, don't double-prefix
if name.startswith("mcp_"):
@@ -968,6 +1039,10 @@ def build_anthropic_kwargs(
for tool in anthropic_tools:
if "name" in tool:
tool["name"] = _to_oauth_wire_name(tool["name"])
+ description = tool.get("description")
+ if isinstance(description, str):
+ # Prose-safe aliases only — see _OAUTH_PROSE_ALIAS_NAMES.
+ tool["description"] = _apply_oauth_prose_aliases(description)
# 4. Apply the same normalization to tool names in message history
# (tool_use blocks) so replayed turns match the wire names above.
@@ -1001,8 +1076,18 @@ def build_anthropic_kwargs(
# Anthropic has no tool_choice "none" — omit tools entirely to prevent use
kwargs.pop("tools", None)
elif isinstance(tool_choice, str):
- # Specific tool name
- kwargs["tool_choice"] = {"type": "tool", "name": tool_choice}
+ # Specific tool name. Under OAuth every tool on the wire is
+ # mcp__-prefixed and/or alias-renamed (see _to_oauth_wire_name
+ # above) — route the forced name through the same normalizer so
+ # tool_choice always matches the corresponding tools[] entry.
+ # Left un-normalized, a forced ``session_search``/``memory``
+ # choice would (a) still carry the literal trigger string onto
+ # the wire, defeating the alias, and (b) reference a tool name
+ # that no longer exists in ``tools[]``, which Anthropic rejects.
+ wire_tool_choice = tool_choice
+ if is_oauth:
+ wire_tool_choice = _to_oauth_wire_name(tool_choice)
+ kwargs["tool_choice"] = {"type": "tool", "name": wire_tool_choice}
# Map reasoning_config to Anthropic's thinking parameter.
# Claude 4.6+ models use adaptive thinking + output_config.effort.
diff --git a/agent/transports/anthropic.py b/agent/transports/anthropic.py
index 98721f7c5e6..3c42d7ded2f 100644
--- a/agent/transports/anthropic.py
+++ b/agent/transports/anthropic.py
@@ -84,7 +84,11 @@ class AnthropicTransport(ProviderTransport):
to OpenAI finish_reason, and collects reasoning_details in provider_data.
"""
import json
- from agent.anthropic_adapter import _to_plain_data, _sanitize_replay_block
+ from agent.anthropic_adapter import (
+ _OAUTH_TOOL_NAME_REVERSE_ALIASES,
+ _sanitize_replay_block,
+ _to_plain_data,
+ )
from agent.transports.types import ToolCall
strip_tool_prefix = kwargs.get("strip_tool_prefix", False)
@@ -151,6 +155,12 @@ class AnthropicTransport(ProviderTransport):
name = single
elif _tool_registry.get_entry(bare):
name = bare
+ elif bare in _OAUTH_TOOL_NAME_REVERSE_ALIASES:
+ # OAuth wire alias (e.g. chat_history_lookup ->
+ # session_search, #65365). Checked LAST so a real
+ # tool actually registered under the wire name
+ # still wins — same GH-25255 precedence.
+ name = _OAUTH_TOOL_NAME_REVERSE_ALIASES[bare]
tool_calls.append(
ToolCall(
id=block.id,
diff --git a/tests/agent/test_anthropic_mcp_prefix_strip.py b/tests/agent/test_anthropic_mcp_prefix_strip.py
index 41c75e904e7..16713128a4e 100644
--- a/tests/agent/test_anthropic_mcp_prefix_strip.py
+++ b/tests/agent/test_anthropic_mcp_prefix_strip.py
@@ -94,6 +94,56 @@ class TestAnthropicMcpPrefixStrip:
assert result.tool_calls[0].name == "mcp__read_file"
+class TestAnthropicOAuthAliasRoundTrip:
+ """#65365: session_search / memory schemas alone deterministically trip
+ Anthropic's OAuth billing classifier (verified live via the
+ anthropic-ratelimit-unified-* response headers, see issue comments).
+ Both are aliased to neutral wire names; normalize_response must reverse
+ the mapping so the dispatcher still sees the real tool."""
+
+ def _get_transport(self):
+ from agent.transports.anthropic import AnthropicTransport
+ return AnthropicTransport()
+
+ def test_oauth_session_search_alias_round_trips_to_registry_name(self):
+ transport = self._get_transport()
+ block = _make_tool_use_block("mcp__chat_history_lookup")
+ response = _make_response(block)
+
+ registry = _FakeRegistry({"session_search"})
+ with patch("tools.registry.registry", registry):
+ result = transport.normalize_response(response, strip_tool_prefix=True)
+
+ assert len(result.tool_calls) == 1
+ assert result.tool_calls[0].name == "session_search"
+
+ def test_oauth_memory_alias_round_trips_to_registry_name(self):
+ transport = self._get_transport()
+ block = _make_tool_use_block("mcp__context_notes")
+ response = _make_response(block)
+
+ registry = _FakeRegistry({"memory"})
+ with patch("tools.registry.registry", registry):
+ result = transport.normalize_response(response, strip_tool_prefix=True)
+
+ assert len(result.tool_calls) == 1
+ assert result.tool_calls[0].name == "memory"
+
+ def test_registered_tool_wins_over_oauth_alias(self):
+ """A real tool actually registered under the wire name keeps
+ GH-25255 precedence — the alias must not hijack it."""
+ transport = self._get_transport()
+ block = _make_tool_use_block("mcp__chat_history_lookup")
+ response = _make_response(block)
+
+ registry = _FakeRegistry({"mcp_chat_history_lookup", "session_search"})
+ with patch("tools.registry.registry", registry):
+ result = transport.normalize_response(response, strip_tool_prefix=True)
+
+ assert len(result.tool_calls) == 1
+ assert result.tool_calls[0].name == "mcp_chat_history_lookup"
+
+
@@ -106,14 +156,15 @@ class TestAnthropicOAuthOutgoingPrefix:
"""build_anthropic_kwargs must emit ZERO single-underscore ``mcp_`` names on
the OAuth wire — bare names and MCP server names both land on ``mcp__``."""
- def _build(self, tools, is_oauth=True):
+ def _build(self, tools, is_oauth=True, messages=None, tool_choice=None):
from agent.anthropic_adapter import build_anthropic_kwargs
return build_anthropic_kwargs(
model="claude-sonnet-4-6",
- messages=[{"role": "user", "content": "Hi"}],
+ messages=messages or [{"role": "user", "content": "Hi"}],
tools=tools,
max_tokens=4096,
reasoning_config=None,
+ tool_choice=tool_choice,
is_oauth=is_oauth,
)
@@ -155,3 +206,120 @@ class TestAnthropicOAuthOutgoingPrefix:
for n in names:
assert not (n.startswith("mcp_") and not n.startswith("mcp__"))
+
+# ---------------------------------------------------------------------------
+# #65365: session_search / memory OAuth billing-classifier trigger
+# ---------------------------------------------------------------------------
+
+class TestAnthropicOAuthClassifierAlias:
+ """OAuth must alias the two schemas issue #65365 isolated as independent,
+ deterministic triggers (session_search alone, memory alone) — in tool
+ name, tool description, system-prompt prose, and named tool_choice."""
+
+ def _build(self, tools, is_oauth=True, messages=None, tool_choice=None):
+ from agent.anthropic_adapter import build_anthropic_kwargs
+ return build_anthropic_kwargs(
+ model="claude-sonnet-4-6",
+ messages=messages or [{"role": "user", "content": "Hi"}],
+ tools=tools,
+ max_tokens=4096,
+ reasoning_config=None,
+ tool_choice=tool_choice,
+ is_oauth=is_oauth,
+ )
+
+ def _tool(self, name, description="x"):
+ return {"type": "function", "function": {"name": name, "description": description, "parameters": {}}}
+
+ def test_oauth_aliases_session_search_and_memory_names(self):
+ kwargs = self._build([
+ self._tool("session_search", "Use session_search to recall prior chats."),
+ self._tool("memory", "Persist notes with memory."),
+ ])
+ names = sorted(t["name"] for t in kwargs["tools"])
+ assert names == ["mcp__chat_history_lookup", "mcp__context_notes"]
+
+ def test_oauth_aliases_session_search_in_tool_description_not_memory(self):
+ """session_search is prose-safe (unambiguous token); memory is
+ ordinary English and must NOT be rewritten in free text — only its
+ tool name is aliased."""
+ kwargs = self._build([
+ self._tool("session_search", "Call session_search to recall prior chats."),
+ self._tool("memory", "Persist notes; uses working memory internally."),
+ ])
+ by_name = {t["name"]: t["description"] for t in kwargs["tools"]}
+ assert "chat_history_lookup" in by_name["mcp__chat_history_lookup"]
+ assert "session_search" not in by_name["mcp__chat_history_lookup"]
+ assert "memory" in by_name["mcp__context_notes"] # untouched prose
+
+ def test_oauth_aliases_session_search_in_system_prompt_prose(self):
+ kwargs = self._build(
+ [self._tool("session_search")],
+ messages=[
+ {"role": "system", "content": "When relevant, use session_search to recall it."},
+ {"role": "user", "content": "Hi"},
+ ],
+ )
+ system_text = "\n".join(
+ b["text"] for b in kwargs["system"] if isinstance(b, dict) and b.get("type") == "text"
+ )
+ assert "chat_history_lookup" in system_text
+ assert "session_search" not in system_text
+
+ def test_oauth_does_not_alias_longer_identifier_containing_token(self):
+ """Word-boundary matching: a path like tools/session_search_tool.py
+ must survive untouched, not become chat_history_lookup_tool.py."""
+ kwargs = self._build(
+ [self._tool("session_search")],
+ messages=[
+ {"role": "system", "content": "See tools/session_search_tool.py for details."},
+ {"role": "user", "content": "Hi"},
+ ],
+ )
+ system_text = "\n".join(
+ b["text"] for b in kwargs["system"] if isinstance(b, dict) and b.get("type") == "text"
+ )
+ assert "tools/session_search_tool.py" in system_text
+
+ def test_oauth_tool_choice_named_alias_matches_wire_name(self):
+ """The gap left open by prior alias work: a forced tool_choice must
+ be normalized through the same alias + mcp__ prefix as tools[], or
+ (a) the literal trigger string still reaches the wire and (b) the
+ name no longer matches any entry in tools[]."""
+ kwargs = self._build(
+ [self._tool("session_search")],
+ tool_choice="session_search",
+ )
+ assert kwargs["tool_choice"] == {"type": "tool", "name": "mcp__chat_history_lookup"}
+ assert kwargs["tool_choice"]["name"] in {t["name"] for t in kwargs["tools"]}
+
+ def test_oauth_tool_choice_bare_name_still_gets_mcp_prefix(self):
+ """Non-aliased tool_choice names still need the mcp__ prefix under
+ OAuth (pre-existing GH-25255 invariant, now routed consistently)."""
+ kwargs = self._build(
+ [self._tool("read_file")],
+ tool_choice="read_file",
+ )
+ assert kwargs["tool_choice"] == {"type": "tool", "name": "mcp__read_file"}
+
+ def test_oauth_skips_alias_on_wire_name_collision(self):
+ """If a real (e.g. MCP server) tool already owns the alias's wire
+ name, session_search must keep its own name rather than collide —
+ two identical tool names is a hard 400, strictly worse than #65365."""
+ kwargs = self._build([
+ self._tool("session_search"),
+ self._tool("mcp_chat_history_lookup"),
+ ])
+ names = sorted(t["name"] for t in kwargs["tools"])
+ assert names == ["mcp__chat_history_lookup", "mcp__session_search"]
+
+ def test_api_key_path_never_aliases(self):
+ """The alias is OAuth-only — API-key requests must be byte-identical
+ to before this fix."""
+ kwargs = self._build(
+ [self._tool("session_search", "Use session_search to recall prior chats.")],
+ is_oauth=False,
+ )
+ assert kwargs["tools"][0]["name"] == "session_search"
+ assert "session_search" in kwargs["tools"][0]["description"]
+