Most guides on how to build AI agents with Claude start with a framework. The agents we actually run started with a cron line and a Python script, and Claude only gets called for the one step a script cannot do.
- An agent is a model, tools and a loop. Claude asks for a tool, your code runs it, the result goes back, and it repeats until the task is done.
- There are three ways to build one with Claude: the Messages API with your own loop, the Agent SDK, or Claude Code run non-interactively with
claude -p. - Most useful agents are mostly not AI. Ours are a scheduled job, a deterministic script, one Claude call for the judgement step, and a report committed to git.
- Limits belong in code. A prompt that says "never exceed the budget" is a request. A validator that rejects the action is a rule.
- A subscription is not an API key. Scripts that call the API need a Claude Console key stored as a secret.
- A manual run passing proves nothing about the schedule. One of our agents passed every manual test and failed its first three scheduled runs.
This post teaches the mechanics from Anthropic's documentation as it stands in November 2026, then shows the shape we use in production on our own site. If the vocabulary is new, start with AI agents explained, which is the hub for this whole section.
What you are actually building
Anthropic's Agent SDK docs define the thing plainly: "An agent is an application that completes a task by planning its own steps and calling tools that read files, run commands, or edit code." Three parts carry that sentence:
- The model decides what to do next.
- Tools are functions the model may ask for: read a file, query a database, fetch a URL, send an email.
- The loop feeds each tool's result back so the model can decide the next step.
A chatbot stops after one reply. An agent keeps going until the job is finished or something stops it. That "something" is the part you design: a turn limit, a permission list, a budget check, a person.
Anthropic's own comparison table lists four ways to get there. Trimmed to what matters when choosing:
| You want to | Use | Who writes the loop |
|---|---|---|
| Call the Claude API from your own code | Client SDK (Messages API) | You, or the SDK's beta tool runner |
| Embed Claude Code's agent in your own Python or TypeScript app | Agent SDK | The SDK |
| Run one-off or scripted tasks from a terminal or CI | Claude Code CLI with -p |
Claude Code |
| Have Anthropic host the agent | Managed Agents | Anthropic |
We have production experience with the first row and daily interactive use of Claude Code. The Agent SDK and Managed Agents sections below are documentation only: we have not run them in production.
Route one: the Messages API and your own loop
This is the "from scratch" route and the one worth understanding even if you never ship it, because every other route is this loop with more furniture.
Anthropic's tool use documentation describes the round trip. You pass a tools list. When Claude wants one, the response comes back with stop_reason: "tool_use" and one or more tool_use blocks. Your code runs the operation and sends back a tool_result. Tools you define run in your application; Anthropic calls these client tools. Server tools such as web_search, web_fetch and code_execution run on Anthropic's side and need no handler.
Install the SDK and set a key from the Claude Console:
pip install anthropic
export ANTHROPIC_API_KEY="your-console-key"
Then the loop. This follows the documented shape, wrapped in a while so it handles more than one tool call:
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
tools = [{
"name": "get_page_title",
"description": "Return the <title> of a page on our site, given its path.",
"input_schema": {
"type": "object",
"properties": {"path": {"type": "string", "description": "e.g. /services/"}},
"required": ["path"],
},
}]
def run_tool(name, args):
if name == "get_page_title":
return lookup_title(args["path"]) # your own code
return f"unknown tool: {name}"
messages = [{"role": "user", "content": "Which service pages have titles over 60 characters?"}]
for turn in range(10): # your limit, not the model's
response = client.messages.create(
model="claude-opus-5-5", # the ID in Anthropic's examples today; check the models page
max_tokens=1024,
tools=tools,
messages=messages,
)
if response.stop_reason != "tool_use":
break
messages.append({"role": "assistant", "content": response.content})
results = [
{"type": "tool_result", "tool_use_id": block.id,
"content": run_tool(block.name, block.input)}
for block in response.content if block.type == "tool_use"
]
messages.append({"role": "user", "content": results})
print(next(b.text for b in response.content if b.type == "text"))
Four things in that snippet are doing safety work, and all four are yours:
- The description is the interface. Claude decides when to call a tool from its description. Vague descriptions produce wrong calls.
run_toolis the only place anything happens. The model can ask for anything. It can only get what that function is willing to do.- The
range(10)is a stop rule. Without it, a confused agent can loop until the bill arrives. stop_reasonis checked. We learned this one the hard way, further down.
The docs also mention a tool runner in the client SDKs that drives this loop for you (the Agent SDK overview calls it beta), and strict: true on a tool definition to guarantee calls match your schema.
Route two: the Claude Agent SDK
If your agent's job involves files and shell commands, writing those tools yourself is wasted effort. The Agent SDK "gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript." The docs describe it as a library that runs the Claude Code binary, and both packages bundle that binary in most installs.
Install, per the quickstart (Python 3.10+ or Node.js 18.14+):
pip install claude-agent-sdk
# or
npm install @anthropic-ai/claude-agent-sdk
The quickstart's first agent, lightly trimmed:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async def main():
async for message in query(
prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob"], # pre-approved tools
permission_mode="acceptEdits", # auto-approve file edits
),
):
if isinstance(message, ResultMessage):
print(f"Done: {message.subtype}")
asyncio.run(main())
No tool definitions, no loop. query() returns an async iterator and the SDK handles "the orchestration, tool execution, context management, and retries."
Two details from the docs that matter before you rely on it:
allowed_toolspre-approves; it does not restrict. The quickstart is explicit that to limit the agent to a set of built-in tools you pass that set astools. A read-only agent should be givenRead,GlobandGrepand nothing else.- It loads your Claude Code configuration. The capabilities table says skills, commands and memory "load automatically from your project's
.claude/and from~/.claude/, same as Claude Code." Useful on your laptop, surprising on a server.
Authentication is an API key in ANTHROPIC_API_KEY. The SDK does not read .env files for you. And the docs carry a note worth quoting if you are building a product: "Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK."
Route three: Claude Code without the terminal session
If you already use Claude Code interactively, the shortest path to an unattended agent is the same binary with -p. The programmatic usage page covers it:
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
The flags that turn a chat tool into a script component:
# Same result on every machine: skip local hooks, plugins, MCP servers, memory and CLAUDE.md
claude --bare -p "Summarize README.md" --allowedTools "Read"
# Machine-readable output, with a schema
claude -p "Extract the main function names from auth.py" \
--output-format json \
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'
# Narrow shell permissions instead of all of Bash
claude -p "Look at my staged changes and create an appropriate commit" \
--allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"
# Nobody is there to answer prompts
claude -p "Update the dependency pins and run the tests" \
--permission-mode auto --permission-prompts none
Read the bare-mode section before you put this in CI. Without --bare, the docs say a -p session "runs the hooks in a project's .claude/settings.json and connects the servers in its .mcp.json, even in a folder you've never trusted." With it, Claude Code never reads OAuth credentials, so you must supply ANTHROPIC_API_KEY. Anthropic calls --bare "the recommended mode for scripted and SDK calls" and says it will become the default for -p in a future release.
For a schedule, there are two documented options. The Claude Code GitHub Action runs on any GitHub event, including cron:
name: Daily Report
on:
schedule:
- cron: "0 9 * * *"
jobs:
report:
runs-on: ubuntu-latest
permissions:
contents: read
issues: read
id-token: write
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: "Generate a summary of yesterday's commits and open issues"
claude_args: |
--allowedTools "mcp__github__list_commits,mcp__github__list_issues"
That is the docs' own example with the model line removed. Set --max-turns in claude_args and a workflow timeout to cap a runaway job. The other option is cloud scheduled tasks, formerly called routines: a saved prompt, repositories and connectors that run on Anthropic's infrastructure on a schedule, an API call or a GitHub event. As of November 2026 the page labels them a research preview, available on paid plans, created at claude.ai/code/routines or with /schedule. Documentation only on both: our scheduled agents predate them and use plain Python. How we work with Claude Code day to day is in how to use Claude Code effectively.
The shape we run in production
Our agents live in the same repository as our website. None of them is a free-running loop. Each one is five boring parts:
- A scheduled job. A GitHub Actions workflow with a cron trigger.
- A deterministic script. Python that gathers facts and computes every number.
- One Claude API call for the judgement step. Classification, a quality score, a short paragraph.
- A committed report. The output lands in git, where it has a date and a diff.
- A human gate. Somebody reads it before anything consequential changes.
The SEO audit is the clearest example. The workflow is thirty lines of setup around this:
# .github/workflows/seo-audit.yml
on:
schedule:
- cron: '0 11 15,30 * *' # 15th and 30th, 11:00 UTC
workflow_dispatch:
permissions:
contents: write # so the job can commit the report
jobs:
audit:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
# ... set up Python, install deps ...
- name: Run SEO audit
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: python3 _local/seo/audit.py
audit.py reads every post and counts the mechanical things in plain Python: title length, description length, word count, headings, internal links, whether sources are declared. That static part is worth 70 of the 100 points. Then it asks Claude for the 30 that need reading: which content silo the post belongs to, a quality score out of ten, and up to five recommendations. The call asks for JSON against a schema, with the taxonomy in a cached system block so repeated posts do not pay for it again:
# _local/seo/audit.py: claude_audit_post()
message = client.messages.create(
model=MODEL,
max_tokens=2500,
thinking={"type": "adaptive"},
output_config={
"effort": "medium",
"format": {"type": "json_schema", "schema": POST_AUDIT_SCHEMA},
},
system=system_blocks, # silo taxonomy, cache_control: ephemeral
messages=[{"role": "user", "content": user}],
)
That is copied from our running code, which was written against an earlier API version; check the current parameter names before borrowing it. The point is the division of labour. Thirteen reports sit in the repository as of this week. The full build is in building a daily SEO audit agent, which still describes the original daily schedule.
Notice there is no tool loop. The model is not choosing which files to read. The script reads all of them and asks one bounded question about each. Reach for a loop only when the next step really depends on what the last one found.
Put the numbers in code, not in the prompt
The second agent writes a daily operations email. Its first version handed the model a pile of raw figures and a list of instructions about what it must not say. The docstring of the rewrite records why that changed: "A prompt is not a guarantee."
The current version computes and formats every number in Python. Claude receives finished strings and writes at most two sentences on top:
# _local/agent/daily_report.py
def build_facts(ctx: dict) -> list[str]:
"""Pre-formatted strings. The model may quote these and nothing else."""
...
def write_note(ctx, action, model):
"""Ask Claude for the judgement paragraph. Never fatal: any failure returns
(None, None) and the deterministic email ships unchanged."""
try:
client = Anthropic()
facts = "\n".join(f"- {x}" for x in build_facts(ctx))
msg = client.messages.create(
model=model, max_tokens=220,
system=[{"type": "text", "text": VOICE,
"cache_control": {"type": "ephemeral"}}],
messages=[{"role": "user", "content": prompt}],
)
...
except Exception as e:
return None, None
Three rules from that file transfer to any agent:
- Unknown is not zero. If a value cannot be sourced, the script prints why it is missing. A model handed a blank will happily narrate a zero.
- The model is optional. No key, or an API error, and the report still sends. The AI step adds judgement; it must never be the thing that blocks the facts.
- Configuration that reaches the prompt is behaviour. A limit enforced in one field and described in another drifts. If the description is what the model reads, the model follows the stale one.
The approval gate, and what broke without one
Our most ambitious agent managed our own search ads. Each morning it read performance data, asked Claude for proposed moves, re-validated every proposal against rails written in code (a spend ceiling, a bid clamp, an edit-freeze window, a list of protected campaigns), ran the ad platform's own dry-run, and only then applied anything. In its cautious mode it wrote proposals to a review queue instead, and a person approved them by number. Approval chose which proposals the rails got to judge. It could not overrule them.
The engineering held. The program did not: we ended our ad spend in September 2026 after it produced three attributed leads and no clients, and the optimiser is switched off. We wrote up the buyer's side of that in AI agents for business. The builder's lessons are narrower and they are the useful part here:
- It passed every manual test and failed its first three scheduled runs. The response was capped at a small
max_tokens, the model's reasoning used the budget, and the JSON arrived cut off. Nothing checkedstop_reason. The manual runs happened to fit. Fix: a far higher cap, and a hard failure on amax_tokensstop. - It invented a landing page. A proposed ad pointed at a URL that did not exist. Fix: a function that requests every proposed URL and rejects anything that is not a 2xx or 3xx. Telling the model to use real pages had not been enough.
- Its own housekeeping locked it out. Harmless actions were exempt from the edit freeze but still counted as edits when the freeze was calculated, so the agent re-armed the freeze against itself and was rejected eight runs in a row. We found it by reading the action log, where the same rejection string repeated.
- Nothing alerted on failure for four days. A scheduled job that fails silently is worse than no job. We added a step that opens an issue when a scheduled run fails, and a separate canary that complains when the SEO report is more than 18 days old.
- The stop rule lived in a comment. There was a test for "this is not working", and it was never executable. A stop rule counts when it is in code, runs on the schedule, and its consequence is a pause.
A first agent you can build this week
In order:
- Choose a read-only job with a checkable answer. Broken links, missing descriptions, pages that changed since last week.
- Write the deterministic part first and run it by hand. If plain code can answer the whole question, you do not need an agent, and that is a good outcome.
- Add one Claude call for the part that needs reading comprehension. Ask for structured output. Check
stop_reason. - Get a Console API key and store it as a repository secret named
ANTHROPIC_API_KEY. Keep it out of your shell profile: Claude Code will offer to use a key it finds there, and then your interactive sessions bill the API instead of your plan. - Commit the report, one file per run, named by date.
- Schedule it, then check the scheduled run specifically. Ours start one to three hours after the cron time on GitHub's shared runners, so nothing downstream assumes punctuality.
- Add a staleness check that alerts when the newest report is too old.
- Only then add write access, one narrow action at a time, each behind a validator and, where the blast radius is real, a person.
To package the instructions for Claude Code, see Claude skills and Claude Code hooks.
Knowing how to build AI agents with Claude is mostly knowing where not to use Claude. Let code count, let the model read, let git remember, and let a person decide anything you could not undo. If you would like that shape built around your own site or back office, it is the core of our AI integration work, and you can tell us what you would hand to an agent first.
Common questions
How to build AI agents with Claude?
Pick one of three routes. Call the Messages API with a tools list and write the loop yourself: Claude answers with a tool_use block, your code runs the tool and returns a tool_result, and you repeat until it stops asking. Use the Claude Agent SDK if you want Claude Code's built-in file, shell and search tools inside your own Python or TypeScript program. Or run Claude Code itself non-interactively with claude -p from a script or CI job. Start with the smallest one that does the job, and put every limit that matters in code.
How to build AI agents in Claude Code?
Claude Code is already an agent, so building one in it mostly means packaging instructions and running them unattended. Write the task as a prompt or a skill, then run it with claude -p and an explicit --allowedTools list so it can finish without permission prompts. Anthropic's docs recommend adding --bare for scripts and CI so the run does not load whatever hooks, plugins or CLAUDE.md happen to be on that machine. For a recurring job, use the Claude Code GitHub Action with a cron trigger, or a cloud scheduled task.
How to build AI agents from scratch?
From scratch means the Messages API and a while loop. Define each tool with a name, a description and a JSON input schema. Send the conversation. If the response's stop_reason is tool_use, run each requested tool, append the results as tool_result blocks, and call the API again. Stop when Claude answers in plain text or when you hit your own turn limit. That is the whole mechanism. Everything else, such as retries, logging, permissions and memory, is ordinary software you add around the loop.
How to build AI agents without coding?
You can get a long way with Claude Code and plain English. Describe the job, let Claude Code write the script and the workflow file, and review what it produced. As of November 2026 Anthropic also documents cloud scheduled tasks, a research-preview feature that saves a prompt, a repository and connectors and runs them on a schedule, created at claude.ai/code/routines or with /schedule. You still need to read the output and decide what the agent may change. Skipping the code does not skip the judgement.
How to build AI agents for beginners?
Build a read-only agent first. Give it one job, such as checking every page of a site for a missing description, and let it write a report to a file. Do the checking in ordinary code and use Claude only for the part that needs reading comprehension. Run it by hand until the report is boring and correct. Then schedule it. Add the ability to change things last, one narrow action at a time, each behind a validation step or a person's approval.
Do I need an API key to build agents with Claude, or is a subscription enough?
For code that calls the Messages API or the Agent SDK you need an API key from the Claude Console. A Claude subscription covers the apps and Claude Code; it does not hand you a key, and Anthropic's Agent SDK docs say third-party developers may not offer claude.ai login in their products without approval. The one overlap is Claude Code in CI: the GitHub Action accepts either an API key or a long-lived token generated with claude setup-token on a paid plan. Check the vendor pages for current plan terms.
What is the difference between the Claude Agent SDK and the Messages API?
The Messages API gives you the model and a tools parameter, and you write the loop and every tool. The Agent SDK is a library that runs the Claude Code binary, so file reading, editing, shell commands, permissions, sessions, hooks and subagents come built in. Anthropic's comparison table puts it this way: use the client SDK to call the API directly and write the tool loop yourself, and the Agent SDK to embed Claude Code's agent in a process you operate. Managed Agents is the hosted third option.

