Chapter 9 · 7 lessons
Build Your Own Agents
Go from using agents to shipping them: Claude Agent SDK, OpenAI Agents SDK, Cursor SDK, browser and computer use, A2A for agent-to-agent, and running agents in production.
Claude Code · OpenAI Codex · Cursor · LangChain / LangGraph
Show all 7 lessonsHide list
Lesson 1 of 7
When to Build an Agent (and Which Layer)
You build an agent when a task repeats, needs tools, and does not fit inside an interactive session: a PR reviewer, a nightly dependency updater, a support triage bot, a data-migration assistant. Pick the lowest layer that does the job.
| Layer | Examples | Choose when |
|---|---|---|
| Headless coding CLI | claude -p, codex exec, Cursor CLI | A script or CI step that runs one task in a repo |
| Coding-agent SDK | Claude Agent SDK, Cursor SDK | You want a coding agent's tools and loop inside your own app |
| General agent SDK | OpenAI Agents SDK | Tool-calling agents with handoffs and guardrails, not repo-centric |
| Graph framework | LangGraph | Explicit state, durable checkpoints, human approval steps |
| Plain API calls | Responses / Messages APIs | One or two model calls — no loop needed |
Signal
Say which layer you rejected: 'A LangGraph graph is overkill here; a Claude Agent SDK script with two allowed tools and a turn cap does it.'
Lesson 2 of 7
Claude Agent SDK
The Claude Agent SDK exposes the same agent loop, tools, and context management that power Claude Code, in Python (claude-agent-sdk) and TypeScript (@anthropic-ai/claude-agent-sdk). query() runs a task and streams messages; ClaudeSDKClient keeps a session across turns and supports interrupts.
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Where do we validate session tokens? Cite files.",
options: { allowedTools: ["Read", "Grep", "Glob"] },
})) {
if (message.type === "result") console.log(message.result);
}- allowedTools is your first guardrail — start read-only and add Edit/Bash only when needed
- Hooks, custom tools, MCP servers, subagents, and skills are all configurable in options
- Auth via ANTHROPIC_API_KEY, or Bedrock/Vertex/Foundry through environment settings
- For other languages, run the CLI with -p and --output-format json
Lesson 3 of 7
OpenAI Agents SDK
The OpenAI Agents SDK (Python 'openai-agents', TypeScript '@openai/agents') is a lightweight framework for tool-calling agents. Its core ideas: Agents (instructions + tools), a Runner that executes the loop, handoffs to specialist agents, guardrails that validate input and output, sessions for memory, and built-in tracing.
from agents import Agent, Runner, function_tool
@function_tool
def lookup_order(order_id: str) -> str:
return orders.get(order_id)
billing = Agent(name="Billing", instructions="Resolve billing issues.",
tools=[lookup_order])
triage = Agent(name="Triage", instructions="Route to the right specialist.",
handoffs=[billing])
result = Runner.run_sync(triage, "I was charged twice for order 812")
print(result.final_output)- Handoffs keep each agent's instructions short and focused
- Guardrails run checks in parallel and can stop a run early (tripwires)
- Traces show every model call, tool call, and handoff — use them to debug and to build eval sets
Lesson 4 of 7
Cursor SDK and Cloud Agents API
The Cursor SDK (TypeScript '@cursor/sdk', Python 'cursor-sdk', public beta) runs Cursor agents from your own code, locally against a directory or in the cloud against a cloned repo that can end in a PR. Agent.prompt() is a one-shot; Agent.create() + agent.send() supports streaming and follow-ups; Agent.resume() continues an agent later.
import { Agent } from "@cursor/sdk";
const result = await Agent.prompt("Fix the failing lint errors in src/", {
apiKey: process.env.CURSOR_API_KEY!,
model: { id: "composer-2.5" },
local: { cwd: process.cwd() },
});
process.exit(result.status === "finished" ? 0 : 2);- Always set local or cloud explicitly — local is the silent default
- A thrown CursorAgentError means the run never started; result.status === 'error' means it ran and failed
- Dispose agents (await using / with) so long-running services do not leak processes
- Cloud runs can open PRs automatically; a REST API covers other languages
Lesson 5 of 7
Browser and Computer Use
Some tasks live behind a UI: reproducing a front-end bug, verifying a checkout flow, filling a legacy admin form. Browser and computer-use tools let agents see and act on screens.
| Approach | How it works | Tradeoff |
|---|---|---|
| Browser automation via MCP | Playwright MCP drives a real browser using accessibility snapshots | Reliable and cheap; web only |
| IDE browser tools | Cursor and others give the agent a browser tab for testing | Great for dev loops on your app |
| Computer use | Model sees screenshots and issues mouse/keyboard actions (Anthropic and OpenAI offer these tools) | Works on any UI; slower, costlier, needs strong sandboxing |
Sandbox it
Screens contain untrusted content that can carry prompt injections. Run computer-use agents in a VM or container with no access to your real accounts, and require approval for purchases or messages.
Lesson 6 of 7
A2A, Deployment, and Operating Agents
MCP connects an agent to tools and data. A2A (Agent2Agent) connects agents to other agents across frameworks and vendors. Contributed by Google and now a Linux Foundation project, A2A reached v1.0 in 2026: agents publish an Agent Card at /.well-known/agent-card.json describing skills, endpoint, and auth, then exchange Tasks and Messages over JSON-RPC with streaming and push notifications.
| Protocol | Connects | Example |
|---|---|---|
| MCP | Agent → tools / data | Your agent calls a GitHub or database server |
| A2A | Agent → agent | Your travel agent delegates to a vendor's booking agent |
- Operate agents like services: timeouts, turn caps, budgets, retries only when safe
- Trace every run (LangSmith, OpenAI tracing, harness logs) and keep IDs in your logs
- Version prompts, tools, and models together; eval before rollout
- Least-privilege credentials per agent; humans approve irreversible actions
Put it into practice
The SDK review-agent lab builds a PR reviewer end to end and runs it in CI.
Lesson 7 of 7
Worked Example: A Review Bot the Team Keeps
A team adds an AI reviewer to every PR.
bot: full write access, no turn limit, prompt "review this PR"
PR #481: 23 comments — naming nits, 'consider adding docs',
one real bug buried at #17
team: mutes the bot within a weekscript: Claude Agent SDK, allowedTools [Read, Grep, Glob], maxTurns 12 skill: team checklist (security, error paths, tests, migrations) rule: max 5 findings, file:line + severity + fix, else "LGTM" CI: one sticky comment; skipped for fork PRs metric: 2 weeks → 61% of findings acted on
- Least privilege and a turn cap bounded risk and cost
- A checklist skill replaced a vague 'review this' prompt
- A cap on findings forced prioritization; a metric proved value
Takeaway
Agents you ship are products. Scope them, measure them, and tune them.