Context Engineering for AI Agents: Memory, Tools, and Retrieval

Rajni

Written by

Rajni
Himanshu

Reviewed by

Himanshu

Published 02 December 2026

Expert Verified

<p>context engineering for AI agents, showing memory, tools, and retrieval connected to an AI agent workflow with a developer, laptop, and AI assistant robot.</p>

Summarize this post with AI

Short answer: Context engineering for AI agents means deciding what the model sees at each step. Memory brings back relevant facts from earlier interactions, tools let the agent act or look up live data, and retrieval brings in current information from sources such as policy documents. For a refund request, that might mean loading a previous support note, looking up the order, and retrieving the applicable return policy. Selecting only what the agent needs for its next decision leaves room in the context window for the answer.

TL;DR

  • Start small. Use a short working note, expose only the tools the task needs, and start with a fixed retrieval step.
  • Set rules for memory. Record where each fact came from, who can update it, and when it expires.
  • Debug one failed run. Check what the agent retrieved, what reached the model, and what the tool did. Fix the first failure you can reproduce.
  • Add complexity when tests justify it. Use summaries when long runs lose important details. Consider agent-driven search when a task needs several dependent lookups.

An AI support agent handles the first ten turns of a conversation correctly. Later, it asks for an order number the customer already gave and quotes last year’s return policy.

Inspect the failed run and you might find that search ranked the old policy above the current one, or that a summary dropped the order number. Both failures look like a bad reply to the customer, but they need different fixes. In Anthropic’s guide to context engineering for AI agents, these kinds of decisions come down to what information the model receives at each step.

This blog follows a refund request to show how to trace a wrong answer back to its source, preserve key details in a long conversation, and check eligibility and approval before issuing a refund.


What Is Context Engineering for AI Agents?

AI agent identifies an order, checks refund eligibility, and prepares the next action.

Context engineering is the application logic that assembles the model’s input at each step of a task. It decides which instructions, records, tool results, and earlier decisions the model receives. As the task progresses, the application keeps the details the next step depends on and leaves everything else in the systems that own it.

Take the refund request from the opening. The same conversation needs three different sets of inputs:

StepWhat the model needsWhat the application carries forward
Identify the orderThe customer’s request and the order reference they already providedThe verified order ID after the application checks access
Assess eligibilityThe purchase date, item type, and policy that applies to that purchaseThe eligibility result, its reason, and the policy version used
Prepare the next actionThe eligibility result and the options available to the customerThe proposed action and any approval required before execution

The application assembles those inputs before each model call. It can keep the verified order ID in task state, so summarising the conversation can’t erase it. It can also filter policies by market and effective date before the model sees them. That prevents a relevant-looking but expired policy from becoming the basis for a decision.

The boundary matters when the agent can take action. The model can explain the eligibility result or propose a refund. The application rechecks the order, amount, and required approval before it issues one. That gives you a traceable chain from the information the model saw to the action the system allowed.


How Context Engineering Extends Prompt Design

Prompt engineering shapes the instructions a model follows. Context engineering also determines which instructions, evidence, and tools the application supplies on each call. Both matter when you debug an agent.

Take an instruction like “Use the return policy that applies to this order.” The wording tells the model what to do. The application still needs to find the policy that matches the purchase date and market, then include the relevant passage. If the search returns an expired policy, updating the prompt alone leaves the agent working with the wrong evidence.

What an AI Agent Sees on Each Call

An agent’s input can change from one call to the next. Some instructions apply throughout the task. Other inputs, such as a policy passage or an order lookup result, are useful only for a specific decision. These inputs share a token budget, so leave room for the model’s response.

ComponentWhat to includeWhat can go wrong
System instructionsThe agent’s role, task rules, and limits on what it can doConflicting rules lead to inconsistent decisions.
Tool definitionsNames, descriptions, and parameters for tools relevant to the current stepSimilar tools are easy to confuse, and long schemas take up space.
Retrieved knowledgeRelevant passages from current documents or recordsA search can surface an outdated policy or one that applies to a different market.
MemorySelected facts or notes saved from earlier steps or sessionsAn outdated preference or unverified fact can carry into a new decision.
Message history and tool resultsRecent turns and relevant results from the current taskOld messages and oversized results can bury the details needed for the next step.

LangChain’s guide to context engineering describes four ways to manage these inputs. Write a verified fact to storage so it survives later turns. Select the records or tools needed for the current call. Compress long histories or tool results while preserving key details. Isolate a separate task, such as comparing several policy versions, in its own context and pass back the finding and its source.


Long Context in AI Agents and Its Trade-Offs

An order lookup might return 50 fields, even though the agent only needs the purchase date and item type. If the application includes the full result in every later call, those fields keep taking up space. After several lookups and follow-up questions, the agent may have more information to process and a harder time finding the detail that applies.

Important facts can get buried

Chroma’s Context Rot report tested 18 language models and found that performance could decline as inputs grew, even when the relevant information was still present. Test the same refund request at the start of a conversation and again after several follow-ups. Check that the agent applies the same return window and uses the original purchase date in both cases.

Repeated inputs add to the cost of a task

In its multi-agent research write-up, Anthropic reported that agents used about four times as many tokens as chat interactions, and multi-agent systems used about 15 times as many. The Manus engineering team reported roughly 100 input tokens for every output token in its workflow. Use these figures as examples and measure your own total input tokens per completed task to see what repeated lookups, long histories, and extra model calls cost you.

Stable instructions make caching easier

Where your provider supports prompt caching, it can reuse work from an earlier call when the beginning of the input matches. Keep stable instructions at the front and put changing details, such as the current time or latest order status, later in the input. To reduce clutter as the conversation grows, carry forward the specific facts the next step needs and keep the full records in their original systems.


AI Agent Memory Across Tasks and Sessions

A refund agent needs to remember the verified order reference while it works through a case. If the customer returns next week, the outcome of that case may still matter. Give each piece of information a lifespan and load it when a later decision needs it.

Working memory supports the current task. Use structured task state for values such as a verified order ID or a pending approval. A scratchpad can hold progress notes and open questions. Long-term memory carries selected information across sessions, such as a customer’s stated preferences or the outcome of a previous case. Check current refund eligibility against the order and applicable policy each time.

What to Store in Agent Memory

Memory typeWhat it holdsExample
EpisodicPrevious events, actions, and outcomesA prior refund request was escalated because the original payment method was unavailable.
ProceduralInstructions for carrying out a taskRefunds above a configured amount require approval. Keep this rule in versioned configuration and enforce it in the application.
SemanticFacts about a customer or domainThe customer asked to receive updates in French. Record where that preference came from and let the customer change it.

Scope customer memory to the right account and organisation. A WhatsApp AI agent can load a customer’s language preference or prior case outcome once the application has matched the conversation to the correct record.

Three Ways to Implement Agent Memory

ApproachHow it worksWhen to use itMain trade-off
File-based notesStore plans, decisions, or handoff notes in files the application controls. Anthropic’s memory tool illustrates this approach.A single task or a small set of durable notesFree-form notes can become inconsistent as the agent rewrites them.
Editable memory blocksKeep a small set of editable blocks in the model’s context and move older information to searchable storage, as in Letta’s memory architecture.The same profile or task details matter across many turnsActive blocks take up context on every call where they’re included.
Fact extractionExtract candidate facts from conversations and compare them with existing entries before adding, updating, deleting, or skipping them.Many users have long histories, and each request needs only a few factsExtraction adds processing, and a mistaken update can affect later sessions.

What the Benchmarks Tell You

In its internal agentic search evaluation, Anthropic reported a 39% improvement over baseline when it combined the memory tool with context editing. Context editing alone improved performance by 29%. Claude by Anthropic

The Mem0 paper shows a different trade-off. On its long-conversation benchmark, Mem0 cut p95 latency from about 17.1 seconds to 1.4 seconds. The full-context baseline scored higher on the model-judged answer metric, at 72.9% versus 66.9% for Mem0. Replay the same requests against both approaches and track which facts go missing alongside latency and token use. arxiv.org

Rules for Writing, Loading, and Expiring Memory

  1. Define who can write each field. The agent can draft a case note. Account details should come from verified records, and changes that require customer confirmation should follow that workflow.
  2. Record the source and date. When a customer updates a preference, replace the active value and keep enough history to explain the change.
  3. Expire facts that can change. Recheck details such as delivery status against the source system. Keep more durable information, such as a confirmed language preference, until the customer updates it or your retention rules require removal.

A useful test is to reopen the refund case in a new session after the customer changes their language preference. The agent should use the updated preference, find the earlier case outcome, and check the current order and policy before giving a new answer.


Managing Tool Calls and Context Size

A refund agent might need to look up an order, check eligibility, and request approval. Loading the full support tool catalogue adds descriptions and parameter schemas to the model’s input. It also gives the model more similar actions to choose from. Start with the tools needed for the current step, then measure what changes as you expand the catalogue.

How Tool Calling and MCP Work Together

With function calling, the model returns a structured request with a tool name and arguments. Your application checks the arguments and permissions before deciding if the request can run. MCP gives the application a standard way to discover and call tools exposed by servers. For example, the model can request lookup_order, and the application can route that request to the appropriate MCP server after verifying access.

What a Large Tool Catalogue Costs

In Anthropic’s advanced tool use example, loading more than 50 MCP tool definitions upfront brought total context use to about 77,000 tokens, including the system prompt and conversation history. Loading relevant tools on demand brought it down to about 8,700 tokens. www.anthropic.com

The RAG-MCP preprint reports a separate benchmark where retrieving relevant tool descriptions raised selection accuracy from 13.62% to 43.13% and cut prompt tokens by more than half. On your own workflow, track both measures and check how often the discovery step misses a tool the agent needs

Ways to Reduce Tool Overhead

Four ways to reduce AI agent tool overhead: prune and rename tools, load them on demand, process large results with code, and use a gateway for multiple servers.

Try these four options in order, starting with the cheapest.

  1. Prune and rename overlapping tools. Give each tool one clear job. Names such as lookup_order, check_refund_eligibility, and issue_refund make it easier to tell which tool retrieves data, which applies a rule, and which changes an order.
  2. Load specialised tools on demand. With Anthropic’s tool search, you can mark less-used tools with defer_loading: true so their definitions load when needed. Compare the added search time with the token savings, and test that the agent can still find the right tool for an uncommon request. www.anthropic.com
  3. Filter large results in code. If a tool returns hundreds of records, extract the fields the model needs before passing them into context. In Anthropic’s code execution example, loading only the required tools and processing results in code reduced token use from 150,000 to 2,000. If the agent runs code, enforce permissions and resource limits in the execution environment. www.anthropic.com
  4. Use a gateway for multiple servers. The MCP360 gateway README shows how search and execute can give an agent access to a wider tool catalogue through two entry points. Check which tools each caller can discover and which actions they’re authorised to execute.

Keep Tool Results Small and Traceable

After an order lookup, carry forward the verified order reference, purchase date, and relevant item details. Keep a reference to the original result for review. If the next decision depends on a changing value, such as delivery status, fetch it again from the source.

Use pagination or field selection to limit large results before they reach the model. The MCP tools specification also recommends returning tools in a consistent order when the available set stays the same, which helps clients cache the list. If permissions change during a task, apply the new permissions on the next call


Retrieval Strategies for AI Agents

Retrieval gives the model evidence for its next answer or action. In retrieval-augmented generation (RAG), the application finds relevant passages and includes them in the model’s input. For a refund request, relevance has two parts. The passage needs to explain returns, and the policy needs to apply to the order’s market, purchase date, and item type.

Retrieve Up Front or Load on Demand

ApproachHow it worksWhen to use it
Fixed retrievalThe application runs a search at a defined step and sends the top matching passages to the model.The workflow already knows which source to search, such as a help centre for policy questions.
Just-in-time retrievalThe application or agent starts with a reference, such as a record ID or document path, and fetches the content when a later step needs it.The right source depends on information gathered during the task.

A refund workflow can use both. The order lookup gives you the purchase date and market. Once those fields are available, a fixed search can filter for policies that apply to that order. If the matching policy points to a separate exception for final-sale items, the application can fetch that document only when the item qualifies for the check.

Put the Most Useful Evidence First

Liu and colleagues’ Lost in the Middle study found that the models they tested often performed worse when the relevant information appeared in the middle of a long input. Before adjusting passage order, filter out documents that don’t apply, remove duplicates, and keep source details such as the title, version, and effective date. Then test passage placement on the model and prompt you actually use.

For the refund workflow, a useful test includes two policies with similar wording and different return windows. Check that retrieval surfaces the applicable policy and that the model bases its answer on that version.

Add Agent-Driven Search for Dependent Lookups

Start by checking where a failed search went wrong. If the right policy never appears in the results, try metadata filters or combine keyword and semantic search. If the policy appears but ranks below weaker matches, test reranking. If customers use wording that your index rarely matches, test query rewriting.

As this comparison of agentic RAG and traditional RAG explains, agent-driven search gives the model more control over when to search and what to look up next. That helps when one result determines the next source, such as a return policy that points to an exception the workflow can’t predict in advance. Test the same requests against your fixed pipeline and compare answer accuracy, lookup count, and end-to-end latency before expanding the workflow.


A Refund Workflow From Lookup to Approval

A customer service agent can use a customer’s past support history to pick up a refund request. The order system and the applicable return policy determine what the customer qualifies for. This example shows what the model receives at each step and what the application checks before money moves.

StepWhat the model receivesWhat the application does
Understand the requestThe customer’s message and any relevant past case outcome or language preferenceLoads memory for the verified customer and carries forward the order reference if it’s already known.
Look up the orderThe lookup_order tool and the verified order referenceChecks order access and returns the fields needed for the decision, such as purchase date, market, and item type.
Find the applicable policyThe relevant policy excerpt and the order facts needed to interpret itRetrieves the version that applies to the purchase and keeps its source and version with the case.
Prepare the next actionThe eligibility result, refundable amount, and available next stepsChecks the order against the policy and determines if the request needs approval.
Execute and confirmThe result of the refund action or the status of the approval requestRechecks eligibility, amount, and required approval before issuing the refund. Records the outcome and returns the status.

Trace a Wrong Answer Back to Its Source

Suppose the agent gives a customer 30 days to return an item. The order lookup returned the correct market and purchase date, but the policy search ranked an old 30-day policy above the newer 14-day policy that applies to that purchase. Filter the policy search by market and effective date, then replay the same request. Check which policy version reached the model and which deadline appeared in the reply.

Carry forward the verified order reference, policy version, and decision status as the conversation continues. Keep the full order record in the order system. Expose issue_refund only at the execution step, where the application can enforce current permissions and approvals. The customer should hear that the refund was issued only after the payment system confirms it. the window. Longer tasks need the techniques in the next section.


Managing Context During Long Agent Tasks

A long refund case can span several messages, order lookups, and policy checks. By the time the customer follows up, the agent may need only a few details from those earlier steps. Compaction helps a single agent continue with a shorter history. Sub-agents give independent tasks their own context and return findings to the lead agent.

TechniqueUse it whenMain trade-off
CompactionOne conversation keeps growing, but only some details matter for the next step.A summary can drop an exception, change the meaning of a decision, or lose its source.
Sub-agentsIndependent checks can run in parallel and return findings the lead agent can combine.Each sub-agent adds model calls, and the lead agent must reconcile conflicting results.

Compact History Without Losing Decisions

Anthropic’s guide to context engineering recommends tuning compaction on real traces. Start by checking that the summary preserves essential details, then trim what the next step rarely uses.

Give the summary a structure that matches the task:

  • Open request. What the customer wants and what remains unresolved.
  • Evidence checked. The verified order reference, policy version, and relevant findings.
  • Decisions made. What the agent or application decided and why.
  • Pending work. Outstanding approvals, failed lookups, and the next allowed action.

Keep approval status and other execution-critical fields in structured application state so they survive even if a summary omits them. To test compaction, pause a refund case while approval is pending, compact the history, and resume with “Any update?” The agent should identify the case and explain that approval is still pending.

Give Sub-Agents Independent Work

A lead agent investigating a missing parcel could delegate two read-only checks in parallel. One sub-agent pulls the carrier scan history. Another checks the store’s dispatch records. Ask each to return its finding, source, and any uncertainty so the lead agent can resolve discrepancies or hand the case to support.

In Anthropic’s multi-agent research evaluation, a lead agent with sub-agents outperformed a single agent by 90.2%. That result came from an internal research benchmark. On your own workflow, compare the quality of the final decision, wall-clock latency, and total token use before adopting the pattern.


Security Controls for AI Agent Context

A customer ticket can describe a refund request. A policy page can explain which purchases qualify. Your application decides who can access an order, approve a refund, and move money. Keep that boundary explicit when retrieved content, saved memory, and tool results enter the model’s context.

Prompt Injection in Documents and Tool Results

An agent can encounter instructions inside a web page, support ticket, or tool response. For example, a ticket may claim a manager already approved the refund. Treat that claim as part of the customer’s message and check approval in your own system before acting.

Keep the source attached to each retrieved passage. Validate structured tool results before they enter context, and check permissions again when a tool is called. The controls in this guide to securing MCP servers in production also apply to the servers supplying that data.

Memory Poisoning Across Sessions

OWASP’s Top 10 for Agentic Applications identifies memory and context poisoning as ASI06. The risk lasts beyond the original conversation if the agent saves an unverified claim and loads it into a later session.

Give the agent permission to write specific kinds of information, such as a case summary or a confirmed language preference. Store approvals and account permissions in records your application controls. If you discover a bad memory entry, invalidate it and review the decisions that relied on it.

Changes to Approved Tools

A tool’s description, schema, or behaviour can change after you approve it. Keep a version or fingerprint of the definitions you reviewed and flag unexpected changes before exposing the updated tool to the agent. A definition check detects changes to the metadata you pinned. Tool permissions and runtime monitoring still matter because the server’s behaviour can change without a schema update.

Controls to Enforce in the Application

  • Separate read and write permissions. An order lookup tool should only read order data. For remote tools, use OAuth 2.1 authorisation for MCP to check the caller’s token and granted scopes at the server.
  • Bind approval to the exact action. Record the approved order, refund amount, and currency. If those details change before execution, recheck eligibility and require a fresh approval where policy calls for one. The same pattern applies to spending limits in agentic commerce.
  • Keep credentials out of model inputs and logs. Let the application supply credentials when it calls the service. Record tool names, request IDs, approval references, and outcomes, and redact sensitive values from diagnostic traces.
  • Limit repeated actions. Rate-limit tool calls and make payment writes safe to retry so a timeout can’t cause a duplicate refund.

A useful staging test is to submit a ticket that claims a refund was already approved when the approval record is empty. The agent can acknowledge the request and route it for review. The refund tool should remain unavailable to execute until the application verifies the required approval.


A Practical Starting Point for Context Engineering

Pick one workflow and replay a request that failed. Capture enough detail to follow the path from the customer’s message to the agent’s reply and any tool action. Then fix the first step where the result went wrong.

  1. Record what reached the model. Track token counts by component, retrieved source IDs and versions, loaded tool names, and tool outcomes. Tools covered in this guide to AI agent observability platforms, such as Langfuse and LangSmith, can help you trace those steps. Use redacted samples when you need to inspect the exact input.
  2. Find the first failure. Check four points in order. Did the system find the right information? Did that information reach the model? Did the model use it correctly? Did the application carry out the intended action? A wrong refund deadline could come from stale search results, a passage dropped during context assembly, or an answer that applied the wrong rule.
  3. Change one part and replay the same cases. If search returned the wrong policy, fix the filter or ranking first. If the agent picked the wrong tool, examine overlapping names and descriptions. Compare task completion, latency, and token use before and after the change.
  4. Add complexity when a test shows a need. Add memory when the workflow depends on information from earlier sessions. Add compaction when long runs lose decisions the agent still needs. Use sub-agents when independent work can run in parallel and the results justify the extra calls.
SymptomCheck firstFirst fix to try
The agent forgets an earlier decisionDid the decision survive context assembly or compaction?Store it in structured task state and load it when needed.
The agent calls the wrong toolWere several tools described as handling the same request?Clarify tool descriptions and narrow the set available for that step.
The answer cites an outdated policyWhich policy version reached the model?Filter by effective date and market before ranking passages.
Replies get worse late in a sessionWhich component grows most between calls?Trim old tool output and preserve open decisions in the summary.
Costs climb on routine tasksAre inputs getting larger, or is the agent making more calls?Limit repeated data first, then measure tokens per completed task.
Behaviour changes after reading external contentWhich source entered context just before the change?Review that source and test the application’s permission checks in staging.

Keep the failing request in your test set with a clear pass condition. For the refund example, a pass means the current policy reaches the model, the reply gives the correct deadline, and any refund still goes through the required approval checks.


Frequently Asked Questions

What is context engineering?

Context engineering is the discipline of controlling everything a model reads at each step, from system instructions and tool definitions to retrieved documents, memory entries, and conversation history. In an agent, that control repeats on every pass through the tool-use loop.

How is context engineering different from prompt engineering?

Prompt engineering optimizes the wording of instructions, usually once. Context engineering manages the whole input on every turn, including tool results, memory, and retrieved documents. Prompt wording stays one component of it.

What is the difference between RAG and agentic RAG?

RAG retrieves relevant text in a fixed step before the model answers. Agentic RAG hands that step to an agent that chooses when to search, rewrites queries, and checks results, at the price of more cost, latency, and failure points. Improve hybrid search, reranking, and query rewriting before adding the agent.

How does AI agent memory management work?

AI agent memory management means deciding what the agent stores outside its window, when it loads each entry back, and when entries expire. Begin with file notes, then move to self-editing blocks or an extraction layer when notes stop being enough. Three rules apply throughout. Control who writes, date and source every entry, and expire volatile facts.

What is the difference between LLM tool calling and MCP?

LLM tool calling is the model emitting a structured request that your application runs. MCP is the standard that defines how tools are described and reached, and the model still chooses which tool to call. Both put tool definitions in the window, so keep the set small.


Conclusion

Context engineering for AI agents comes down to selection. Memory should hold only entries you can date, source, and expire. Tools should be the smallest set the agent can choose between correctly, loaded on demand. Retrieval should start fixed and ranked, with agent-driven search added only when logs show questions that need several dependent lookups.

Anthropic expects smarter models to need less prescriptive engineering and expects context to remain a finite resource at any window size. Anthropic’s platform already ships a memory tool and deferred tool loading, and the MCP specification asks servers for stable tool ordering, so the lasting work is policy and measurement. Open the log from your last failed run and write down what filled the window.

Share

Tags

Agentic RAGAI Agent MemoryContext EngineeringLLM Tool CallingModel Context Protocol
Rajni

Article by

Rajni

AI & Tech | Senior Content Writer

Rajni is a senior content writer at Delta4 Infotech covering AI agents, automation, and no-code tools. She writes across the AI space, from chatbots and customer support to MCP and agent workflows, focused on how businesses actually put these tools to work.

Related posts

Best CapCut Alternatives in 2026 (Compared by Use Case)
AI

Best CapCut Alternatives in 2026 (Compared by Use Case)

Quick Answer VN Video Editor and Instagram Edits offer free mobile exports without a watermark. DaVinci Resolve suits advanced desktop editing, while Clipchamp offers free, watermark-free exports up to 1080p. Canva suits teams that reuse branded templates, and Kapwing works well for shared subtitling and dubbing, with a watermark on free exports. CoAnimator suits editable [&hellip;] Share this: Share on X (Opens in new window) X Share on Facebook (Opens in new window) Facebook

HimanshuHimanshu·02 Dec 2026
RAG for Customer Support: Architecture, Examples, and Best Practices
AI

RAG for Customer Support: Architecture, Examples, and Best Practices

Quick Answer Retrieval-augmented generation (RAG) helps a customer support chatbot answer questions using your company’s approved content. First, it indexes sources such as help articles and policies. When a customer asks a question, it retrieves relevant passages and uses them to draft a reply. If the sources don’t support an answer, the chatbot should ask [&hellip;] Share this: Share on X (Opens in new window) X Share on Facebook (Opens in new window) Facebook

RajniRajni·01 Dec 2026
MCP Tool Poisoning: Attack Examples, Detection, and Prevention
AI Tools

MCP Tool Poisoning: Attack Examples, Detection, and Prevention

Quick Answer MCP tool poisoning is a form of indirect prompt injection. A tool’s description or schema contains instructions that can influence an AI agent when the client passes that metadata to the model. The agent may disclose sensitive data or misuse another connected tool without ever calling the poisoned tool. Review raw tool definitions [&hellip;] Share this: Share on X (Opens in new window) X Share on Facebook (Opens in new window) Facebook

HimanshuHimanshu·30 Nov 2026