The field guide to building AI agents
Every Agent Loop Notes entry, sorted by the part of the agent it helps with. If you are new to building agents, read the sections in order. Each entry links the documentation and papers it draws on.
Tools and tool calling
Every agent step either calls a tool or decides not to. These entries cover how to describe tools so the model picks the right one, how to get answers back in a fixed shape, and how to expose tools over MCP.
- No. 6Structured Outputs vs Function Calling: Which to Use When
Structured outputs vs function calling: use tools when the model must act, a JSON schema when you need the answer in a fixed shape, and strict mode for both.
- No. 9Build an MCP Server in Python: A Working 60-Line Example
Build an MCP server in Python with the official SDK: a 60-line docs search server with tools, a resource and a prompt, plus tests and Claude Code setup.
- No. 10Human in the Loop Agents: Approving Risky Tool Calls
Add human approval to AI agents: sort tools by risk, pause and save state, bind each yes to the exact call, then resume. Code for OpenAI, LangGraph and Claude.
- No. 25Handoffs vs Agents as Tools in the OpenAI Agents SDK
Handoffs vs agents as tools in the OpenAI Agents SDK: who owns the reply, what history each specialist sees, guardrails, turn limits and tested code for both.
- No. 26Stateless MCP Server: Keep State With Explicit Handles
MCP 2026-07-28 removed sessions and Mcp-Session-Id. Keep state across tool calls with server-minted handles: tested Python code, auth, expiry and errors.
Context and memory
What the model sees on each turn decides what it can do. These entries cover what to keep in the context window, what to summarize, and what to store outside it.
- No. 4AI Agent Memory: What to Store, Summarize and Forget
How AI agent memory works: trimming and compacting history, saving notes outside the context window, scoring what to recall, and deciding what to forget.
- No. 8Context Engineering for Agents: Budgeting the Context Window
Context engineering for long-running agents: measure what fills the window, trim tool results, clear old ones, compact the history and keep notes outside it.
- No. 24prompt is too long: Fix the Claude API Context Limit Error
Fix the Claude API 400 prompt is too long error in agent loops: count tokens first, cap tool results, drop old turns without breaking pairs, or compact.
Testing and evals
An agent you can't measure is an agent you can't change safely. These entries cover eval suites, graders, LLM judges and tests for multi-agent systems.
- No. 3How to Write Evals for an AI Agent: A Practical Starter Guide
Build your first agent eval suite step by step: pick real tasks, grade outcomes instead of paths, measure consistency with pass^k and read the transcripts.
- No. 5LLM as a Judge: Writing Rubrics That Agree With Humans
How to write an LLM-as-a-judge rubric people agree with: binary criteria, one call per criterion, position swaps, and checking agreement with Cohen's kappa.
- No. 15Multi Agent Evaluation: How to Test Agent Handoffs
Test multi-agent handoffs in two layers: deterministic tests for routing, context and guards, then a labeled eval that scores which agent ends up in control.
Debugging and reliability
Agents fail in loops, timeouts and half-finished tool calls. These entries cover tracing every step, retrying safely and stopping runs that never end.
- No. 2AI Agent Calling the Wrong Tool? 7 Causes and How to Fix Them
A debugging checklist for tool-calling agents: overlapping tools, vague descriptions, ambiguous parameters, noisy output and bad errors, with a fix for each.
- No. 7Agent Infinite Loop: How to Debug Agents That Never Stop
Why AI agents get stuck in infinite loops, and how to stop them: turn caps, token budgets, repeated-call detection, better tool errors and clear stop rules.
- No. 11Agent Observability Tracing: What to Log on Every Step
Trace an AI agent with OpenTelemetry: one span per run, model call and tool call, which gen_ai attributes to record, and how to keep prompts out of traces.
- No. 13Agent Tool Retries: Timeouts, Backoff and Idempotency Keys
Retry agent tool calls only when it is safe: per-attempt timeouts, capped backoff with jitter, idempotency keys and errors the model can read and act on.
- No. 16tool_use ids without tool_result blocks: Claude API Fix
Why the Claude API returns "tool_use ids were found without tool_result blocks immediately after", the six histories behind it and code to fix them.
- No. 17LangGraph GraphRecursionError: Fix the Recursion Limit Error
Why LangGraph raises GraphRecursionError, what recursion_limit counts, the real defaults, and tested fixes with RemainingSteps and call limit middleware.
- No. 18MaxTurnsExceeded in OpenAI Agents SDK: When to Raise max_turns
Why OpenAI Agents SDK raises MaxTurnsExceeded, what counts as a turn, the default of 10, and tested fixes to find the loop, handle it, resume or raise the cap.
- No. 19spawn npx ENOENT: MCP Server Not Showing Up in Claude Desktop
Fix a local MCP server that won't show up in Claude Desktop: read the logs, fix spawn npx ENOENT with absolute paths and env PATH, and handle Windows.
- No. 20Invalid schema for response_format: Fix OpenAI Strict Schemas
Fix OpenAI structured outputs "Invalid schema" errors: additionalProperties false, every key in required, a root object, and keywords strict mode rejects.
- No. 21Claude Code Hooks: Block Risky Commands With PreToolUse
Block rm -rf, force pushes and curl | sh in Claude Code with a PreToolUse hook: the settings.json entry, a tested Python script, exit codes and limits.
- No. 22Claude API 529 overloaded_error: Retries and Model Fallbacks
Handle Claude API 529 overloaded_error in agent loops: what the SDK retries by default, longer backoff, falling back to another model, and errors in streams.
- No. 23MCP error -32000: Connection closed: Fix stdio Servers That Exit
Fix MCP error -32000 Connection closed: find why a stdio server exits at startup, from import errors and missing env vars to relative paths and stdout.
- No. 27LangGraph Durable Execution: Resume Agent Runs After a Crash
How LangGraph durable execution resumes a crashed agent run: checkpointers, thread IDs, tasks, durability modes, and what happened when we killed the process.
- No. 28Claude Code MCP Failed to Connect: Read the Error, Then Fix It
Fix a Claude Code MCP server stuck on Failed to connect: read the detail in claude mcp list, then fix paths, env vars, timeouts, approvals and URLs.
Safety and control
An agent that reads the web or acts on someone's behalf needs limits. These entries cover prompt injection and the design patterns that contain it.
- No. 14Prompt Injection Attacks on AI Agents That Read the Web
How prompt injection hijacks agents that browse, read email or call tools, why filters can't stop it, and the design patterns that limit the damage.
Cost
Long agent runs resend a lot of tokens. These entries cover prompt caching and routing easy turns to smaller models.
- No. 1Prompt Caching for AI Agents: How to Cut Input Costs
How prompt caching works on Claude and OpenAI, how to order an agent's prompt so the cache hits, and how to measure your hit rate from the usage fields.
- No. 12LLM Model Routing: Send Easy Agent Turns to a Smaller Model
Cut LLM costs with model routing: fixed routes, a cheap classifier and cascades that escalate on failure, with working Python and what the research found.