Context Engineering for AI Agents: How to Give Agents the Right Data, Tools, and Memory
AI agents do not fail only because the underlying model is weak. They often fail because the model receives the wrong information, cannot find the right tool, forget an important decision, or becomes overloaded with irrelevant context.
That is where context engineering for AI agents comes in.
Context engineering is the practice of giving an AI agent the right data, tools, instructions, and memory at the right moment. It goes beyond prompt engineering. Instead of only asking, “What should the model say?” context engineering asks, “What should the agent know, access, remember, and be able to do at this step?”
This guide explains how context engineering works, how to design agent data and tool systems, how memory supports long-running tasks, and how to build AI agents that remain reliable in production.
What Is Context Engineering for AI Agents?
Context engineering is the process of curating everything an AI model can see and use when it makes a decision. For an AI agent, that includes the system prompt, user request, conversation history, retrieved documents, tool definitions, tool results, permissions, and stored memory.
Anthropic defines context as the set of tokens provided to a large language model during inference. Context engineering is therefore the discipline of selecting and maintaining the most useful tokens so the model produces the desired outcome.
In simple terms, context engineering for AI agents means designing the agent’s working environment.
A well-designed agent does not receive every available file, database record, API response, or chat message. It receives a focused set of high-signal information that helps it complete the current task.
LangChain describes context engineering as providing the right information and tools in the right format so an LLM can accomplish a task. It identifies missing or incorrect context as one of the main reasons agents become unreliable.
Context Engineering vs Prompt Engineering
Prompt engineering and context engineering are related, but they solve different problems.
Prompt engineering focuses on writing effective instructions. It determines the agent’s role, tone, constraints, examples, and output format.
Context engineering focuses on the complete information state available to the model. It determines what data the agent can access, which tools it can use, what it remembers from earlier steps, and how much context it should retain.
Prompt engineering answers the question, “How should the model respond?” Context engineering answers the question, “What should the model know and be able to do right now?”
Prompt engineering is most useful for single-turn tasks. Context engineering becomes essential when an agent must reason across multiple steps, call tools, retrieve company data, or work over long periods.
Anthropic describes context engineering as the natural progression of prompt engineering because modern agents need to manage system instructions, tools, Model Context Protocol integrations, external data, and message history together.
Why AI Agents Need Context Engineering
An AI agent usually works in a loop.
First, the model receives a request and its current context. Next, it decides whether to respond or call a tool. If it calls a tool, the tool executes and returns a result. That result becomes new context for the next model call. The loop continues until the agent completes the task.
This loop creates a context problem.
Every tool result, retrieved document, user message, and intermediate reasoning step can become context for the next decision. If the agent retains everything, its context becomes crowded. If it discards too much, it may lose an important constraint, decision, or fact.
Anthropic calls this challenge context rot. As the number of tokens in the context window increases, a model’s ability to accurately recall information from that context can decline. The company explains that context should be treated as a finite resource with diminishing returns.
The goal is not to give the agent more context. The goal is to give it the smallest set of relevant, accurate, and actionable context.
The Anatomy of an AI Agent’s Context
An effective agent context contains several layers. Each layer answers a different question.
System instructions
System instructions define the agent’s role, boundaries, tone, and operating rules.
For example, a customer support agent may receive instructions such as:
“Help customers resolve billing and account issues. Use only approved knowledge-base articles. Do not provide legal advice. Escalate refund requests above $500 to a human agent.”
Good system instructions are specific enough to guide behavior, but flexible enough to let the model reason through unfamiliar cases. Anthropic recommends avoiding overly rigid if-then rules while also avoiding vague instructions that assume shared knowledge.
User request and conversation history
The user request tells the agent what it needs to do. Conversation history preserves earlier questions, clarifications, decisions, and tool results.
For a short task, recent messages may be enough. For a longer task, the agent needs a way to summarize or compress older context without losing the goal.
Retrieved data
Retrieved data gives the agent facts it does not already know. This can include knowledge-base articles, CRM records, product documentation, policy documents, database records, or search results.
Retrieval augmented generation, commonly called RAG, is often used to find relevant information before the model responds. However, RAG alone is not enough for complex agents. The agent also needs to know when to retrieve, what to retrieve, and how to interpret the result.
Tool definitions and tool results
Tools allow an agent to act. They can search a database, read a file, call an API, update a CRM record, create a ticket, or execute code.
Tool definitions tell the model what tools exist, what inputs they require, and when to use them. Tool results return information that becomes context for the next decision.
Agent memory
Memory allows an agent to preserve useful information beyond a single prompt or conversation. It can store user preferences, project decisions, completed steps, open questions, and learned facts.
Memory is especially important for agents that work across sessions or complete long-running tasks.
How to Give AI Agents the Right Data
The right data is relevant, accurate, current, permission-aware, and formatted for the task.
Agents should not receive raw dumps of company data. They should receive a curated view of the information needed to make the next decision.
Use runtime context
Runtime context includes information that changes based on the user, environment, or request.
Examples include user ID, user role, permissions, locale, timezone, subscription plan, environment, API credentials, and compliance requirements.
A finance agent may need to know whether the user is an administrator or a read-only viewer. A healthcare agent may need to apply different rules based on jurisdiction and regulatory requirements.
LangChain separates runtime context from short-term state and long-term memory. Runtime context includes static configuration such as user identity, API keys, database connections, permissions, and environment settings.
Maintain short-term state
Short-term state, also called working memory or session state, contains information relevant to the current conversation.
This can include the user’s goal, uploaded files, authentication status, selected filters, recent tool results, and intermediate findings.
For example, if a user uploads a contract and asks the agent to identify risky clauses, the agent should retain the uploaded document reference throughout the task. It does not need to retain every page in full context at all times.
Use long-term memory carefully
Long-term memory stores information that remains useful after the conversation ends.
Examples include user preferences, communication style, previous project decisions, recurring workflows, product requirements, and approved business rules.
A coding agent may remember that a team uses TypeScript, prefers certain testing patterns, and requires security review before deployment. A sales agent may remember that a customer prefers concise email updates and works in the EMEA region.
LangChain refers to long-term memory as a store that can contain user preferences, extracted insights, memories, and historical data across conversations.
Use RAG for relevant knowledge
RAG helps an agent retrieve relevant information from a larger knowledge base. Instead of placing every document into the context window, the agent searches for the most relevant chunks and adds only those to context.
For example, a support agent asked about a refund policy should retrieve the current refund policy, not every policy document the company owns.
A strong RAG system uses clean source data, useful metadata, effective chunking, and a retrieval strategy suited to the content. Salesforce recommends accurate and relevant structured and unstructured data, along with hybrid or vector search, content parsing, index optimization, and a well-tuned chunking strategy.
Prevent contradictory context
Contradictions are one of the most damaging context problems.
If the system prompt says refunds require manager approval, but a retrieved policy says refunds are automatic, the agent may choose the wrong action. If one tool returns an old customer record and another returns a newer record, the agent may produce an inconsistent answer.
Resolve conflicts before they reach the model. Establish a source of truth, assign priority to authoritative sources, timestamp data, and remove duplicate or outdated content.
How to Design Tools for AI Agents
Tools are how an agent interacts with the world. They let it retrieve live data, take action, and complete tasks that a language model cannot do through text generation alone.
Anthropic defines agents as LLMs that autonomously use tools in a loop. It also emphasizes that tool definitions and specifications deserve as much attention as prompts.
Give every tool a clear purpose
Each tool should have one obvious job.
Instead of creating a broad tool called get_data, create focused tools such as search_customer_orders, get_invoice_details, update_ticket_status, and search_knowledge_base.
Clear tool names reduce ambiguity. They help the model understand when to use a tool and what result to expect.
Write useful tool descriptions
A tool description should explain what the tool does, when to use it, what inputs it needs, and what it returns.
For example, a tool named search_orders could find a customer’s orders by status. It could accept a customer ID, order status, and result limit. The agent should use it when a user asks about order history, delivery status, or order details. It should not use it for refunds, account changes, or payment updates.
LangChain notes that tool names, descriptions, argument names, and argument descriptions guide the model’s reasoning about when and how to use a tool.
Keep the tool set small
Too many tools can overwhelm the model. If several tools appear to solve the same problem, the agent may choose the wrong one or waste steps exploring options.
Start with the minimum viable set of tools. Add new tools only when a real task requires them.
Anthropic warns that bloated tool sets can create ambiguity about which tool to use. If a human engineer cannot easily determine the correct tool, an AI agent is unlikely to do better.
Return compact results
Tool outputs should be token efficient.
A database query should not return an entire customer table. It should return only the relevant fields, a limited number of records, and a clear structure.
For example, instead of returning 500 rows of raw order data, return:
“Found 12 pending orders for customer 4821. The three most recent are order 9931, order 9874, and order 9802.”
This preserves the information the agent needs while conserving context.
Control permissions dynamically
Not every user should have access to every tool.
A viewer may have access only to read tools. An editor may be able to update records but not delete them. An administrator may have broader access, subject to audit logging and approval rules.
Dynamic tool selection lets the agent see only the tools appropriate for its current permissions, authentication state, and conversation stage. LangChain provides examples of filtering tools based on state, user preferences, feature flags, and runtime permissions.
AI Agent Memory: Short Term and Long Term
Memory is one of the most important parts of context engineering for AI agents.
Without memory, an agent must rediscover the same facts in every step. With poorly designed memory, it may retain irrelevant information, contradict itself, or expose sensitive data.
Working memory
Working memory is the information available during a single model call.
It includes the current prompt, recent messages, active tool results, and retrieved documents. It disappears or changes when the next model call begins.
Short-term memory
Short-term memory lasts for the current conversation or task.
It helps the agent remember the user’s goal, uploaded files, selected filters, authentication state, and intermediate findings.
For example, if a user asks an agent to analyze a sales report and then asks, “What were the biggest risks?” the agent should remember which report it analyzed.
Long-term memory
Long-term memory persists across conversations and sessions.
It allows an agent to remember durable facts, such as a user’s preferred communication style, a project’s technical constraints, or a customer’s historical preferences.
Claude’s memory tool, for example, lets an agent create, read, update, and delete memory files that persist between sessions. It supports just-in-time context retrieval, meaning the agent records what it learns and reads it back only when needed.
Use structured notes
The best agent memory is structured, concise, and purposeful.
Instead of storing every message or tool result, the agent should write notes such as:
“Customer requested a refund for order 8842. Policy requires manager approval above $500. Order total is $740. Next step: request approval and notify customer.”
This note preserves the decision, constraint, and next action without retaining the entire conversation.
Anthropic describes structured note-taking as a memory technique where an agent writes notes to persistent external storage and retrieves them later. This allows the agent to track progress across complex tasks without keeping everything in active context.
Managing Long-Running AI Agents
Long-running tasks create a special context problem. An agent may need to work for minutes or hours, call dozens of tools, and process more information than fits in a context window.
Larger context windows help, but they do not remove the need for context engineering. More context can still introduce noise, cost, latency, and reduced focus.
Use context compaction
Compaction summarizes older conversation history and restarts the agent with a condensed version of the context.
The summary should preserve the task goal, key decisions, unresolved issues, important constraints, and essential facts. It can discard redundant tool outputs and low-value messages.
Anthropic describes compaction as summarizing a conversation nearing the context limit and reinitiating a new context window with that summary.
Clear old tool results
Many tool results are useful only for a short time.
Once an agent has extracted the needed fact from a search result or database response, it may not need the full raw output later. Tool-result clearing removes old, re-fetchable outputs while preserving the fact that the tool was called.
Claude’s context engineering documentation identifies compaction, tool-result clearing, and memory as three key techniques for managing agent context.
Use just-in-time retrieval
Just-in-time retrieval means the agent stores lightweight references instead of loading all information upfront.
For example, instead of placing an entire 300-page policy manual into context, the agent stores the file path or search query. When it needs a specific section, it retrieves only that section.
Anthropic notes that agents can maintain identifiers such as file paths, stored queries, and web links, then use tools to load relevant data at runtime.
Use sub-agents for complex work
A sub-agent is a specialized agent that handles one focused part of a larger task.
A research agent may delegate competitor analysis, technical research, and source verification to separate sub-agents. Each sub-agent can use a clean context window and return only a concise summary to the main agent.
This separates detailed exploration from high-level decision-making. Anthropic notes that sub-agents can explore extensively while returning condensed summaries, often around 1,000 to 2,000 tokens.
Example: Context Engineering for a Customer Support Agent
Consider a customer support agent that helps users resolve billing issues.
The agent should not receive every customer record, every support ticket, and every internal policy document at once.
Instead, it should receive the user’s identity and permission level, the current request, relevant CRM fields, the customer’s recent ticket history, approved knowledge-base articles, available support tools, and a memory note about prior interactions.
When the customer asks about a refund, the agent can retrieve the current refund policy, check the order status, verify eligibility, and determine whether approval is required.
If the request requires a refund above the approval threshold, the agent should create an approval task rather than attempting an unauthorized action.
This is context engineering in practice. The agent receives the right data, has the right tools, and retains the right memory.
Context Engineering Best Practices
The most effective context engineering systems start simple and improve through testing.
Begin with a clear system prompt, a small tool set, and a limited data source. Add retrieval, memory, dynamic tool selection, and compaction only when the task requires them.
LangChain recommends starting simple, testing incrementally, monitoring performance, and documenting the context strategy. It also distinguishes transient model context from persistent state changes.
Start with a minimal context set and add information only when it improves task performance. Use structured data because JSON, schemas, and typed fields are easier for agents to interpret than unstructured text.
Retrieve just enough information by using filters, metadata, summaries, and source citations. Design tools for clarity so each tool has a clear purpose, explicit inputs, and predictable outputs.
Separate read and write permissions to prevent agents from taking destructive actions without authorization. Persist decisions rather than raw data by storing concise notes about goals, constraints, and next steps.
Summarize before truncating so important decisions and unresolved issues remain available when context becomes long. Evaluate continuously by tracking task completion, tool selection, retrieval quality, cost, latency, and failure patterns.
How to Measure Context Engineering
Context engineering should be measured by outcomes, not by how much information the agent receives.
Track task completion rate, tool-selection accuracy, retrieval precision, retrieval recall, hallucination rate, token usage, latency, cost per task, and context overflow frequency.
Also measure memory quality. An agent that remembers incorrect or outdated facts can become less reliable over time.
For production systems, log every model call, tool call, retrieved source, memory update, and final output. This makes it possible to identify whether a failure came from a weak model, poor retrieval, a bad tool definition, or a context-management issue.
Frequently Asked Questions
What is context engineering for AI agents?
Context engineering for AI agents is the practice of giving an agent the right instructions, data, tools, conversation history, and memory at each step. It helps the agent complete tasks reliably without overloading the model with irrelevant information.
How is context engineering different from prompt engineering?
Prompt engineering focuses on writing effective instructions. Context engineering manages the entire information environment, including retrieved data, tool results, permissions, memory, and conversation history.
What is agent memory?
Agent memory is a system that lets an AI agent retain useful information across steps or sessions. It can include short-term conversation state and long-term stored knowledge.
How does RAG help AI agents?
RAG helps an agent retrieve relevant information from a knowledge base before responding. It reduces the need to place every document into the context window.
What is the context window in an AI agent?
The context window is the amount of text and other tokens a model can consider during a single inference call. It includes prompts, conversation history, retrieved content, and tool results.
What is MCP in AI agents?
The Model Context Protocol, or MCP, is a standard way for AI models and agents to discover, connect to, and exchange data with external tools and services.
Final Thoughts
Context engineering for AI agents is the difference between a demo that works occasionally and an agent that performs reliably in production.
A strong agent needs more than a good prompt. It needs the right data, clearly defined tools, secure permissions, useful memory, and a strategy for managing context over time.
The best context engineering approach is simple: give the agent the smallest set of high-signal information needed to make the next correct decision.