[FEATURE] Expose context_management / clear_tool_uses_20250919 config for long-running agent sessions
Preflight Checklist
- [x] I have searched existing requests and this feature hasn't been requested yet
- [x] This is a single feature request (not multiple features)
Note: #26215 covers similar ground but was closed as not planned without an Anthropic response. Re-filing with concrete production impact data, a reproducible patch approach, and a narrower scope.
---
Problem Statement
The Anthropic Messages API beta context-management-2025-06-27 exposes two server-side context-editing strategies:
clear_thinking_20251015— controls thinking-block retentionclear_tool_uses_20250919— clears stale tool use/result pairs once input tokens cross a configurable threshold
Claude Code (and by extension the Claude Agent SDK, which spawns Claude Code as a subprocess) only ever wires up clear_thinking_20251015 in its internal context-management builder. clear_tool_uses_20250919 is never emitted, regardless of which betas are enabled, what env vars are set, or what's in settings.json. There is no user-facing knob to turn it on.
For long-running agentic workloads — the exact use case Claude Code and the Agent SDK are designed for — this is the difference between sessions that complete and sessions that hit the 200K context window mid-task. We're running production agent sessions of 70+ turns where each turn does multiple Read/Grep/Glob/Bash calls. Without clear_tool_uses, every stale file read stays in context forever, the cache invalidates repeatedly, and we either burn 3–5× more input tokens than necessary or fail outright before the task completes.
Server-side compaction is not a substitute. Compaction is lossy and wholesale; clear_tool_uses_20250919 is selective and preserves recent conversation. They solve different problems, and we need the latter.
The gap is particularly painful because:
- The API supports it today
- Claude Code already speaks the
context_managementpayload internally (see #21612, where Claude Code sendscontext_managementand the API rejects it with400: Extra inputs are not permitted— implying partial internal use) - Direct Messages API users can configure it freely
- Only Claude Code / Agent SDK consumers are locked out
---
Proposed Solution
Add a contextManagement key to settings.json (and/or a CLI flag and env var) that Claude Code reads and passes through to the Messages API context_management parameter when the context-management-2025-06-27 beta is active.
Example settings.json:
{
"contextManagement": {
"edits": [
{ "type": "clear_thinking_20251015", "keep": "all" },
{
"type": "clear_tool_uses_20250919",
"trigger": { "type": "input_tokens", "value": 50000 },
"keep": { "type": "tool_uses", "value": 2 },
"clear_at_least": { "type": "input_tokens", "value": 35000 },
"clear_tool_inputs": true
}
]
}
}
Equivalent CLI flag:
claude --context-management '{"edits":[…]}'
Equivalent env var (most useful for SDK consumers spawning Claude Code as a subprocess):
CLAUDE_CONTEXT_MANAGEMENT='{"edits":[…]}'
Implementation should be a near-passthrough: parse the JSON, validate it loosely against the documented edit types, and merge it into the outgoing Messages API request. Since Claude Code already constructs context_management payloads internally for clear_thinking, the plumbing is mostly there — this request is to expose the same mechanism to users and stop hard-coding the edit list.
Ideally this also flows through the Claude Agent SDK as a first-class option (ClaudeAgentOptions.contextManagement) so SDK consumers don't need to set env vars on the spawned subprocess.
---
Alternative Solutions
We are currently running a post-install patch script that injects clear_tool_uses_20250919 into the minified cli.js builder by regex-matching the clear_thinking_20251015-only function and rewriting it. The script handles three different builder shapes we've seen across SDK versions 0.1.x → 0.2.92 (our current production version) and is gated by an idempotency marker.
Why this is not a real solution:
- It's load-bearing duct tape on minified JavaScript. Every Claude Code / Agent SDK release risks the regex falling through to
NO_MATCHand silently disabling clearing — meaning we don't notice until production sessions start blowing context budgets again. - It can't be recommended to other teams in good conscience.
- It creates an upgrade tax: every release needs a manual diff of the builder before we can take it.
- It's brittle in exactly the way "patch a vendor's minified bundle" always is.
Other alternatives considered:
- Bypass the Agent SDK and call the Messages API directly. Works, but loses the entire agent loop, built-in tools, and permission system that we use the SDK for. Throws the baby out with the bathwater.
- Aggressive use of
/clearand session resets. Lossy and disruptive to the agent's task state. - Wait for server-side compaction. Compaction is wholesale and kicks in too late for our workload — we want selective, threshold-based pruning, which is exactly what
clear_tool_uses_20250919provides. - Use a smaller model. Doesn't solve the problem; it just pushes the failure mode out by a few turns.
---
Priority
High — actively blocking production reliability and inflating costs measurably (estimated 3–5× input-token spend on affected sessions vs. raw API calls with proper context management).
---
Use Case Example
We operate an AI-powered application generation platform built on the Claude Agent SDK. A typical user session looks like this:
- User submits a natural-language prompt describing an application concept.
- The agent spawns a Claude Code subprocess with extended thinking enabled.
- Over 70+ turns, the agent reads ~30 source files, runs ~20 Grep/Glob calls to locate patterns, executes ~15 Bash commands to install deps and run builds, and makes ~25 Edit/Write calls to scaffold and iterate the project.
- By turn ~40, accumulated tool results exceed 100K tokens. By turn ~55, we hit 180K+ and either trigger lossy compaction (which degrades task quality) or fail outright.
What we want to happen instead:
- At turn ~30, when input tokens cross 50K, the API server-side clears tool results from turns 1–25 except the most recent 2 tool_use pairs.
- The agent continues with a leaner context, preserving recent conversation and current task state.
- The session completes 70+ turns without hitting the context wall, without lossy compaction, and with the recent conversation intact.
This is exactly what clear_tool_uses_20250919 is designed for. We just can't reach it through Claude Code or the Agent SDK.
Concrete numbers from production traffic on a representative session:
| Metric | Without clearing | With clearing (patched) |
|--------|-----------------|------------------------|
| Cumulative input tokens | ~480K | ~140K |
| Compaction triggered | Yes, at turn 52 | No |
| Task completion quality | Noticeably degraded post-compaction | Clean completion at turn 71 |
| Input token cost ratio | 3.4× higher | Baseline |
The cost delta is ~3.4× on input tokens, plus the avoided cost of degraded task outputs requiring user retries.
---
Additional Context
Related issues
- #26215 — earlier feature request for the same capability, closed as not planned/stale with no Anthropic response on the thread. Refiling with production impact data and a working (if fragile) reference implementation.
- #21612 — bug where Claude Code internally sends
context_managementand the API rejects it with400: Extra inputs are not permitted. Suggests Claude Code already constructs this payload in some code paths, which would make exposing it to users a small change rather than a from-scratch implementation. - #14450 — older "context management" request, but actually about workspace/conversation switching. Different problem; mentioning to disambiguate.
API documentation
- Context editing — documents both
clear_thinking_20251015andclear_tool_uses_20250919, including the exactcontext_management.edits[*]shape this issue is asking Claude Code to accept as pass-through config.
Reference implementation
Our patch script targets the internal context-management builder function across three code shapes seen in SDK versions 0.1.x, 0.2.x (early), and 0.2.84+ (confirmed working through 0.2.92, our current production version). It locates the function that constructs the context_management.edits array (which currently only pushes a clear_thinking_20251015 entry), and appends a clear_tool_uses_20250919 entry with configurable trigger/keep/clear_at_least thresholds. Anthropic engineers familiar with the builder internals will recognize the pattern immediately. Happy to share details if useful.
Why this is filed against claude-code rather than the SDK
The Agent SDK's TypeScript surface is a thin wrapper; the actual API call is made by the bundled Claude Code CLI binary. Exposing contextManagement as an SDK option without corresponding support in Claude Code itself wouldn't work. So the fix needs to land here first, with the SDK then exposing it as a typed option that flows through to the subprocess.
SDK version tested
Production: @anthropic-ai/claude-agent-sdk@0.2.92 — the builder uses the 3-param shape (hasThinking, isRedactThinkingActive, clearAllThinking) that only pushes clear_thinking_20251015. All production data points in this issue were collected against this version.
Technical considerations
- The change should be opt-in (default behavior unchanged) to avoid surprising existing users
- Validation can be loose — Claude Code can pass the JSON through and let the API return descriptive errors for malformed edits
- The beta header
context-management-2025-06-27is already supported viaANTHROPIC_BETAS, so no new beta plumbing is needed - Settings precedence should match other
settings.jsonkeys: env var > CLI flag > project settings > user settings
This issue has 5 comments on GitHub. Read the full discussion on GitHub ↗