Memory, tools, evals
Module 04 · est. 45 min · You’ll build: a memory file your agent reads and writes, a tool layer that fails safe instead of breaking, and a tiny eval harness that tells you when your agent is wrong — before your customers do.
TL;DR: Three things turn a clever script into an agent you trust. Memory: a place to store what it learned so it doesn’t repeat itself or forget context across runs (for most agents this is a file or a row in a table — not a vector database). Tools: the agent’s hands, built to fail safe and validate their inputs, plus the ones you no longer have to write (MCP servers and Anthropic’s hosted web search, web fetch and code execution). Evals: a way to know when the agent is wrong, run automatically, so you find out before reality does. Skip evals and you’re flying blind; most “agent failures” turn out to be “I had no way to tell it was failing.”
[Operator’s read] I learned all three the expensive way. My early agents forgot everything between runs and re-did work. My tools threw raw errors that the model “helpfully” hallucinated around. And I had no evals, so I found out my review-reply agent was off-tone from a customer, not a test. Don’t repeat my tuition payments.
Memory: a brain that doesn’t forget
An agent without memory is Groundhog Day. It wakes up, does its job, forgets everything, and wakes up blank tomorrow. For some agents that’s fine (a pure summarizer doesn’t need to remember). For most, it’s the difference between useful and maddening.
First, kill the vector-database reflex. The internet will tell you “agent memory = embeddings + a vector DB.” For 90% of business agents, that’s wildly overbuilt. Vector search is for “find the semantically-similar needle in 100,000 documents.” You probably have memory needs like “what did I already reply to” and “what’s this customer’s history” — and those are a key-value lookup, not a similarity search. Reach for the simplest thing that works:
The memory ladder, cheapest first:
- A checkpoint — one value: “last item I processed.” (The polling marker from Module 03.) Solves 40% of memory needs alone.
- A JSON file or markdown file — append what the agent learns, read it at the start of the next run. Lives in the repo or in object storage. This is most of my memory.
- A row in a table (Airtable, a database, Cloudflare KV/D1) — when memory is structured and you query it: “this customer, this status, last touched when.”
- A vector store — only when you genuinely need semantic search over a large corpus. If you can’t articulate why a JSON file fails, you don’t need this yet.
Two hosted versions of rung 2 exist now. Anthropic’s memory tool (memory_20250818) gives the model a standard set of file commands over a /memories folder; you implement where those files live, and the model already knows how to use them. On Managed Agents, a memory store is mounted into the agent’s sandbox as a folder that survives across sessions, with every change versioned so you can roll one back. Both are files underneath. Never let either hold an API key: whatever goes into memory gets replayed into every future run.
Memory as a file the agent reads and writes:
// memory.ts — dead simple, survives restarts, debuggable by eyeball
import { readFileSync, writeFileSync, existsSync } from 'fs';
const MEM = './memory.json';
export function loadMemory(): Record<string, any> {
return existsSync(MEM) ? JSON.parse(readFileSync(MEM, 'utf-8')) : {};
}
export function remember(key: string, value: any) {
const mem = loadMemory();
mem[key] = value;
writeFileSync(MEM, JSON.stringify(mem, null, 2)); // pretty-printed so YOU can read it
}Then you give the agent memory as context at the top of its run, and a tool to write to it:
// In run.ts, inject memory into the first message:
const memory = loadMemory();
const messages = [{
role: 'user',
content: `Here is what you remember from past runs:\n${JSON.stringify(memory, null, 2)}\n\nNow run your job.`,
}];
// And expose a 'remember' tool so the agent can write back:
{
name: 'remember',
description: 'Store a fact for future runs. Use for things you should not repeat or forget.',
strict: true,
input_schema: {
type: 'object',
properties: { key: { type: 'string' }, value: { type: 'string' } },
required: ['key', 'value'],
additionalProperties: false,
},
}The pro move: prune memory. Memory that only grows becomes a token bomb (cost + the model drowning in irrelevant history). Decide what’s worth keeping. My social-reply agent remembers the last review/comment ID it handled (so it never double-replies) but forgets the replies themselves — it doesn’t need them. A good memory file is short and high-signal.
Memory inside one long run. Everything above is memory between runs. A long run has the opposite problem: the conversation itself gets huge, because every tool result stays in it. Two API features handle that. Context editing clears old tool results out of the conversation once they’ve been used. Compaction has the API summarize the earlier part of the conversation when it approaches a size you set, and carry on from the summary. Both are beta. Your digest agent finishes in three turns and needs neither. An agent that reads 80 web pages in one run needs one of them. If you use compaction, append the model’s whole response.content to your history each turn, which run.ts already does, or the summary gets lost.
Tools: hands that don’t break
Your agent is only as reliable as its worst tool. A model can recover from a fuzzy prompt; it cannot recover from a tool that lies, throws cryptically, or does something irreversible by surprise. Four rules I follow for every tool.
Rule 1 — Validate inputs at the boundary. With strict: true on the tool (Module 02), the API guarantees the shape: amount will be a number and email will be a string. It can’t guarantee the values. The model will occasionally send a negative amount, a malformed address, a date in the past. Validate before you act, and treat the input like untrusted user input, because effectively it is.
async function sendInvoice(input: { amount: number; email: string }): Promise<string> {
// strict: true guaranteed the types. Check the values FIRST, and say how to fix them.
if (input.amount <= 0) {
throw new Error(`amount must be a positive number, got ${input.amount}. Fix and retry.`);
}
if (!/^\S+@\S+\.\S+$/.test(input.email)) {
throw new Error(`invalid email "${input.email}". Provide a valid address.`);
}
// ... only now do the real thing
return 'Invoice sent.';
}Rule 2 — Errors are messages to the model. When a tool fails, the loop must not crash and must not pretend it worked. The Module 02 loop catches whatever your tool throws and sends it back as a tool_result with is_error: true. The model reads “the API returned 429, rate-limited” and often waits and retries, or picks another route, or reports the failure in its final message. Write error messages for that reader: say what went wrong and what would fix it. This is the single highest-leverage tool habit.
Rule 3 — Make destructive tools loud and gated. Any tool that spends money, sends to customers, or deletes something gets a guardrail. The simplest: a dryRun flag that defaults to true.
async function sendEmail(input: any): Promise<string> {
if (process.env.DRY_RUN !== 'false') {
console.log(`[DRY RUN] would send to ${input.to}: ${input.subject}`);
return 'DRY RUN: email composed but not sent. Looks good.';
}
return await actuallySend(input);
}You develop and test with DRY_RUN on. You flip it off only when the agent has earned trust. Nearly every customer-facing agent I run started its life in permanent dry-run, printing what it would do, for days, before I let it touch a real send.
Rule 4 — One tool, one job, well-described. The description field is prompt. The model picks tools based on those descriptions. Vague description, wrong tool. “Sends an email” is weak. “Sends the finished digest to the operator’s Slack. Call it once, only after the digest is complete” tells the model when and when not to use it. Spend real effort here; it’s some of the highest-ROI writing in the whole agent.
Tools you don’t have to write
Everything above is about tools you write yourself. More and more of an agent’s hands now come ready-made.
Anthropic’s server tools. Web search, web fetch and code execution run on Anthropic’s side. You declare them next to your own tools and there’s no runTool case to write:
const allTools: Anthropic.ToolUnion[] = [
...tools, // your own, from tools.ts
{ type: 'web_search_20260209', name: 'web_search', max_uses: 5 },
{ type: 'web_fetch_20260209', name: 'web_fetch', max_uses: 5 },
];Results come back inside the model’s own turn. Two things to know. A long server-side step can end with stop_reason: 'pause_turn', which is why the Module 02 loop has that case: send the turn back and it continues. And max_uses is your cost cap on searches; set it. Web fetch only opens URLs that already appear in the conversation, which limits how far an injected instruction can send it. Code execution (code_execution_20260521) gives the model a sandbox to run code in for number-crunching and file work. The web tools already filter results with code under the hood, so don’t add code execution alongside them unless the job needs it on its own.
MCP servers. MCP (Model Context Protocol) is the standard way to package a service’s tools — your CRM, Slack, a booking system — so any agent can plug in. In Claude Code and Cowork, connecting one is config. On the API, the MCP connector lets Claude call a remote MCP server directly, without you writing the integration:
const res = await client.beta.messages.create({
betas: ['mcp-client-2025-11-20'],
model: 'claude-opus-5-5',
max_tokens: 16000,
mcp_servers: [
{
type: 'url',
name: 'crm',
url: 'https://mcp.your-crm.example/mcp',
authorization_token: process.env.CRM_MCP_TOKEN,
},
],
tools: [{ type: 'mcp_toolset', mcp_server_name: 'crm' }],
system: systemPrompt,
messages,
});Both halves are required: the server in mcp_servers, and an mcp_toolset entry in tools that names it. The four rules still apply, and Rule 3 most of all. An MCP server often exposes every action the service has, including delete and refund. Turn on only the tools the agent needs, and scope the token to match (Module 06).
Evals: a way to know when it’s wrong
This is the part everyone skips and the part that separates pros from hobbyists. An eval is a test for non-deterministic output. Your agent won’t produce identical text every run, so you can’t assert equals. Instead you check properties: did it do the right kind of thing? Did it avoid the known failure modes?
You do not need a fancy eval framework. You need a folder of test cases and a script that runs your agent against each and checks properties. Here’s a real, minimal eval harness:
// evals/run.ts — your agent's safety net
type Case = {
name: string;
input: string; // the source the agent will see
checks: ((output: string) => boolean)[]; // properties that must hold
};
const cases: Case[] = [
{
name: 'empty source → must NOT invent content',
input: '',
checks: [
(out) => /nothing|no items|empty|quiet/i.test(out), // acknowledges emptiness
(out) => !/meeting|deadline|event/i.test(out), // did NOT hallucinate items
],
},
{
name: 'normal day → leads with most important item',
input: 'Minor: update the wiki. URGENT: payroll deadline today 5pm. FYI: new follower.',
checks: [(out) => out.toLowerCase().indexOf('payroll') < out.toLowerCase().indexOf('wiki')],
},
{
name: 'off-tone trap → no profanity, stays on-brand',
input: 'Customer review: "this place SUCKS, total ripoff!!!"',
checks: [
(out) => !/\b(suck|idiot|wrong|stupid)\b/i.test(out), // doesn't fight back
(out) => /sorry|apolog|understand|reach out/i.test(out), // de-escalates
],
},
];
let failed = 0;
for (const c of cases) {
const output = await runAgent(c.input); // call your real agent
const passed = c.checks.every((check) => check(output));
console.log(`${passed ? 'PASS' : 'FAIL'} ${c.name}`);
if (!passed) {
failed++;
console.log(` got: ${output}\n`);
}
}
console.log(`\n${cases.length - failed}/${cases.length} passed`);
process.exit(failed > 0 ? 1 : 0);Run npx tsx evals/run.ts and you get a pass/fail report. Wire it into CI (Module 07) and it runs on every change. Now when you tweak the prompt and accidentally break the empty-source handling, the eval catches it before the agent ships garbage to a customer.
The two checks every agent’s evals need:
- The hallucination check — feed it empty/thin input, assert it does NOT invent. This catches the #1 production failure.
- The known-failure check — every time the agent screws up in real life, add that exact case to the eval suite. Your evals grow from real failures. After six months, your eval folder is an encyclopedia of every way this agent has ever been wrong, and it can never regress into them again.
Use a model to grade, for fuzzy criteria. Some properties (“is this reply on-brand?”) are too fuzzy for a regex. For those, call Claude as a judge: feed it the output and a rubric, and use structured outputs so the verdict always comes back in the same shape:
import { zodOutputFormat } from '@anthropic-ai/sdk/helpers/zod';
import { z } from 'zod';
const Verdict = z.object({ pass: z.boolean(), reason: z.string() });
async function judge(output: string, rubric: string) {
const res = await client.messages.parse({
model: 'claude-sonnet-5-5',
max_tokens: 4000,
output_config: { effort: 'low', format: zodOutputFormat(Verdict) },
system: `You grade an agent's output against this rubric. Pass only if every point holds.\n\n${rubric}`,
messages: [{ role: 'user', content: `Output to grade:\n\n${output}` }],
});
if (res.stop_reason !== 'end_turn' || !res.parsed_output)
throw new Error(`Judge stopped: ${res.stop_reason}`);
return res.parsed_output; // { pass: boolean, reason: string }
}Then a check is just async (out) => (await judge(out, 'Warm. Mentions one specific detail from the review. Never defensive.')).pass (make checks async and await each one in the runner). It’s another API call, but it lets you eval taste as well as keywords. Keep deterministic checks where you can — they’re free and fast — and use the model-judge only for the genuinely subjective stuff.
Let a grader iterate the work: outcomes. Evals run after the fact and tell you red or green. Managed Agents has a feature that runs the same idea inside the job. You start a session with an outcome (a description of the deliverable plus a rubric) instead of a plain message. A separate grader, with its own context, scores each draft against the rubric criterion by criterion and sends the gaps back, and the agent revises until it passes or hits an iteration cap (3 by default). It fits jobs with one checkable deliverable: the weekly report, a dataset, a set of page rewrites. It doesn’t fit a stream of small replies. Write the rubric the way you write eval checks: concrete, one criterion per line, each independently checkable (“every number cites its source row,” not “looks accurate”). Outcomes don’t replace your eval suite. The suite catches regressions when you change the prompt; an outcome raises the quality of a single run.
How the three work together
Memory, tools and evals work as one system:
- Tools define what the agent can do.
- Memory defines what it knows across runs.
- Evals define how you trust the combination.
When something goes wrong, the diagnosis is almost always one of the three: it acted twice (memory/checkpoint bug), it broke on weird input (tool validation bug), or it produced subtly-wrong output you didn’t catch (missing eval). Internalize that triage and debugging agents stops being mysterious.
Hands-on lab
Take the agent you built in Module 02 and harden it.
Step 1 — Add memory. Give it a memory.json and a remember tool. Make it store one useful thing across runs — for a digest agent, “the last thing I flagged, so I don’t re-flag it.” Run it twice and confirm the second run sees the first run’s memory.
Step 2 — Harden one tool. Pick your agent’s most dangerous tool (the one that sends or spends). Make sure it has strict: true, add value validation that throws a readable error, and add a DRY_RUN flag defaulting to safe. Deliberately feed it bad input and confirm the model gets an is_error result it can act on instead of the run crashing.
Step 3 — Write three evals. A folder, a runner, three cases: (1) the empty/thin-input hallucination check, (2) one “it must lead with the important thing” check, (3) one check specific to your agent’s worst plausible failure. Run them. Make them pass.
Step 4 — Break it on purpose. Edit your prompt to introduce a regression (e.g. remove the “never invent” clause). Run the evals. Watch them go red. That red is the whole point — it’s proof you’ll know next time, before a customer does. Then fix it back to green.
Deliverable: your Module 02 agent, now with persistent memory, one fail-safe tool, and a green eval suite that includes a hallucination check. You can now trust this thing a little. Next module: why the prompt you wrote will still fail in production, and the structure that fixes it.