Reader companion · Second printing, Oct 2026 · Hands-on · Python · MCP

Building Agentic AI Systems:
From First Agent to MCP, Multi-Agent Orchestration, and Production

“It is meant to be an engineering book for building reliable AI agents, not only agent demos. Its promise fits in five words: build, secure, evaluate, optimize, deploy.” — Preface
31 Chapters6 Interludes246 Exercises6 CapstonesProduction Case Study460 PagesPythonMCPMulti-AgentAgent SecurityEvaluation & SLOsFree Local Model
🛒 Amazon.com (US)🇮🇳 Amazon.in🇬🇧 Amazon.co.uk🇩🇪 Amazon.de🇨🇦 Amazon.ca🇦🇺 Amazon.com.au

More: 🇯🇵 JP · 🇫🇷 FR · 🇪🇸 ES · 🇸🇬 SG · 🇦🇪 AE · ISBN: 979-8-1775-0632-6 (paperback) · 979-8-1775-1473-4 (hardcover)

Course kit with code, starter files, checkers and every solution: github.com/sbittla/building-agentic-ai

Ask the book — Claude AI companion

Every answer is grounded in the book’s chapters with specific section citations.

⚡ Launch Interactive Companion →

Choose an example question above, or type your own.

About this book

Most agent tutorials either hide everything behind a framework or assume you already write fluent Python. This book closes that gap. You build the agent loop by hand first — call the model, run the tools it asks for, send back the results, repeat — so every framework becomes readable, and then you take it all the way to production: build, secure, evaluate, optimize, deploy.

You build more than 20 agents and tools along the way: a safe calculator, a SQL analyst that corrects its own queries, a code-fixing agent that runs tests, a multi-agent research team, a router, a writer-and-critic pair, an agent published as an MCP server and a deployed agent API. One enterprise support agent grows chapter by chapter from a single model call into a production service, and a closing case study follows it through a real release, incident and rollback.

Safety and measurement are part of the craft: approval gates in code, sandboxes, allow-lists, defenses against prompt injection and exfiltration, a risk model that sizes each agent, and evaluation suites with enough trials to tell a real gain from luck. Fourteen reference cards and seven architecture decision records collect the frameworks. Every exercise has a reference solution in the course kit at github.com/sbittla/building-agentic-ai.

Who this book is for

  • Beginners with no programming background — Chapter 0 and the interludes teach what you need
  • Developers who have built a chatbot and want reliable, production-grade agents
  • Platform engineers building MCP servers, gateways and agent runtimes
  • Staff engineers and architects — the reference model, scorecard, SLOs and agent platform
  • Performance engineers — latency, throughput, cost per successful task and capacity planning

The route

  • Parts 0–1: foundations, tool calling and the agent loop
  • Parts 2–4: state, real APIs, SQL, measuring an agent, human approval, feedback loops, first teams
  • Part 5: MCP servers, clients and the 2026 protocol
  • Parts 6–7: context, memory, RAG, long-running jobs, planning, orchestration, deterministic control, computer use, frameworks
  • Part 8: security, risk sizing, identity and authorization
  • Part 9: evaluation, AgentOps, performance and cost, deployment and MCP at company scale
  • Then: a production case study, six capstones, an afterword and twelve appendices

What’s inside — chapter by chapter

Click any chapter, interlude, the case study, a capstone or an appendix to see its key takeaways, architect’s takeaway and sections. Citation chips in answers scroll directly to the matching chapter.

Chapter 0Foundations
  • The terminal runs commands; ./course.sh runs them inside the course container.
  • Dictionaries, lists, functions and try/except are the Python this book relies on.
  • JSON is how programs exchange data; JSON Schema describes what valid JSON looks like.
  • Web APIs return a status code and (usually) JSON; 4xx means fix your request, 5xx means retry.
  • Secrets live in environment variables, never in code.

Sections: The terminal and the course kit · Python in one file · JSON and JSON Schema · Web APIs and HTTP · Secrets and environment variables · Docker in five minutes

Interlude PThe Python You'll Need
  • Comprehensions build lists and dictionaries in one line.
  • fn(**args) calls a function with a dictionary of arguments: this is how tools are called.
  • Functions are values: store them in dictionaries and pass them around.
  • Classes bundle data with the functions that use it; dataclasses are classes for data.
  • Decorators wrap or register functions.

Sections: Six features, one file · The one pattern to understand deeply

Chapter 1What an Agent Is (and Isn't)
  • An LLM call sends messages and returns one message with content blocks, token usage and a stop reason.
  • LLMs don't know the present, can't be trusted with exact math and can't see private data.
  • A workflow follows steps you wrote. An agent chooses its own steps. Autonomy has a cost, so choose the least autonomous option that does the job.
  • "Agentic" is a spectrum; describe systems by their dimensions: autonomy, state, planning, tool use, environment, persistence, feedback, delegation and adaptation.
  • Every agent has four parts: model, tools, loop and stop condition.
  • The model only asks for actions; your code performs them.
  • The reference model's layers (user/API, runtime, planning, memory, context, tools, policies, model, MCP/APIs/A2A, environment, evaluation and observability) organize the whole book.
  • The model knows only what's in its context, so choosing that context is a core skill; the harness around the model decides what's allowed.
  • Agents come in kinds (assistant, knowledge agent, analyst, action agent, feedback loop, team, planner, long-running, computer use), each with its own main risk.
  • Every agent goes through the agent engineering lifecycle: decide once, then design, build, secure, evaluate, optimize, deploy, operate and improve, round again for each version, and eventually retire.

Architect’s takeaway: Autonomy has a cost: measure whether an agent saves money before building one.

Sections: Anatomy of an LLM call · Where plain LLMs fail · Do you actually need an agent? · What makes a system agentic? · The four parts of an agent · A fixed workflow, for contrast · The agent architecture reference model · The route, and one agent to follow through it · Kinds of agents and when to use each · The agent engineering lifecycle

Interlude TTesting with pytest
  • A test is a function named test_* that asserts; pytest finds and runs it.
  • parametrize, pytest.raises, tmp_path and monkeypatch cover almost every test in this book.
  • Test the model-free parts directly; replace the model with a scripted stand-in to test the loop.
  • Good tests check one behavior, cover the edges and run fast.

Sections: A test is a function that asserts · The five patterns you'll use · Good tests

Chapter 2Tool Calling (Function Calling)
  • A tool is a function plus a name, a description and a JSON Schema.
  • The model asks for a tool with a tool_use block. Your code runs it and replies with a tool_result that has the matching ID.
  • The description is the model's only guide, so write it carefully.
  • Treat every tool input as untrusted; never eval it.
  • Return errors as data with is_error: true so the model can recover.

Architect’s takeaway: Tools are contracts with models: clear input specs prevent injection attacks.

Sections: What a tool is · Your first tool: today's date · A second tool, made safe: a calculator · The round-trip, step by step · Writing descriptions that work · Errors are data

Chapter 3Tool Selection, Routing and Tool Search
  • A registry maps names to functions; TOOLS describes them to the model.
  • The model picks tools by reasoning over descriptions, so overlap and vagueness cause misroutes.
  • tool_choice can require a tool, forbid tools or force a specific one.
  • A routing eval turns "it seems better" into a number.
  • Validate arguments in the schema and in code, and write error messages that explain the fix.
  • With many tools, defer most of them and let the model find what it needs with tool search.

Architect’s takeaway: More tools mean longer reasoning and higher injection risk; evaluate trade-offs.

Sections: A tool registry · How the model chooses · Controlling the choice with tool_choice · Measuring routing accuracy · Validating arguments · When you have dozens of tools: tool search

Chapter 4The Agent Loop
  • The agent loop repeats: call model → run tools → send results, until the model stops asking.
  • Return a result for every tool_use block in a response.
  • Always cap iterations; add budgets and no-progress checks later.
  • Trace every step. The trace, not the final answer, shows you what went wrong. Appendix B has a step-by-step debugging playbook for when an agent misbehaves.
  • History is resent on every call, so input tokens grow quickly; keep tool outputs small.
  • The system prompt says who the model is, when to use which tool, the rules, the output format and what to do when stuck; hard rules go in code as well.

Architect’s takeaway: Unbounded loops kill costs: set iteration caps and stopping conditions first.

Sections: From two calls to a loop · Walking through one run · Several tool calls in one turn · Stop conditions · Tracing: see what your agent does · Why history grows, and what it costs · A multi-turn chat with the agent · Thinking and effort · Budgets for a whole task · Writing the system prompt

Chapter 5State and Short-Term Memory
  • History lasts one session. Persistent state lives outside the model and is changed only by tools.
  • Use exact identifiers (IDs) for anything a tool changes, and give the model a way to look them up.
  • Make state-changing tools idempotent, because agents repeat calls.
  • When a request is ambiguous, the right answer is a question.
  • Choose storage by scale and concurrency: JSON, then SQLite, then a database.

Architect’s takeaway: Episode boundaries drive memory costs: choose them by session, not by time.

Sections: Two kinds of memory · The to-do tools · Idempotent tools · Ambiguity: ask, don't guess · Choosing a storage backend · What the agent should (and shouldn't) remember

Interlude RRegular Expressions
  • A pattern is built from a few pieces: literals, \d \w \s, sets, repetition, anchors and groups.
  • search finds, findall extracts, sub replaces and match checks the start.
  • Write patterns as raw strings (r"...").
  • Use regex to find and extract text, never as a security check.

Sections: The pieces · The four functions

Chapter 6Agentic Search: Exploring an Environment
  • Agentic search is list → search → read, with the model choosing each step.
  • Resolve paths, then check they're inside the sandbox.
  • Page large outputs and cap search hits.
  • Require citations; they make answers checkable and evaluable.
  • Use agentic search for exact, fresh, modest-size data, and RAG for fuzzy meaning at large scale, or both.

Architect’s takeaway: Agent file access needs strong isolation: design permissions before building tools.

Sections: Agentic search · The notes tools · The sandbox · Protecting the context window · Citations · Agentic search or RAG?

Chapter 7Real APIs
  • Wrap external APIs in tools with timeouts, retries with backoff, and clear failure messages.
  • Retry timeouts, 429 and 5xx; fail fast on other 4xx.
  • Return all candidates for ambiguous inputs and let the model ask the user.
  • Cache responses that don't change quickly; measure hits and calls.
  • Budget external calls per run, and tell the model what to do when the budget runs out.

Architect’s takeaway: External APIs fail as a matter of course: give every call a timeout, a retry limit and a failure message the model can act on.

Sections: Choosing an API for learning · The weather tools · What can go wrong with an API call · Ambiguity: ask the user · Caching · Budgets for external calls

Interlude SSQL in One Sitting
  • SELECT … FROM … WHERE picks and filters; ORDER BY and LIMIT sort and trim.
  • Aggregates with GROUP BY summarize; JOIN combines tables on matching ids.
  • Parameters prevent SQL injection; CTEs make long queries readable.
  • Check someone else's SQL from FROM and JOIN through to ORDER BY.

Sections: Eight queries, each building on the last · Reading someone else's SQL

Chapter 8Self-Correction: A Text-to-SQL Agent
  • A text-to-SQL agent needs only get_schema and run_query; the model does the rest.
  • Enforce read-only access at the connection or user level, not in the prompt.
  • Exact error messages turn failures into self-correction.
  • Cap result sizes and tell the model when you truncate.
  • Evaluate against known answers, because a confident answer can still be wrong.

Architect’s takeaway: Self-correction is expensive: measure latency and token costs before mandating it.

Sections: A sample database · The SQL tools · Safety in layers · Error-driven self-correction · Keeping results small · Checking answers

Interlude MMeasuring an Agent
  • A case is a question and a check; keep cases in a JSONL file and add to it whenever the agent fails in a new way.
  • Run every case several times: one run is an anecdote.
  • Report a pass rate with its 95% interval; small samples have wide intervals.
  • A change is an improvement only when the intervals say so; when they overlap, you can't tell yet.
  • Flaky cases show where the agent is guessing.

Sections: Cases, trials and margins · Reading the results

Chapter 9Human-in-the-Loop Approval
  • Rate every tool by reversibility and impact; don't give agents the most dangerous ones.
  • Separate read-only planning from acting, and bind approval to a stored plan ID.
  • Enforce approval gates in code; tell the model what to do when an action is declined.
  • Log every change so you can undo and explain it.
  • Use reviewed policies to auto-approve low-risk actions.

Architect’s takeaway: Design reversibility first: high-impact actions need undo capability by default.

Sections: Rate actions by risk · Plan, then act · The gate lives in code · Audit log and undo · Never overwrite · Auto-approval policies

Chapter 10Feedback Loops
  • Feedback loops replace "the model thinks it's done" with an objective signal.
  • Protect the signal: agents must not be able to edit the tests.
  • Run generated code with timeouts, and in isolation for anything real.
  • Stop on budget and on lack of progress, not only on an iteration cap.
  • Deliver changes as a diff for human review.

Architect’s takeaway: Composable tools need clear execution boundaries: define them before agents scale.

Sections: Why feedback loops work · A project with bugs · The fixer agent · Guardrails for code-changing agents · Stop conditions: budget and progress · Review by diff

Interlude AAsynchronous Python
  • Async lets one program overlap many waits: for the model, APIs and servers.
  • async def defines, await waits, asyncio.run starts and gather runs things at the same time.
  • to_thread keeps blocking code from freezing everything; async with opens what must be closed.
  • Always await a coroutine, and never call blocking functions inside async code.

Sections: Waiting without blocking · The five ideas · Reading async agent code

Chapter 11Multi-Agent Systems
  • Orchestrator–worker: a lead plans, subagents work in parallel with clean contexts and the lead synthesizes.
  • Use a forced tool call to get a structured plan.
  • Run subagents concurrently with asyncio, and run blocking tools in threads.
  • Subagents should return short, cited findings.
  • Multi-agent systems are more powerful for broad tasks and much more expensive; measure before choosing.
  • Beyond orchestrator–worker: routers, handoffs, evaluator–optimizer loops and voting each fit a different job.
  • Contracts, contained failures, least privilege and one trace id keep a team of agents under control; A2A connects agents across organizations.

Architect’s takeaway: Multi-agent systems add latency and failure modes: design handoff explicitly.

Sections: Why more than one agent? · The research team · How it works · Writing good subtasks · Cost and when not to use it · Four more patterns · Keeping a team of agents safe and debuggable

Chapter 12MCP Fundamentals and Your First Server
  • MCP packages tools once so any compatible host can use them.
  • Hosts run models; each host has one client per server; servers offer tools, resources and prompts.
  • The Python SDK builds tool schemas from type hints and docstrings.
  • Log to stderr in stdio servers, and test with Inspector before involving a model.
  • Use stdio for local servers and Streamable HTTP for shared or remote ones.

Architect’s takeaway: Standard protocols reduce integration friction but increase orchestration complexity.

Sections: The problem MCP solves · Hosts, clients and servers · What a server offers · Your first server · Testing with MCP Inspector · Connecting to Claude Desktop · Transports: stdio and Streamable HTTP · Other MCP features you'll meet

Chapter 13Build Your Own MCP Client
  • An MCP host lists tools from each server and gives them to the model; the loop itself doesn't change.
  • Namespace tool names by server to avoid collisions and help the model.
  • Route each call to its server with call_tool, and pass is_error through.
  • Keep connections open for the session with AsyncExitStack.
  • Use resources for reference data and prompts for user-selected templates.
  • Wrap a whole agent as an MCP tool to delegate across teams; it keeps its own limits and reports failures as errors.

Architect’s takeaway: MCP server quality directly determines agent reliability; prioritize robust debugging.

Sections: What changes in the loop · Two more servers · The MCP host · Connection lifecycle · Reading resources and prompts · Agents as MCP servers

Chapter 14Using Servers You Didn't Write
  • Reference and vendor servers give agents large capabilities with a line of config.
  • Every server runs with your permissions; check who publishes it and narrow what it can do.
  • Anyone who writes content your agent reads can attempt prompt injection.
  • Defend in layers: remove capabilities, require approvals in code, hide unneeded tools, then prompt, then log.
  • A policy layer between model and servers enforces allow-lists, approvals and auditing.
  • The policy layer also limits where data can go; Chapter 25 explains why that matters as much as guarding writes.

Architect’s takeaway: Every third-party server runs with your permissions: decide trust in your policy layer, never from the server's own description.

Sections: Reference servers · One config for all of them · Trusting a server · Prompt injection through tool output · A policy layer

Chapter 15MCP in 2026: From Tool Calling to Agent Infrastructure
  • The 2026-07-28 specification made MCP stateless: each request carries its version and capabilities, so any server copy can answer; server/discover is optional.
  • HTTP requests repeat the method and tool name in headers for gateways; servers reject requests whose headers and body disagree.
  • Lists carry ttlMs and cacheScope; clients cache them, which saves a request on nearly every model call.
  • Optional features now live in extensions; as of 2026-07-28, sampling, roots, protocol logging and HTTP+SSE are deprecated, not removed: they keep working for at least a year.
  • Jobs, gateways, registries and company sign-on are built on these changes in sections 30.8 to 30.11.

Architect’s takeaway: Stateless protocols and progressive discovery scale better than monolithic tool sets.

Sections: From tool calling to infrastructure · The protocol on the wire · Discovery and caching · Extensions and the road ahead

Chapter 16Context Engineering
  • Context engineering asks what information the agent needs on each step, in what form, from which source; prompts are only one part of it.
  • Assemble context per call from routed sources, by priority, within a budget, and keep a report of what was left out.
  • Give every item a time to live and a provenance label; refresh stale items and resolve conflicts by age and authority.
  • Trim old tool results, compact older turns, keep notes outside the context, and cut only at safe points.
  • Order context from stable to volatile and cache the stable prefix; cache reads cost a tenth of normal input.
  • Give subagents a small brief and take back a condensed answer; never share raw tool output between agents.
  • Programmatic tool calling keeps bulky intermediate results out of the context entirely.

Architect’s takeaway: Token budget drives architecture: compress context ruthlessly or fail at scale.

Sections: From prompt engineering to context engineering · What fills the context, and measuring it · Assembling context for each step · Freshness and provenance · Trimming old tool results · Compacting with a summary · Prompt caching · Letting the API manage context · Isolating context between agents · System prompts and tool sets as design · Keeping big results out of context: programmatic tool calling

Chapter 17Agent Memory Engineering
  • Working, episodic, semantic and procedural memory need different lifetimes, stores and levels of scrutiny.
  • A memory policy gives each memory a kind, subject, scope, owner, source, confidence and expiry, and your code enforces it.
  • Recall ranks by match, recency, confidence and kind, and returns only what fits the budget.
  • Supersede by subject, expire on schedule, consolidate episodes and forget on request.
  • Scope memories to a user, an agent or a team, and restrict who may write shared memory.
  • Defend against memory poisoning with a write gate, provenance, "memory is data" and least-privilege writes.
  • Memory is persistent, attacker-reachable state: stamp every record with tenant, owner, provenance and trust, authorize reads before ranking, and audit every write, read and deletion without copying the content, so you can delete, prove it and roll back.

Architect’s takeaway: Choose memory system by query pattern: external databases scale better than context.

Sections: Why memory is architecture · Four kinds of memory · A first long-term memory · A memory policy · Recall by relevance · Forgetting and staleness · Who owns a memory: scopes and sharing · Memory poisoning · Where memories live · Memory is a security boundary

Chapter 18Agentic RAG and Knowledge Systems
  • RAG = chunk, embed, index, retrieve, then answer with citations.
  • Embeddings capture meaning; BM25 captures exact words; hybrid ranking gets both.
  • Retrieval works best as a tool the agent can call repeatedly.
  • Measure retrieval with recall@k and MRR before tuning anything else.
  • Agentic retrieval plans information needs, chooses a source for each, judges the evidence and searches again when it's thin.
  • Verify answers in code: citations must point at retrieved evidence, and numbers must appear in it.

Architect’s takeaway: Retrieval quality determines hallucination risk: invest in ranking and citation.

Sections: The pipeline · Chunking · Embeddings · Keyword search and hybrid ranking · Retrieval as a tool · Measuring retrieval · Going further · From RAG to agentic retrieval · Choosing a source · Is the evidence enough? · Verifying the answer

Chapter 19Long-Running Agents
  • Long-running work follows goal, plan, execute, checkpoint, recover, continue, verify, deliver.
  • A job is data: each step's status and result are saved before the next step starts, including model outputs.
  • Retry transient failures with backoff and a limit; raise permanent errors immediately; time-limit steps and jobs.
  • Give every side effect a stable idempotency key, or escalate when its outcome is unknown.
  • Leases let another worker finish a dead worker's job.
  • Escalate to a person when the runner shouldn't guess, and compensate finished steps, newest first, when a job is abandoned.
  • For open-ended work, keep a checklist with checks in code and a progress file, and do one verified item at a time.

Architect’s takeaway: Design checkpointing before you need it: agent state must survive restarts.

Sections: From prompt → answer to goal → deliver · What breaks when work takes hours · Checkpoints: a job is data · Retries, timeouts and errors you mustn't retry · Idempotency: doing it twice must be safe · Leases and task queues · Escalation and compensation · Open-ended work: a harness across sessions · Durable execution in production

Chapter 20Planning and Model Routing
  • Decide step by step for short tasks; plan first for long ones, and replan when reality disagrees.
  • Get plans as structured data: steps, tools, dependencies and a done condition.
  • Check plans in code before running them: size, known tools, valid dependencies, no cycles.
  • Execute each step with its own brief, tools and done condition; keep finished results when replanning.
  • A checked plan can become a durable job (Chapter 19).
  • Route between models and effort levels with rules, a classifier or a cascade.
  • Compare routers by cost per successful task, measured on real checks.

Architect’s takeaway: Planning delays execution: only justify its cost if revisions save more tokens.

Sections: Step by step, or plan first? · A plan is data · Check the plan before running it · Execute: one step, one brief · Replanning · Plans and long-running jobs · Model routing · Three routers · Measure cost per successful task

Chapter 21Multi-Agent Orchestration
  • Choose a topology deliberately; a supervisor with limited depth is the usual start.
  • Contracts define what agents hand each other, and code validates them.
  • A shared board records the team's work; only the orchestrator writes it, and it enforces depth, task, duplicate and budget limits.
  • Specialists get briefs, not histories: smaller, safer and testable.
  • Contain failures as error results the lead can handle, and label results as data from another agent.
  • Resolve disagreements with independent verification, evidence, code and people.
  • A2A connects agents across teams and companies through agent cards and tasks; MCP inside your system, A2A at its boundary.
  • A team pays for itself only when its measured success gain, valued per task, exceeds its coordination overhead (extra calls, duplicated context, messages, waiting for the slowest worker, retries and compounding failures), or when it meets a requirement one agent can't.

Architect’s takeaway: Wrong routing costs more than wrong execution: invest in routing quality early.

Sections: Topologies · Contracts between agents · A shared board and hard limits · Briefs, not histories · How teams fail, and containment · Resolving disagreement · Agents across boundaries: A2A · MCP or A2A? · When not to build a team · Does the team pay for itself?

Chapter 22Hybrid Architectures: Probabilistic Intelligence, Deterministic Control
  • Give the model what needs judgment: understanding text, drafting, planning. Give code what must be right every time.
  • Put model calls inside a deterministic shell: states and transitions in code, with one method that moves a case and logs why.
  • Treat model outputs as proposals, and check them against the input, the records, the user's identity and the policy.
  • Keep rules as data, and take every number from records.
  • Guard model outputs before they reach people, with a fallback that's always correct.
  • Log every transition; wait for people without holding resources.
  • Unit-test the deterministic parts; evaluate the probabilistic parts.

Architect’s takeaway: Rules engines scale better than models for deterministic paths: choose wisely.

Sections: Two kinds of work · A deterministic shell with model steps · States and transitions in code · Model outputs are proposals · Rules as data, numbers from records · Guard what the model says · Approvals and the audit trail · Where to draw the line

Chapter 23Computer-Use Agents
  • Use a computer-use agent when there's no API; use the API when there is.
  • Show the model the page as text with numbered controls; keep screenshots as evidence for people, or use them when there's no page structure.
  • The harness signs in, keeps the browser on an allowlist, holds dangerous clicks for approval, limits and logs actions and never lets the agent type passwords.
  • Read, act, read again; verify important results in code.
  • Page text is untrusted input. The strongest defense is an account that can only do what the task needs.
  • Make it reliable with waits, fresh references, timeouts, an isolated browser and durable steps for long queues.
  • Wrap each action in code: check the page before, verify it after, retry only what didn't happen or is safe to repeat, hand expired sessions and MFA to a person and log every read as evidence.

Architect’s takeaway: GUI agents are fragile: design error recovery and execution bounds before scaling.

Sections: When to use the screen · How an agent sees a screen · The harness · Acting and checking · Controls that don't depend on the model · Injection through the screen · Making it reliable · Desktop computer use · Reliability engineering for computer use

Chapter 24Skills, Frameworks and Agent Runtimes
  • Frameworks package the loop, tool schemas, limits, approvals and memory you built by hand.
  • The tool runner is the lightest step: your Chapter 4 loop in one call.
  • The Claude Agent SDK is a full agent runtime; isolate it and gate tools with can_use_tool.
  • A skill is reviewed procedural memory; test that it improves results, with checks in code.
  • A skill is executable agent knowledge: give it a version, a manifest with permissions and a content hash, a trust level, a regression gate and a way to roll back.
  • Choose a runtime by where state lives, how controls are enforced, what you can observe, where code runs, and cost.
  • LangChain's create_agent is model-agnostic and extensible with middleware.
  • Agent Skills package instructions and files that an agent loads only when a task needs them.
  • Claude Managed Agents runs the loop and the sandbox for you; custom tools, permission policies and budgets keep you in control.
  • The practices matter more than the framework.
  • Almost everything in this book works with other model providers: keep model calls behind one function, and rerun your evaluations when you switch.

Architect’s takeaway: A framework packages the loop, not the judgment: keep your controls and evaluations portable, and rerun them whenever you change runtime.

Sections: The same ideas, different names · The tool runner: your loop, built in · The Claude Agent SDK · LangChain: model-agnostic agents · Build or buy? · Using other model providers · Agent Skills: packaging know-how · Claude Managed Agents: renting the whole runtime · Choosing a runtime · Skills as software

Chapter 25Agentic Security
  • An agent's attack surface is its ways in (untrusted text), its ways to act, and what it can reach.
  • Threat-model with four questions, and break the lethal trifecta wherever you find it.
  • Prompt injection comes directly, indirectly, stored in memory, relayed by agents, in tool descriptions and hidden in content. Prompts reduce it; code and architecture stop it.
  • Allow-list outbound sites, ask before sending anything after private data was read and refuse private addresses.
  • Separate reading from acting: a quarantined reader with no tools and a schema, a planner that never sees untrusted text.
  • Guard actions, not intentions: canaries, leak scans and egress checks work when the model is fooled.
  • Treat model output as untrusted input to whatever comes next, including the screen.
  • Red-team with a model that obeys attackers, keep the suite in CI and check your agents against the OWASP agentic list.
  • Keep a regression scenario for every defense: the attack succeeding without the control, failing with it, and what remains. Deterministic controls hold even when the model is fooled; model-dependent ones are measured with evaluations.
  • Size an agent's risk as capability × autonomy × access × persistence × blast radius, each 1 to 3. The tier sets the required controls, and cutting any one factor cuts the risk. The score is a judgment aid, not a probability.
  • The model proposes; a deterministic control plane enforces identity, policy, permissions, validation, budgets, approvals, state transitions, audit and rollback.

Architect’s takeaway: Assume the model will be fooled: break the lethal trifecta in the architecture, and guard actions in code rather than in the prompt.

Sections: The attack surface of an agent · Threat-modeling an agent · Prompt injection, in all its forms · Data leaving: exfiltration and SSRF · Designs that defeat injection · Guards that don't trust the model · Model output is untrusted too · Red teaming and monitoring · Checking your agent against industry lists · Security regression scenarios · Sizing the risk of an agent

Chapter 26Agent Identity and Authorization
  • Every action has a user, an agent and a service; record all three.
  • Agents get their own identities and short-lived tokens, never a person's credentials.
  • Tokens carry the agent, the user, an audience, scopes, limits, an expiry and an id; a registry caps what each agent may ever hold.
  • The tool verifies the token, the resource's owner, the scope and the limits on every call, and logs the decision.
  • Derived tokens can only narrow; revoking a token revokes everything derived from it.
  • Risky actions need a step-up token: minted after a person approves, for one action, one amount, once.
  • Keep revocation, an agent kill switch and key rotation ready; use OAuth, token exchange and your identity provider in production.
  • Finding a capability isn't trusting it: verify the publisher for that kind and the pinned hash, check protocol versions, and delegate across organizations with tokens that only narrow and die with their parent.

Architect’s takeaway: Least privilege applies harder for agents: privilege must match autonomy exactly.

Sections: Who is acting? · Never lend an agent your password · Tokens that say what's allowed · Checking at the tool · Narrower tokens for subagents · Step-up for risky actions · Audit, revocation and the kill switch · In production · Discovery: finding a capability is not trusting it · Trust across organizations

Chapter 27Agent Evaluation: Dimensions, Trajectories and Scorecards
  • Evaluation suites turn "seems better" into pass rates; grow them from real failures.
  • Run cases several times and read pass rates with confidence intervals, pass^k and flaky cases.
  • Calibrate model judges against human labels before trusting them.
  • Grade every run on outcome, process and cost.
  • Trajectory checks cover tools, order, arguments, efficiency, repeated failures and recovery.
  • Score each run on ten dimensions: task success, trajectory, tools, arguments, safety, cost, latency, reliability, groundedness and escalation. Each automatic check is a proxy with blind spots, and the dimensions cover for each other.
  • A scorecard per release shows success, pass^k, accuracy, completion, safety, steps, latency and cost side by side, and uses the same definitions as your production SLOs.
  • Gate CI on a statistical comparison with the baseline, plus fixed limits for what has no slack, such as safety.
  • Evaluate continuously in production: sample, grade, watch for drift and turn failures into test cases.

Architect’s takeaway: Define success metrics before building: measurement shapes every architectural choice.

Sections: From demo to production · Evaluation suites · Outcome, process and cost · Checking the trajectory · Ten dimensions of agent quality · The agent scorecard · A regression gate for CI · Continuous evaluation

Chapter 28AgentOps: Observability, Telemetry and SLOs for Agents
  • Agent observability follows the chain from goal to context, decision, tool, result and outcome.
  • OpenTelemetry spans with the GenAI conventions record model and tool calls without changing the agent; structured logs join them through the trace_id.
  • Keep secrets out and redact personal data; prefer references to copies; retain on purpose.
  • Summarize runs into tokens, cost, latency and per-tool error rates; record error.type so a tool error, a denied authorization and a blocked action reach different owners.
  • Break latency into model, tool and "other", and read a run's trajectory as a timeline.
  • Classify failures with a fixed taxonomy; five of the 12 classes need evals and one needs a memory audit, because traces can't see them.
  • Public incidents map to the same classes and to controls from earlier chapters: grounding, business rules in code, approval gates, isolation of untrusted text and narrow tokens.
  • One page shows the headline numbers, SLOs, failure classes and tools. SLOs measure what users feel, from traces, evals and human review; their error budgets drive burn-rate alerts and release gates.
  • Debug from the alert down: SLO, class, runs, span, logs, change, mitigation and a new test case.
  • A trace says where the time went; joining each span with resource metrics (on time and place) and profiler samples (on span id) says why. Blame a resource only when spans are slower while it's saturated and latency rises with it, then read the remaining tail in the profile.

Architect’s takeaway: Trace every decision and tool call: observability is foundational, not optional.

Sections: Tracing with OpenTelemetry · Structured agent logs · What never goes into telemetry · Token and cost telemetry · Tool-call telemetry · Latency breakdown · Visualizing a trajectory · The agent failure taxonomy · Production dashboards · SLOs for agents · Alerting · Debugging production agents · Correlating traces with resources: continuous profiling

Chapter 29Agent Performance Engineering: Latency, Throughput and Cost
  • Latency is model + tool + retrieval + orchestration + queueing + serialization; cost per task is model + tools + retrieval + infrastructure + retries + human review. Measure every term from traces, and attack the biggest.
  • Each step resends the whole conversation, so cost and latency grow faster than the number of steps; output tokens dominate latency.
  • Pull the levers in order of payoff: caching, trimming, routing, effort, fewer steps, parallel tools, batching, streaming.
  • Judge every change by cost per successful task on your evaluation suite.
  • Make the business case against the human baseline, not zero: tokens are often a small line next to takeovers, upkeep and failures. State every assumption, find the break-even automation and failure rates, rank assumptions by their effect on payback, and rebuild the case monthly from actuals.
  • Choose a design with a reproducible benchmark: answers checked against the data, the same random numbers for every configuration, everything needed to rerun it recorded, and success read with its confidence interval.
  • Enforce budgets in code (per request, per user and per job) and alert on cost per success.
  • Sweep concurrency to find the knee: throughput stops rising, queueing takes over latency, the cache hit rate falls and goodput drops as tasks time out. Cap concurrency at the knee and name the limiting resource.
  • Load-test open-loop at your forecast rate, measure from arrival and watch p95 and errors.
  • Plan capacity with Little's law, the knee and token rate limits, and fail gracefully at the limit.

Architect’s takeaway: Know your cost drivers: token cost and latency often pull in opposite directions.

Sections: The agent performance model · Where the time and money go · The levers · Budgets in code · Performance experiments: finding the knee · Load testing at an arrival rate · Capacity planning · A reproducible benchmark for architecture decisions · Agent economics: from cost per task to payback

Chapter 30Deploying Agents: From One Service to an Agent Platform
  • An agent service needs auth, per-caller rate limits, private sessions, budgets and clean errors.
  • Stream progress with Server-Sent Events so long runs feel responsive.
  • Remote MCP servers run over Streamable HTTP (MCP's HTTP transport) and must be authenticated.
  • Configuration and secrets come from the environment; logs record ids and numbers, not content.
  • Deploy a small, non-root image with secrets given at run time, limits on instances and cost and a smoke test against the public HTTPS URL.
  • Long-running tools return a job handle at once, run durably and are safe to retry; MCP's Tasks extension standardizes the same shape.
  • A gateway gives one place to allow-list tools, check agent tokens, rate-limit, cache and audit, and can offer tools through search.
  • Registries verify publishers, not code: pin versions, watch tool definitions and keep your own allow-list. Company sign-on is moving to issuer validation, client metadata documents and enterprise-managed authorization.
  • When many teams ship agents, a platform team provides shared gateways, identity, policy, memory, workflow, evaluation, observability and cost controls as paved roads. Standardize identity and secrets first.
  • Memory, sessions, private caches and tokens are never shared between tenants; each tenant gets its own keys and budgets.
  • Govern agents with an inventory, launch reviews by risk tier, retention rules, a map to regulation and an incident process.
  • Release gradually (shadow, canary, rollback), version the whole agent, plan for model retirements and retire agents cleanly.
  • The improvement loop mines production failures into deduplicated, labeled cases, then gates a change offline, in shadow and in a canary with code and thresholds, and records the evidence. Every failure it finds stays in the suite, so it can't come back unnoticed.
  • The reference architecture (user or API, runtime, model, MCP, APIs and A2A, environment, with evaluation and observability across all layers) places every agent you build.

Architect’s takeaway: Production systems need strong isolation: one tenant's mistakes shouldn't break others.

Sections: The architecture · The agent API · Streaming progress · A remote MCP server · Configuration and containers · Deploying to the cloud · Launch checklist · Long-running tools: start, then check · Gateways: one front door · Registries and the supply chain · Authorization for companies · From one agent to an agent platform · The agent lifecycle in production · The agent improvement loop · The end-to-end reference architecture

Case StudyThe Support Agent in Production
  • Follows one agent through a release at Harbor & Pine, a fictional online homewares shop: about 600 support conversations a day, up to 1,200 an hour on sale days; 55% order status, 25% returns, 10% refunds, 10% everything else.
  • Requirements are written as numbers: at least 95% of conversations resolved correctly with handbook citations, no customer ever sees another's data, no refund above $100 without a person, p95 reply under 8 seconds and at most $0.02 of model spend per resolved conversation.
  • The design is chosen per kind of request: a workflow for order status (the agent's accuracy at about a third of the cost), a state machine with model steps for returns and refunds, one agent with retrieval and citations for everything else, and a small model routing between them. A team of specialists was rejected on the evidence.
  • Testing found four problems, each of which changed the design: invented policy (fixed by citation checks in code), a cost eight times the budget from pasting the handbook into the system prompt (fixed by retrieval and prompt caching, to about $0.01), identity passed as a tool argument (moved to the login) and retries hiding in the latency tail.
  • Capacity comes from Little's law and the measured knee: a concurrency limit of twelve, checked against token rate limits, with an honest HTTP 503 beyond it.
  • An incident: release 1.3's warmer prompt passed the gate but, as a 10% canary, stopped handing upset customers to a person. The burn-rate alert rolled it back automatically, and the handoff rule moved from the prompt into code.
  • The order of the work is the lesson: decide what the agent is for, write the evaluation before the agent exists, threat-model before connecting tools, measure before optimizing, and ship behind a gate, a canary and a practiced rollback.

Sections: The requirements · The threat model · Choosing the design, request by request · Evaluation data · What testing found, and what changed · Load test and capacity · Deployment and observability · An incident, and the rollback · The trade-offs, in one place

Capstone 1Customer Support Agent
  • Answers policy questions from the help center with citations, looks up only the signed-in customer's orders and never reveals another customer's data (Chapter 18).
  • Starts a return only when the order is inside the return window, checked in code; refunds over a threshold need human approval (Chapters 9 and 22).
  • Identity is never a tool argument: the host starts the orders server for the signed-in customer, so "I'm actually ben@example.com" can't turn the agent into a lookup service (Chapters 26 and 30).
  • Remembers preferences and open issues under a memory policy (Chapter 17), and hands off to a person with a written summary when the customer is upset, asks for a person or the agent is unsure.
  • Week 4 milestone: a 30-case eval with trajectory checks, traces and cost per resolved conversation under 20 concurrent chats. Real-world version: Intercom's Fin.
  • Each capstone takes about four weeks part-time with weekly milestones (servers, agent, safety, measurement) and is graded on one rubric: functionality 20%, architecture 15%, safety and identity 20%, evaluation 20%, observability 10%, performance and cost 10%, documentation 5%. Reference solutions are in solutions/capstones; build your own first. All six run on the free local model, though 4, 5 and 6 work noticeably better with Claude.

Sections: helpdesk, orders and handoff MCP servers · returns within policy · memory policy · human handoff

Capstone 2Natural-Language Data Analyst
  • Answers data questions over a real multi-table database (Chinook or your own export), shows its SQL in every answer and makes charts with a make_chart tool.
  • A read-only SQL MCP server with a business-definitions resource; the user confirms table selection before querying, QueryGPT-style.
  • Self-correction with a retry budget; queries are parsed and checked in code (read-only, row limits, allowed tables), and terms like "revenue" come from the definitions, never the model's guess (Chapter 22).
  • Evaluated on 25 cases that compare result values, not text, plus trajectory checks and cost per correct answer. Real-world version: Uber's QueryGPT.

Sections: Read-only warehouse MCP server · business definitions · table confirmation · self-correction · charts

Capstone 3Incident Triage Assistant
  • When an alert fires, collects logs, metrics, recent deployments and runbooks and posts a first triage summary: impact, timeline, suspected cause, evidence and next steps.
  • Flags anomalies such as p95 latency or error rate against a baseline; statistics are computed in code, never by the model.
  • Investigates logs, metrics and deployments in parallel with subagents, each with a narrow brief (Chapters 16 and 21), and compares that with a single agent on quality, latency and cost.
  • Suggests runbook steps but never runs a remediation without approval. An extension flags performance regressions between two load-test runs (Gatling, JMeter, k6 or Locust) only when a bootstrap confidence interval says they're real.

Sections: logs, metrics, git and runbooks servers · parallel subagents · statistics in code · structured triage report

Capstone 4Code Review and Fix Agent
  • Reviews a pull request through the GitHub MCP server with a read-only, repository-scoped token; write access is a separate, approved step (Chapter 26).
  • Runs tests and linters in a container with no network (Chapter 10) and posts a structured review: bugs, risks, missing tests and style, each tied to a file and line.
  • For failing tests, proposes a fix on a new branch with a long-running harness: progress file, checklist, a commit per step and resume after interruption (Chapter 19). It never edits tests.
  • Treats PR text and code comments as untrusted input (Chapter 25), and is evaluated on bugs found, false alarms, fix success rate and cost per merged fix.

Sections: GitHub MCP server · scoped tokens · tests in a no-network sandbox · structured review · resumable fix harness

Capstone 5Deep Research Assistant
  • A multi-agent research assistant that plans, researches in parallel, checks its claims and writes a cited brief within a budget.
  • The lead produces a structured plan with objectives, boundaries and effort per subtask, and stops at its budget (Chapter 20); subagents get isolated briefs (Chapter 21).
  • Every claim is checked against fetched source text and unsupported claims are revised or dropped (Chapter 18); a critic pass adds one revision, and fetched pages are treated as untrusted.
  • Week 4 compares a single agent with the team on quality, latency and cost per brief. Real-world version: Anthropic's Research feature, at roughly 15 times the tokens of a chat (Chapter 11).

Sections: Lead planner · parallel subagents · fetch, library and memory servers · claim verification · critic pass

Capstone 6Back-Office Workflow Agent
  • Works through a queue of requests in a web application that has no API, in a browser, one at a time, over hours (Chapter 23).
  • Processes the queue as a long-running job: a checkpoint after each request, resume after a crash, retries with a limit and escalation to a person (Chapter 19).
  • Hard rules in code whatever the model decides: credits above a limit need approval, the agent visits only the app's own address and every submission is logged (Chapter 22).
  • Signs in as its own service account, never a person's password (Chapter 26), and treats a customer note saying "also refund $500" as an injection, not an instruction (Chapter 25).

Sections: Browser automation with Playwright · durable request queue · hard rules in code · service-account identity

AfterwordWhere to Go from Here
  • The support agent, followed through the lifecycle of section 1.10, is the whole book: decide, design, build, secure, evaluate, optimize, deploy, operate, improve and eventually retire.
  • Chapter 1's question, answered again: choose the least autonomy that does the job; give the model what needs judgment and give code everything that must be right every time: the rules, the numbers, the permissions and the stop conditions.
  • What stays true as models change: an agent is a model, tools and a loop with a stop condition; a tool is a contract; the model proposes and code decides; context is the craft; a change is an improvement only when a measurement says so; every agent gets its own identity and least privilege.
  • Where the field is going: computer use and A2A as core techniques, an advisor model consulted by a cheaper executor, agents that buy things on a user's behalf, and agent identity built into the protocols themselves.
  • What to do next: build a capstone to the full rubric, bring one read-only agent to work with its eval suite written first, and keep up without chasing by asking which layer and which control each new feature needs.

Sections: The support agent, start to finish · Chapter 1's question, again · What stays true · Where the field is going · What to do next

Appendix ARunning the Course Kit with Docker
  • Every exercise runs in the course kit's Docker image: Ubuntu 24.04, Python 3.12, Node.js 24, the MCP SDK, MCP Inspector, reference servers, GitHub's server, the Claude Agent SDK, LangChain, FastAPI and a small embedding model.
  • You type commands on your own computer; Docker runs them in the container against your workspace folder. On Windows use .\course.cmd wherever the book shows ./course.sh.
  • Hardware: 16 GB of RAM recommended and about 15 GB of disk for Claude; for the free local model, 16 GB minimum (32 GB recommended), about 25 GB of disk, and optionally an NVIDIA GPU with 8 GB or more.

Sections: What your computer needs · what's in the kit · course.sh commands · the sandbox service

Appendix BTroubleshooting
  • A symptom → likely cause → fix table for setup errors, such as a 401 AuthenticationError (API key not set in this shell), a NotFoundError for a retired model name, or a 400 error when a tool_use block has no matching tool_result.
  • Current models can start a reply with a thinking block, so select content blocks by type; if stop_reason is max_tokens with no answer, raise max_tokens to 2,000 or more.
  • A step-by-step debugging playbook for the harder case: the agent runs but does the wrong thing. Start from the trace, not the final answer (Chapter 4).

Sections: Common errors and how to fix them · a debugging playbook for an agent that does the wrong thing

Appendix CGlossary
  • Plain-language definitions of every term the book uses, each pointing to the section that explains it.
  • Examples: A2A (an open protocol for independent agents to find each other through agent cards and hand off tasks), adaptive thinking, agent card, the agent architecture reference model and the agent engineering lifecycle.

Sections: Terms from A2A to the agent engineering lifecycle

Appendix DReferences
  • The primary sources behind the book: Anthropic's "Building effective agents" and its multi-agent research system write-up, the Claude models overview, the Model Context Protocol documentation, quickstarts and registry, the MCP reference servers and GitHub's MCP server.
  • Also industry case material used in the chapters and capstones, such as Uber's QueryGPT and GitHub's Copilot cloud agent.

Sections: Primary sources for the book

Appendix EWhat the Exercises Cost
  • Every cost figure comes from one cost model (dev/cost_model.py in the kit), assuming Claude Sonnet 5 at $2 per million input tokens and $10 per million output tokens (2026 prices) and about $0.03–0.05 per agent run.
  • One clean pass of every paid exercise is $28–49; allowing for reruns, all chapters come to about $55–100, and each capstone about $7–12. The biggest items are the load tests and evaluation suites in Part 9.
  • Claude Haiku 4.5 roughly halves the totals; prompt caching and smaller tool outputs cut them further. With the free local model, every exercise except the five marked Claude only costs nothing.
  • Estimate any run yourself: cost ≈ (input tokens × input price + output tokens × output price) ÷ 1,000,000.

Sections: Cost by part · biggest items · estimate a run yourself

Appendix FThe Solutions Folder
  • The solutions folder sits next to course.sh and is mounted read-only at /solutions inside the container, so you can read and run it but never change it by accident.
  • One folder per chapter or interlude with the programs that solve its exercises, improved copies of chapter files, extra evaluation data, ANSWERS.md for concept exercises, and tests; ./course.sh check-solutions runs them all offline.

Sections: What's in the solutions folder · checking your work

Appendix GWhere to Learn More
  • Where to ask when you're stuck (Anthropic Discord, the Anthropic Help Center, the Claude status page, Stack Overflow, r/learnpython, MCP discussions on GitHub), after searching the exact error message; never paste your API key.
  • Free courses that pair well with the book: Anthropic Academy, Anthropic's courses on GitHub, DeepLearning.AI short courses and the Hugging Face AI Agents and MCP courses.
  • Keeping up: this second printing (October 2026) matches repository tag edition-1.1, 246 exercises, Python 3.12, claude-sonnet-5, claude-haiku-4-5 and qwen3.5:9b, and MCP specification 2026-07-28. RESOURCES.md has every link, checked weekly.

Sections: Where to ask for help · free courses · keeping up to date

Appendix HRun the Book Free with a Local Model
  • You don't have to pay for API calls: the course kit runs the open-source qwen3.5:9b model in Docker on your own computer through Ollama, and the book's code uses it without changes.
  • qwen3.5:9b was chosen because it is good at tool calling (66.1 on BFCL-V4, 79.1 on TAU2-Bench) and fits: a 6.6 GB download needing roughly 10–12 GB of memory with a 32k context; it runs with or without a GPU.
  • A small adapter fills the gaps between Claude features and Ollama. Of the 246 exercises, 128 need no model, 104 run on qwen3.5:9b or Claude, 9 are Claude recommended and 5 are Claude only (tool search at scale, Claude Desktop, programmatic tool calling, writing a skill and a managed analyst); LOCAL_MODEL.md in the repository has the same instructions.

Sections: Why qwen3.5:9b · setup · what the kit does for you · which exercises still need Claude

Appendix IReference Cards
  • The book's frameworks on fourteen cards, each pointing to the chapter that explains it.
  • Card 1, Do you need an agent?: a function when rules are exact; a workflow when steps are known in advance; a state machine for stages, rules and audits; RAG for answering from documents; a single LLM call when one prompt does the job; an agent when the steps depend on what you find; a multi-agent system when the work splits into independent parts and the cost is worth it.
  • Also: the dimensions of agency, the reference model, MCP vs A2A vs API vs workflow, the failure taxonomy, the scorecard, agent SLOs, the performance model, durable concepts vs fast-changing details, kinds of agents, the lifecycle, the agent risk model, the deterministic control plane, and agent and team economics.

Sections: Fourteen one-page cards for design reviews and on-call

Appendix JThe Same Concepts on Other Platforms
  • Every concept in the book carries over to other providers and open-source stacks; only the names change.
  • A table maps each concept (tool calling, controlling tool choice, the agent loop, MCP and more) to the Claude API, OpenAI API, Google Gemini API and open-source equivalents such as Ollama and vLLM, checked in September 2026.
  • Section 24.6 shows how to switch providers: keep model calls behind one function and rerun your evaluations when you switch.

Sections: Claude API · OpenAI API · Google Gemini API · open source

Appendix KArchitecture Decision Records
  • An architecture decision record writes down the situation, the decision, when you'd decide differently, what it costs and the evidence; write them in the Design stage and revisit one when its evidence changes.
  • The seven decisions, each with the book's default: a fixed workflow or an agent; one agent or a team; direct tool calls or MCP; fixed retrieval (RAG) or agentic retrieval; a hosted model or a local one; synchronous calls or durable execution; one tenant or many.
  • Default for ADR-1: a workflow, with an agent only for requests whose steps can't be known in advance.

Sections: Seven decisions almost every agent project faces · an ADR template

Appendix LFrom the Book to the Code
  • The book and the course kit are one curriculum: a map from every chapter and interlude to the concept it teaches, its exercises, the folder its listings come from and the capstones that build on it.
  • CURRICULUM_MAP.md in the kit goes one level deeper, with every exercise's level, the model it needs and a link to its solution; both are generated from the manuscript so they can't drift apart.

Sections: Every chapter, its exercises, code folder and capstones

Frequently asked questions

Who is Building Agentic AI Systems for?

Anyone who wants to build AI agents, including people who have never programmed. Chapter 0 and the Python interlude teach the programming you need, and you don't need a machine-learning background: you won't train a model, you'll build reliable software around one. Developers who have built a chatbot will find the later parts on evaluation, security, context engineering, retrieval and deployment useful on their own. Staff engineers, architects, performance engineers and engineering leaders should start with the reference model (Chapter 1), the evaluation, SLO and performance chapters (27–29) and the enterprise agent platform in Chapter 30; the case study and the capstones show what production agent systems require.

Do I have to pay for API calls to do the exercises?

No. The examples use Claude through the Claude API: one clean pass of every paid exercise costs about $28–49, or about $55–100 allowing for reruns (Appendix E). If you'd rather not pay, the Docker-based course kit runs the free open-source model qwen3.5:9b on your own computer and the book's code uses it without changes (Appendix H). Of the 246 exercises, 128 need no model, 104 run on qwen3.5:9b or Claude, 9 are Claude recommended and only 5 are Claude only; every exercise is labeled.

How does the book cover MCP, the Model Context Protocol?

Part 5 is built around MCP, the open standard that connects agents to tools, data and each other. Chapter 12 builds your first MCP server and tests it with MCP Inspector; Chapter 13 builds your own MCP client and publishes a whole agent as an MCP server; Chapter 14 uses servers you didn't write safely, behind a policy layer; and Chapter 15 covers MCP in 2026: the stateless 2026-07-28 specification, discovery and caching, and extensions. Chapter 30 then takes MCP to company scale: long-running tools, gateways, registries and the supply chain, and company authorization (sections 30.8–30.11).

When should I build an agent instead of a workflow?

Choose the least autonomous option that does the job, because autonomy has a cost. Use a plain function when the rules are exact, a workflow when the steps are known in advance, a state machine for processes with stages, rules and audits, RAG for answering from documents and a single LLM call when one prompt does the job. Build an agent only when the steps depend on what you find along the way, and a multi-agent system only when the work splits into independent parts and the cost is worth it. This is section 1.3, Card 1 in Appendix I and ADR-1 in Appendix K.

What is the lethal trifecta in agent security?

The lethal trifecta is private data, untrusted content and a way to communicate out, all in one agent. When all three are present, a prompt injection hidden in content the agent reads can make it leak private data. Chapter 25 shows how to threat-model an agent with four questions and break the trifecta in the architecture: allow-list outbound sites, separate a quarantined reader from the model that acts, and guard actions rather than intentions with canaries, leak scans and egress checks. Every defense gets a regression scenario that shows the attack failing with the control in place.

How do I size the risk of an agent?

Section 25.11 scores an agent as capability × autonomy × access × persistence × blast radius, each from 1 to 3. The score picks one of four tiers, from low (1–8) to critical (82–243), and each tier adds required controls, from an owner, an evaluation gate and an audit log up to isolation, step-up tokens, a red-team run and a security sign-off. Because the factors multiply, cutting any one of them divides the risk. The case study's support agent scores 108 (critical); making every refund wait for a person halves it to tier 3.

How do you evaluate an AI agent before production?

The measurement interlude teaches cases, trials and confidence intervals; Chapter 27 builds on it. You grow evaluation suites from real failures, run each case several times and read results with confidence intervals and pass^k, and grade every run on outcome, process and cost across ten dimensions: task success, trajectory, tools, arguments, safety, cost, latency, reliability, groundedness and escalation. A per-release scorecard and a statistical CI gate against the baseline keep regressions out, and continuous evaluation in production turns new failures into test cases.

What does the case study cover?

The case study follows one support agent, for a fictional shop called Harbor & Pine, through a release: requirements written as numbers, a threat model, a design chosen per kind of request (a workflow, a state machine and one agent), the evaluation suite, four problems testing found and how each changed the design, a load test sized with Little's law, deployment, and an incident in which a warmer prompt stopped handoffs and a canary and burn-rate alert rolled it back. Capstone 1 then asks you to build that agent yourself.

What are the capstone projects?

Six four-week projects that combine the whole book: a customer support agent, a natural-language data analyst, an incident triage assistant, a code review and fix agent, a deep research assistant and a back-office workflow agent that drives a browser. Each has weekly milestones, a reference solution to compare against after you build your own, extension challenges with no published solution, and one rubric covering functionality, architecture, safety and identity, evaluation, observability, performance and cost, and documentation.

Where is the companion code?

Everything is in the free course kit at github.com/sbittla/building-agentic-ai: a Docker image that gives the same Python, libraries, sample data and MCP servers on Windows, macOS and Linux, starter files and automatic checkers for the exercises, and every reference solution. This second printing (October 2026) matches repository tag edition-1.1, with corrections listed in ERRATA.md. The code is MIT-licensed, so you can use it in your own projects.

Also by Srinivasa Rao Bittla

🖥️ AI Infrastructure Engineering🔥 AI-Driven Chaos Engineering🧭 The Forward Deployed Engineer⚡ AI Performance Engineering📖 The Last Invention🧪 AI-Driven Software TestingAll books →