What Is Context Engineering? A Guide for AI Coding Agents

Raghav Chamadiya9 min read
On this page

Context engineering is the practice of deciding what an AI model or agent sees in its context window at each step: the instructions, tool definitions, retrieved documents or code, conversation history and memory. Where prompt engineering writes one good instruction, context engineering keeps the whole window small and relevant on every turn, because a model can only reason over what is in front of it.

Part of the AI Context & MCP guide. For the codebase side in depth, see giving AI coding agents real codebase context.

New to the agent side of this? Start with what agentic coding is and the loop these techniques plug into.

What is context engineering?

Context engineering treats the context window as a budget and spends it on the fewest tokens that let the model do the task. Anthropic's engineering team defines it as "the set of strategies for curating and maintaining the optimal set of tokens (information) during LLM inference" in Effective context engineering for AI agents (September 29, 2025).

The reason it matters is that more context is not free. Anthropic's post describes context rot: as the number of tokens in the window grows, the model's ability to recall information from it accurately declines. An agent that has read forty files to answer a question about two of them is working with a worse window than one that read the two.

For a chat assistant, context is mostly the conversation. For an agent that runs in a loop, context is rebuilt on every step from many sources at once, and each source competes for the same space. Context engineering is the discipline of deciding, for each step, which of those sources get in.

Context engineering vs prompt engineering

Prompt engineering is writing the instruction; context engineering is managing everything the model sees, including that instruction, across every turn of a task. Anthropic calls context engineering "the natural progression of prompt engineering". A prompt is written once. Context is assembled again each time the agent calls the model.

Prompt engineeringContext engineering
Unit of workOne prompt or system promptThe full context window, per model call
When it happensBefore the task, onceOn every step of an agent loop
Main inputsWording, examples, output formatInstructions, tool schemas, retrieved data, history, memory
Typical failureAmbiguous or underspecified instructionRight instruction, wrong or missing facts in the window
Main techniquesFew-shot examples, role, structureRetrieval, compaction, note-taking, subagents, tool design
Who owns itWhoever writes the promptWhoever builds the agent or its tools

Scroll the table sideways to see every column.

A good prompt still matters. It is one input among several, and in a long agent session it is a small share of the window.

What goes into an agent's context window

An agent's context window holds five kinds of input, and each one has its own cost and its own way of going stale.

  1. Instructions. The system prompt plus instruction files such as CLAUDE.md or AGENTS.md. Loaded at the start and paid for on every call.
  2. Tool definitions. The name, description and JSON schema of every tool the agent can call, including each MCP server's tools. Clients that send every schema with every request pay for them on each turn.
  3. Retrieved data. File contents, search results and tool outputs. Usually the largest and least predictable share.
  4. History. The user's messages, the model's replies and the record of earlier tool calls.
  5. Memory. Notes the agent wrote outside the window, such as a to-do list or a notes file, and pulls back in when it needs them.

Most context engineering work is on the third item. Instructions and tool definitions are fixed per session. Retrieved data is chosen step by step, and that choice is where an agent wastes or saves most of its tokens.

Context engineering for coding agents: the codebase problem

A coding agent's context problem is that a repository is far larger than any window, and grep plus file reads is an expensive way to find the few files that matter. To answer "what breaks if I change this function?", an agent without an index searches for the name, opens each match, follows imports, opens more files and often misses a caller in a module it never searched.

Each of those steps puts raw text in the window. Most of it is irrelevant to the question, and all of it stays there for the rest of the session. This is retrieval done at the worst point: at question time, by the model, one file at a time.

The fix is to move retrieval out of the loop. Build an index of the repository ahead of time (symbols, imports, callers, git history, ownership) and let the agent ask it questions. The agent then reads a short, cited answer and opens only the files it needs to edit. See how to give an agent codebase context without prompt stuffing for the trade-offs between pasting files, long context and tool-based retrieval.

Context engineering techniques

The working techniques fall into five groups: instruction files, retrieval over tools, hooks, compaction and subagents. Anthropic's post covers compaction, structured note-taking, subagents and just-in-time retrieval. Coding agents add instruction files and hooks.

TechniqueWhat it controlsIn Claude CodeIn Codex
Instruction filesStanding rules and project factsCLAUDE.mdAGENTS.md
Retrieval over MCPWhat code and facts enter the windowMCP servers, called as toolsMCP servers in config.toml
HooksContext injected at fixed eventsSessionStart, PostToolUse and others in settings.json.codex/hooks.json
CompactionHow history shrinks near the limitAutomatic, or /compactAutomatic compaction
SubagentsWork done in a separate windowSubagents return a summary to the main agentSubagents

Scroll the table sideways to see every column.

Instruction files

CLAUDE.md and AGENTS.md carry what the agent should know before it starts: how to build and test, conventions, which tools to call first. Keep them short and factual, because they are paid for on every call. The CLAUDE.md and AGENTS.md guide covers what to put in them and what to leave out.

Retrieval over MCP

This is just-in-time retrieval: the agent keeps a question in mind and fetches the answer when it needs it, instead of loading files up front. An MCP server for a codebase turns "find every caller of charge()" into one tool call with a short, structured reply. The tool's description and schema are themselves context, so a small set of well-described tools beats a long list.

Hooks

Hooks inject context at fixed points without the agent asking: a freshness note at session start, a warning when the agent edits a fragile file, graph context after a search. They are deterministic, so they suit facts the agent should always see at that moment. Claude Code hooks covers the events and the config.

Compaction and note-taking

Compaction summarizes a long history and continues from the summary. Note-taking writes state to a file the agent can read back later. Both keep a long task going without carrying every earlier tool result forward.

Subagents

A subagent explores in its own context window and returns only a summary. The main agent's window gets the conclusion, not the forty files the subagent read to reach it.

Harness engineering vs context engineering

Harness engineering is building the controls around a coding agent (instructions, tools, checks, feedback loops), and it is usually described as a specific form of context engineering. Birgitta Böckeler's article Harness engineering for coding agent users (martinfowler.com, April 2, 2026) describes a harness as guides that steer the agent before it acts and sensors that observe its output so it can correct itself, and says that "engineering a user harness for a coding agent is a specific form of context engineering".

A practical split: context engineering asks what the model sees on this call. Harness engineering asks what the system around the model does across calls: which linters and tests run, what blocks a bad edit, what feeds results back. A Stop hook that runs the test suite is harness. The test output it puts in the window is context. For the parts of a harness and how teams build one, see what harness engineering is.

Measuring context engineering

Measure context engineering with two numbers: how many of the right files the agent's context contained, and how many tokens and tool calls it took to get there. Answer quality alone hides waste, because a model can reach the right answer after reading far more than it needed.

We measure repowise this way and publish the method on the benchmarks page:

  • File coverage. On 42 ContextBench instances sealed before any tuning, repowise get_answer found 0.876 of the files each real fix touched, against 0.610 for CodeGraph, the next tool.
  • Work per answer. Across five models, an agent with repowise opened up to 99% fewer files per question and wrote up to 51.2% less output (Sonnet 4.6). On Opus 5.5 it opened 0.38 files per question instead of 2.25, with 48 of 48 answers right.
  • Against other context tools. On 43 django/django questions on Codex, repowise took 3.8 tool calls to reach an answer instead of a bare agent's 7.2.

You can run the same measurement on your own agent setup: log tool calls and files opened per task, with and without a change, on a fixed set of questions with known answers.

How repowise does context engineering for code

repowise indexes a repository once and serves it to agents as ten task-shaped MCP tools, so the agent asks one question and gets a cited answer instead of reading files to find out. The index holds the dependency graph, git history, ownership, code health and recorded architectural decisions.

  • get_answer answers a how, where or why question in one call, with citations and a confidence level.
  • get_context returns a card for files or symbols: summary, signatures, callers, owners and the decisions that govern them.
  • get_risk lists what depends on a file, its co-change partners and its test gaps before an edit.
  • Claude Code hooks add graph context after searches and flag stale reads; Codex hooks flag stale context after a commit or pull. Neither makes an LLM call.

Every response carries the indexed commit and a stale warning when the index falls behind the checkout, so the agent knows how far to trust what it just read. See AI context for the full surface, or open FastAPI's indexed architecture to see what an agent gets on a real repository.

FAQ

What is context in AI coding?
Context is everything the model sees when it generates its next step: the system prompt, instruction files such as CLAUDE.md, tool definitions, the code and tool output it has retrieved, and the conversation so far. In a coding agent most of it is retrieved code and tool results, which is why retrieval quality decides how much of the window is useful.
What is harness engineering vs context engineering?
Context engineering decides what the model sees on each call. Harness engineering builds the controls around the agent across calls, such as instruction files, linters, tests and hooks that check its work. Birgitta Böckeler's article on martinfowler.com describes engineering a harness for a coding agent as a specific form of context engineering.
Is context engineering the new prompt engineering?
It extends it. Anthropic calls context engineering the natural progression of prompt engineering: the prompt is still written with care, but in an agent it is one input among tool definitions, retrieved data, history and memory, all managed on every turn.
What is agentic context engineering?
Agentic context engineering is context engineering applied to agents that run in a loop and choose their own next action. The agent itself fetches context through tools, writes notes, compacts its history and delegates to subagents, so the design work moves to the tools and rules that shape those choices.
How do you do context engineering in Claude Code?
Keep CLAUDE.md short and factual, connect MCP servers that answer questions instead of returning whole files, use hooks to inject facts at fixed events, delegate broad exploration to subagents, and compact long sessions with /compact. For a codebase, an index served over MCP such as repowise replaces most grep-and-read exploration.