Reader companion · Second printing, Oct 2026 · Hands-on · Python · MCP
“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
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
Every answer is grounded in the book’s chapters with specific section citations.
Choose an example question above, or type your own.
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.
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.
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
Sections: Six features, one file · The one pattern to understand deeply
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
Sections: A test is a function that asserts · The five patterns you'll use · Good tests
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
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
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
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
Sections: The pieces · The four functions
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?
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
Sections: Eight queries, each building on the last · Reading someone else's SQL
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
Sections: Cases, trials and margins · Reading the results
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
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
Sections: Waiting without blocking · The five ideas · Reading async agent code
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
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
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
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
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
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
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
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
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
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
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?
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
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
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
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
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
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
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
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
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
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
Sections: helpdesk, orders and handoff MCP servers · returns within policy · memory policy · human handoff
Sections: Read-only warehouse MCP server · business definitions · table confirmation · self-correction · charts
Sections: logs, metrics, git and runbooks servers · parallel subagents · statistics in code · structured triage report
Sections: GitHub MCP server · scoped tokens · tests in a no-network sandbox · structured review · resumable fix harness
Sections: Lead planner · parallel subagents · fetch, library and memory servers · claim verification · critic pass
Sections: Browser automation with Playwright · durable request queue · hard rules in code · service-account identity
Sections: The support agent, start to finish · Chapter 1's question, again · What stays true · Where the field is going · What to do next
Sections: What your computer needs · what's in the kit · course.sh commands · the sandbox service
Sections: Common errors and how to fix them · a debugging playbook for an agent that does the wrong thing
Sections: Terms from A2A to the agent engineering lifecycle
Sections: Primary sources for the book
Sections: Cost by part · biggest items · estimate a run yourself
Sections: What's in the solutions folder · checking your work
Sections: Where to ask for help · free courses · keeping up to date
Sections: Why qwen3.5:9b · setup · what the kit does for you · which exercises still need Claude
Sections: Fourteen one-page cards for design reviews and on-call
Sections: Claude API · OpenAI API · Google Gemini API · open source
Sections: Seven decisions almost every agent project faces · an ADR template
Sections: Every chapter, its exercises, code folder and capstones
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.