Context engineering is the work of deciding what an agent sees on every model call. Anthropic defines it as “the set of strategies for curating and maintaining the optimal set of tokens (information) during LLM inference” in its engineering guide. Memory is the part of that job that has to survive between calls and sessions. Both matter for three reasons: context windows are finite, accuracy drops as inputs grow, and an agent pays again for every token it resends.
This hub explains where an agent’s context goes, the techniques that keep it small and relevant, how to design memory that helps rather than misleads, and where FindPicked’s detailed guides fit. The Python example below was run on 17 November 2026; the other claims link to their primary sources.
Why more context is not better
Large context windows invite a simple strategy: put everything in. Three findings argue against it.
- Accuracy drops with length. Chroma’s Context Rot report tested 18 models and found that “model performance varies significantly as input length changes, even on simple tasks.” It also found that “even a single distractor reduces performance” compared with a clean baseline.
- Position matters. Lost in the Middle (Liu et al.) found that models use information best when it sits at the start or end of a long input, and noticeably worse when it sits in the middle.
- Attention is a budget. Anthropic describes an “attention budget” that every added token draws on, and uses “context rot” for the decline in recall as the window fills.
Cost grows with context too. An agent loop sends the growing conversation on every turn, so a long session pays for its early turns many times over. In the run-budget example in our production guide, 18 turns of a growing conversation consumed 675,000 input tokens but only 9,000 output tokens.
What fills an agent’s context window
| Component | How it grows | First control |
|---|---|---|
| System prompt and standing instructions | Rules added after each incident | Keep them at the “right altitude”: clear principles, not every edge case |
| Project memory files such as CLAUDE.md or AGENTS.md | Teams keep appending | Claude Code’s memory docs suggest under 200 lines per file; imports organize content but do not reduce its cost |
| Tool definitions | Every connected server adds tools | Fewer servers; tool search that loads definitions only when needed |
| Tool results | Logs, query results and web pages | Pagination, filtering and truncation; save large output to a file and return a pointer |
| Retrieved documents | Generous retrieval settings | Retrieve less, rank better, and load full documents only when cited |
| Conversation history | Every turn | Compaction and clearing of old tool results |
| Memory notes | Agents write freely | Size caps, expiry and review |
Anthropic’s guide names “bloated tool sets that cover too much functionality” as one of the most common failures it sees, and recommends “a minimal viable set of tools.” Its guide to writing tools adds that Claude Code restricts tool responses to 25,000 tokens by default. For MCP tools, Claude Code warns above 10,000 tokens and saves text results longer than 50,000 characters to a file.
Five techniques that keep context useful
1. Load just in time. Instead of pasting whole files, keep lightweight identifiers such as file paths, stored queries and links, and load the content when it is needed. Anthropic describes Claude Code’s hybrid approach: CLAUDE.md files go into context up front, while tools like glob, grep, head and tail let the agent find and read only what it needs.
2. Compact and clear. Compaction summarizes a conversation that is nearing the limit and continues from the summary. Claude Code keeps the summary plus recently accessed files. A lighter form is clearing old tool calls and results that have served their purpose. On the Claude API, context editing (in beta) clears old tool results past a threshold, and Anthropic’s docs call server-side compaction the primary strategy for long-running conversations.
3. Take structured notes. An agent that writes progress to a file, such as a NOTES.md or a to-do list, can recover after compaction or a new session. Anthropic’s memory tool formalizes this as a /memories directory that your application stores. The docs suggest pairing it with compaction: compaction keeps the active context small, and memory preserves what must survive summarization.
4. Isolate work in sub-agents. A sub-agent explores in its own context window and returns a short summary, which Anthropic says is “often 1,000-2,000 tokens.” Claude Code’s subagents each run with their own context, prompt and tool permissions. The trade-off is cost: in the data behind Anthropic’s multi-agent research system, multi-agent systems used about 15 times as many tokens as chats.
5. Lay out the prompt for caching. Providers cache an exact prefix. Anthropic’s prompt caching covers tools, system prompt and messages in that order; a change at one level invalidates that level and everything after it, and changing tool definitions invalidates the whole cache. At the time of writing, cache reads cost 0.1 times the base input price on most Claude models, or less on some newer ones. OpenAI’s prompt caching is on by default for supported models, starts at 1,024 tokens on GPT-5.6 and later, and requires the entire rendered prefix to match. Put stable content first and anything that changes per request last. The MCP 2026-07-28 specification now asks servers to list tools in a deterministic order for this reason.
Use the symptom to pick a technique:
| Symptom | Likely cause | Try first |
|---|---|---|
| Agent forgets early instructions in long sessions | History crowds out instructions | Compaction plus pinned notes |
| Context is half full before work starts | Too many tools or long memory files | Tool search, fewer servers, shorter instruction files |
| One tool call floods the window | Unbounded tool output | Pagination, truncation, or a file pointer |
| Costs are high but quality is fine | Uncached repeated prefix | Stable prefix order and caching |
| Exploration clutters the main thread | Broad searches in the main context | A sub-agent that returns a summary |
| Work is repeated across sessions | No durable progress record | A progress log the agent reads first |
A tested example: clip tool output and fit history
This short Python module shows two of the techniques. clip_tool_result keeps a large tool result out of the context and leaves a pointer to the full output. fit_history always keeps instructions and notes, then adds the newest turns that fit a budget. The token estimate is a rough planning heuristic of about four characters per token, so use your provider’s token counting for real limits.
from pathlib import Path
def rough_tokens(text: str) -> int:
# Planning heuristic only: roughly 4 characters per token for English prose.
return max(1, len(text) // 4)
def clip_tool_result(text: str, max_chars: int, store: Path, name: str) -> str:
"""Keep a large tool result out of the context window and leave a pointer."""
if len(text) <= max_chars:
return text
store.mkdir(parents=True, exist_ok=True)
path = store / f"{name}.txt"
path.write_text(text)
return (text[:max_chars] + f"\n[truncated: {len(text):,} chars in total; "
f"full output saved to {path}; read it in ranges if needed]")
def fit_history(system: str, notes: str, turns: list[str], budget: int) -> list[str]:
"""Always keep instructions and notes, then the newest turns that still fit."""
kept, used = [], rough_tokens(system) + rough_tokens(notes)
for turn in reversed(turns):
cost = rough_tokens(turn)
if used + cost > budget:
break
kept.append(turn)
used += cost
dropped = len(turns) - len(kept)
marker = [f"[{dropped} earlier turns removed; their summary is in the notes]"] if dropped else []
return [system, notes, *marker, *reversed(kept)]
With 40 synthetic turns of about 600 characters, plus a 330,000-character log appended as the latest turn, and a budget of 6,000 estimated tokens, it printed:
tool result chars: 330000 -> 2112
turns kept: 34 of 40
[6 earlier turns removed; their summary is in the notes]
estimated tokens: 5915
In a real agent, a model call would summarize the dropped turns into the notes before they are removed. Without that step, trimming is just forgetting.
Design memory that helps
Claude Code’s documentation separates two kinds of memory that apply to most agents: instructions people write, such as CLAUDE.md files, and learnings the agent writes itself. Add a third, task state: a progress log and checklist the agent reads at the start of each session. Anthropic’s memory tool docs describe this multi-session pattern: an initial session sets up a progress log and feature checklist, and every later session reads them first and updates them before it ends.
Decide what belongs in memory:
- Store decisions and their reasons, project conventions, verified facts with their source, and open tasks.
- Do not store secrets, personal data you have no reason to keep, unverified guesses, or raw transcripts that the agent could find again.
Treat memory as an attack surface. The OWASP Top 10 for Agentic Applications lists Memory & Context Poisoning as a top risk, because a planted note keeps influencing every later session. Review memory files like code. Claude Code, for example, asks for approval the first time a project’s memory file imports files from outside the project. The memory tool docs also ask you to validate every path against traversal, strip sensitive data before writing, cap file sizes and expire old files.
Memory is context, not control. Claude Code’s docs state that CLAUDE.md content is treated as context, “not enforced configuration.” Rules that must hold belong in permissions, hooks or a sandbox; the AI agent security guide covers those.
Measure context health
Track a few numbers per model call: input tokens, output tokens, cache reads and writes, tool result sizes, and how often compaction runs. On the Claude API, total input equals cache reads plus cache writes plus uncached input, as the rate limits documentation explains, so do not read input_tokens alone as the whole prompt. For planning, the LLM token and cost estimator gives a rough character-based estimate, and the estimate-prompt-size guide explains how to confirm actual usage with your provider. Judge every context change by task success first and token savings second.
Common mistakes
- Loading everything because the window is large. Long inputs reduce reliability, even on simple tasks.
- Letting instruction files grow without limit. Each line is paid for on every call and lowers adherence.
- Connecting every available MCP server. Tool definitions can fill the window before the task starts; see the MCP guide.
- Passing raw tool output straight to the model. Paginate, filter or save to a file and return a pointer.
- Compacting without notes. A summary that drops a decision means the agent will make it again, maybe differently.
- Treating memory as trusted. Anything an agent writes can be wrong or planted.
- Breaking the cache with small edits. A timestamp at the top of the system prompt changes the prefix on every call.
Related guides
For how token use turns into cost, see Running AI Agents in Production. For a rough count of the tokens in a prompt, try the approximate token counter.
Frequently Asked Questions
What is the difference between context engineering and prompt engineering?
Prompt engineering is writing good instructions. Context engineering decides everything the model sees on each call, including tool definitions, retrieved documents, history, tool results and memory, and keeps adjusting it as an agent works through many turns.
Do larger context windows make context engineering unnecessary?
No. Research such as Chroma’s Context Rot report found that performance varies significantly as input length changes, even on simple tasks. Every token also costs money and latency on every call, so a smaller, relevant context usually works better than a full one.
What should an AI agent store in long-term memory?
Store decisions with their reasons, project conventions, verified facts with sources and open tasks. Avoid secrets, personal data you do not need, unverified guesses and raw transcripts. Review memory like code, because a wrong or planted note affects every later session.
How do I stop tool output from filling the context window?
Design tools to paginate, filter or truncate by default, and return only the fields the agent needs. For large results, save the full output to a file and give the agent a short excerpt plus a pointer it can read in ranges.