This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Lab 2 — Build Your Own Agent Harness

Eight incremental steps from one API call to a working harness — tools, the loop, context management, subagents, model routing, permissions, and MCP — checked against Claude Code at every step.

Goal

Using Claude Code every day teaches you what an agent does. This lab teaches you why, by building the same machine yourself. Six ideas carry the whole field:

  • Tool use: how a model acts on files, terminals and other systems.
  • The agentic loop: reason, act, observe, repeat.
  • Context management: keeping the window useful as it fills.
  • Subagents: delegating independent work to a fresh context.
  • Model selection: trading capability against speed and cost.
  • The harness: the runtime, permissions and controls around all of it.

They are not six separate topics. They are six views of one loop, and each one exists because of a problem the previous one creates:

flowchart LR
    S1[1 Stateless call] --> S2[2 One tool] --> S3[3 The loop] --> S4[4 Context management]
    S4 --> S5[5 Subagents] --> S6[6 A model per role] --> S7[7 Harness controls]
    S7 --> S8[8 MCP and the Agent SDK]

You build one Python file, agent.py, in that order. It ends at about 200 lines. After every step you look at the same mechanism inside Claude Code, using its own traces, so the tool you use daily becomes something you can read instead of a black box.

The finished code, with offline tests, is in labs/agent-harness/ in this vault’s repository. Read it after you have written your own version, not before.

Prerequisites:

  • Python 3.11+ and an Anthropic API key.
  • Claude Code installed.
  • In a virtual environment: pip install anthropic "mcp>=2.3" claude-agent-sdk pytest. Keep it activated, so the agent’s shell finds pytest too.
  • The concepts from the Agents thread. This lab links the theory instead of repeating it.

Pace: one step per week is a good rhythm, which makes the whole lab two months of evenings. The point is not to finish. The point is to break each step on purpose before you move on.

How each step works

Each step is one page with the same shape:

  1. The question at the top. You should be able to answer it by the end of the page.
  2. Build: only what is new in agent.py.
  3. Check: what you should see when it works.
  4. See it in Claude Code: where the same mechanism shows up in the tool you already use.
  5. Break it: one deliberate failure. Most of the learning happens here.
  6. Answer: try your own answer before you read it.

The project

The agent works on a tiny project with two files and two bugs:

# sandbox/calc.py
def average(xs):
    return sum(xs) / len(xs) - 1
# sandbox/test_calc.py
from calc import average

def test_average():
    assert average([2, 4]) == 3

def test_empty_list_is_zero():
    assert average([]) == 0

The eight steps

StepYou buildYou see in Claude Code
1 — A stateless callA chat loop over a message list you keepSession transcripts in ~/.claude/projects/
2 — One toolOne tool_use → tool_result round trip by hand/context and the cost of tool definitions
3 — The loopFour tools, parallel calls, errors as results, max_turnsA PostToolUse hook log; stream-json output
4 — Context managementClipping, just-in-time reads, AGENT.md, caching, compaction/context, /compact, CLAUDE.md, tool-results/
5 — Subagentsdelegate(): a fresh run() with fewer tools.claude/agents/*.md and subagents/ transcripts
6 — A model per roleTraces and a benchmark across models and effort/model and model: in subagent files
7 — Harness controlsPermission rules, hooks, saved sessionsallow / ask / deny, permission modes, --resume
8 — Plug-ins, and the real thingAn MCP server, then the agent on the Agent SDKclaude mcp add, /mcp

Debug any agent with four questions

From now on, when Claude Code or your own agent goes wrong, open the trace, find the first turn where it went off course, and ask in order:

  1. Missing context? It didn’t know something it needed, or the thing it needed was buried. Go back to step 4.
  2. Bad tool? The description misled it, the output was too big, or an error was swallowed. Go back to steps 2 and 3.
  3. Weak model? It had the facts and the tools and still reasoned badly. Go back to step 6.
  4. Missing harness constraint? It did something it should never have been able to do. Go back to step 7.

Most failures that look like “the model is dumb” turn out to be the first two.

Where this setup tops out

  • This is Level 1, one agent working for one person. Running many agents on a real codebase, with parallel work in isolated git worktrees, orchestration and review, is Lab 4.
  • Nothing here checks that the output is good. Passing tests are one signal. Evaluating what an agent produces is Lab 3.
  • Regex permissions are not a sandbox. For anything you didn’t write yourself, run the agent in a container with no credentials.
  • In production you would use the platform’s server-side compaction and context editing rather than compact(). Building compact() by hand is how you learn what those do.

Sources

1 - Step 1 — A stateless call

One API call and a list of messages you keep — why a stateless model seems to remember.

Start with no tools and no loop: a single API call with a list of messages that you keep.

By the end of this step you should be able to answer: the API stores nothing between calls, so why does the model seem to remember?

Build

# step1.py
import anthropic

client = anthropic.Anthropic()
MODEL = "claude-opus-5-5"

def text_of(r):                       # content can also hold thinking blocks: keep only text
    return "".join(b.text for b in r.content if b.type == "text")

msgs = []
while True:
    msgs.append({"role": "user", "content": input("you> ")})
    r = client.messages.create(model=MODEL, max_tokens=16000, messages=msgs)
    msgs.append({"role": "assistant", "content": r.content})   # all blocks, unchanged
    print(text_of(r), f"\n[input_tokens={r.usage.input_tokens}]")

Check

Tell it your name, then ask for it back. input_tokens grows every turn, because every turn sends the whole conversation again.

See it in Claude Code

Your sessions are stored as JSONL at ~/.claude/projects/<project>/<session-id>.jsonl, where <project> is the working directory with every non-alphanumeric character replaced by -. Lines of type user and assistant carry a message with the same role and content shape you just built. Read one session top to bottom. The format is internal and changes between versions, so read it but don’t build on it.

Break it

Send only the last message instead of msgs. The “memory” disappears at once.

Answer

It doesn’t remember. Your code sends the whole conversation every time, and the context window is all the model knows on that turn.

Next: Step 2 — One tool

2 - Step 2 — One tool

A tool is a name, a description and a schema; the model asks, your code acts.

A tool is a name, a description and a JSON schema. The model never runs anything. It asks, and your code decides what happens.

By the end of this step you should be able to answer: who executes the tool, and what is a tool description really?

Build

# step2.py
import pathlib
import anthropic

client = anthropic.Anthropic()
MODEL = "claude-opus-5-5"
TOOLS = [{
    "name": "read_file",
    "description": "Read a text file from the project and return its full contents. "
                   "Use it before answering any question about what a file contains.",
    "input_schema": {"type": "object",
                     "properties": {"path": {"type": "string",
                                             "description": "Path relative to the project root"}},
                     "required": ["path"]},
}]

msgs = [{"role": "user", "content": "What does sandbox/calc.py do? Is it correct?"}]
r = client.messages.create(model=MODEL, max_tokens=16000, tools=TOOLS, messages=msgs)
print(r.stop_reason)                                  # tool_use: the model is asking
call = next(b for b in r.content if b.type == "tool_use")
print(call.name, call.input)                          # read_file {'path': 'sandbox/calc.py'}

output = pathlib.Path(call.input["path"]).read_text()  # YOUR code runs the tool
msgs += [{"role": "assistant", "content": r.content},
         {"role": "user", "content": [{"type": "tool_result", "tool_use_id": call.id,
                                       "content": output}]}]
r = client.messages.create(model=MODEL, max_tokens=16000, tools=TOOLS, messages=msgs)
print("".join(b.text for b in r.content if b.type == "text"))

Check

The first response stops with tool_use and has no answer in it. The second one finds the off-by-one bug, using text that only your code could have read.

See it in Claude Code

Every tool definition is part of the prompt on every turn. Run /context to see what is using the window before you have typed anything, then connect one more MCP server and run it again.

Break it

Change the description to "Reads stuff" and ask questions that need two files, and watch it guess instead of reading. Then return "Error: no such file" for a real path and watch it recover, or give up.

Answer

Your code executes the tool, every time. A tool description is prompt text, and the model decides whether and how to call the tool from that text alone.

Next: Step 3 — The loop

3 - Step 3 — The loop

Step 2 in a while loop — four tools, parallel calls, errors as observations, and a brake.

An agent is step 2 in a while loop.

By the end of this step you should be able to answer: who decides that the work is finished, and who decides that it must stop?

Build

Start agent.py with four tools and the loop:

# agent.py
import json, os, pathlib, re, subprocess, threading
from concurrent.futures import ThreadPoolExecutor
import anthropic

client = anthropic.Anthropic()
MODEL = "claude-opus-5-5"
WORKDIR = pathlib.Path(os.environ.get("WORKDIR", "sandbox")).resolve()

SYSTEM = """You are a coding agent working in a small project.
Inspect before you change anything, and verify your work by running the tests before you finish.
Prefer `grep -n` and `sed -n` through run_bash over reading whole large files."""

def text_of(r):
    return "".join(b.text for b in r.content if b.type == "text")

def list_files(path):
    root = WORKDIR / path
    return "\n".join(sorted(str(p.relative_to(WORKDIR)) for p in root.rglob("*") if p.is_file()))

def read_file(path):
    return (WORKDIR / path).read_text()

def write_file(path, content):
    (WORKDIR / path).write_text(content)
    return f"wrote {len(content)} chars to {path}"

def run_bash(command):
    p = subprocess.run(command, shell=True, cwd=WORKDIR, capture_output=True, text=True, timeout=60)
    return f"exit={p.returncode}\n{p.stdout}{p.stderr}"

def tool(fn, description, **params):
    return {"name": fn.__name__, "description": description,
            "input_schema": {"type": "object",
                             "properties": {k: {"type": "string", "description": v}
                                            for k, v in params.items()},
                             "required": list(params)}}

TOOLS = [
    tool(list_files, "List every file under a directory of the project.",
         path="Directory relative to the project root; use . for the root"),
    tool(read_file, "Read a whole text file. For large files prefer run_bash with grep or sed -n.",
         path="File path relative to the project root"),
    tool(write_file, "Create or overwrite a file with the given content.",
         path="File path relative to the project root", content="The complete new file content"),
    tool(run_bash, "Run a shell command in the project root and return exit code, stdout and stderr.",
         command="The command, for example: python -m pytest -q"),
]
FUNCS = {"list_files": list_files, "read_file": read_file,
         "write_file": write_file, "run_bash": run_bash}

def execute(call):
    try:
        out, failed = FUNCS[call.name](**call.input), False
    except Exception as e:                   # errors are observations, not crashes
        out, failed = f"{type(e).__name__}: {e}", True
    return {"type": "tool_result", "tool_use_id": call.id,
            "content": out or "(empty)", "is_error": failed}

def run(task, tools=TOOLS, model=MODEL, max_turns=25):
    msgs = [{"role": "user", "content": task}]
    for turn in range(max_turns):                         # the brake
        r = client.messages.create(model=model, max_tokens=16000, system=SYSTEM,
                                   tools=tools, messages=msgs)
        msgs.append({"role": "assistant", "content": r.content})
        if r.stop_reason != "tool_use":                   # end_turn, max_tokens, refusal...
            return text_of(r)
        calls = [b for b in r.content if b.type == "tool_use"]     # may be several
        msgs.append({"role": "user", "content": [execute(c) for c in calls]})
    return f"Stopped after max_turns={max_turns} without finishing."

if __name__ == "__main__":
    import sys
    print(run(" ".join(sys.argv[1:]) or "Make the tests pass. Run them with: python -m pytest -q"))

Three details carry most of the weight here:

  • One response can hold several tool_use blocks. All their results go back in one user message.
  • A failing tool returns is_error: true and the error text instead of crashing the program. The model reads the error and adapts.
  • max_turns is the brake. The model decides when it is done. The harness decides when it must stop.

Check

Run python agent.py. The agent runs the tests, reads calc.py, rewrites it, runs the tests again and stops with both passing. No line of your code knew the steps in advance.

See it in Claude Code

Add a PostToolUse hook to .claude/settings.json that logs every tool call (it needs jq), then tail -f ~/claude-tool-log.jsonl while you work:

{
  "hooks": {
    "PostToolUse": [
      { "matcher": "*",
        "hooks": [{ "type": "command", "command": "jq -c . >> \"$HOME/claude-tool-log.jsonl\"" }] }
    ]
  }
}

Each line has tool_name, tool_input and tool_response. It is your execute(), seen from the outside. For the whole loop as a stream of events, run claude -p "make the tests pass" --output-format stream-json --verbose.

Break it

Give it an impossible task ("make test_empty_list_is_zero pass without editing calc.py") with max_turns=100, and watch it go round in circles. Then raise an exception inside execute() instead of returning it, and see the whole run die on the first mistake.

Answer

The model decides it is finished by not asking for a tool (end_turn). The harness decides it must stop with max_turns and budgets. You need both: without the brake, a model that never says it is done runs for ever.

Next: Step 4 — Context management

4 - Step 4 — Context management

Clip, retrieve just in time, remember, cache, compact — and why history must be append-only.

Every turn adds to msgs, and nothing ever leaves. Context engineering is the work of keeping that window small and useful.

By the end of this step you should be able to answer: why can more context make an agent worse, and why must the history be append-only?

Build

Add four techniques:

CLIP_AT = 4_000          # characters one tool result may put into the context
COMPACT_AT = 60_000      # tokens of context that trigger compaction

def clip(call_id, out):
    if len(out) <= CLIP_AT:
        return out
    spill = WORKDIR / ".tool-results" / f"{call_id}.txt"
    spill.parent.mkdir(exist_ok=True)
    spill.write_text(out)
    return (out[:CLIP_AT] + f"\n[... {len(out) - CLIP_AT} more characters. Full output saved to "
            f".tool-results/{call_id}.txt; search it with run_bash grep instead of reading it whole.]")

def system_prompt():
    notes = WORKDIR / "AGENT.md"           # project memory, loaded once per session
    return SYSTEM + (f"\n\n# Project notes\n{notes.read_text()}" if notes.exists() else "")

def context_size(u):
    return u.input_tokens + (u.cache_read_input_tokens or 0) + (u.cache_creation_input_tokens or 0)

SUMMARIZE = """Summarize this session so a fresh context can continue it without redoing work:
the task, decisions and constraints, what was tried and what failed, the current state of the
files, and what is left to do. Keep names, paths, numbers and error messages exact.
Do not call any tools; respond with text only."""

def compact(task, msgs, system, tools, model):
    # Only called right after a full tool round, so no tool_use is left waiting for its result.
    ask = msgs[:-1] + [{"role": "user", "content": msgs[-1]["content"] + [{"type": "text", "text": SUMMARIZE}]}]
    r = client.messages.create(model=model, max_tokens=16000, system=system, tools=tools,
                               messages=ask, cache_control={"type": "ephemeral"})  # same prefix: cache hit
    return {"role": "user", "content": f"{task}\n\n# Progress so far\n{text_of(r)}\n\nContinue from here."}

In execute(), pass the output through clip() before you return it. Then change run():

def run(task, tools=TOOLS, model=MODEL, max_turns=25):
    system = system_prompt()                              # built once: frozen for the session
    msgs = [{"role": "user", "content": task}]
    for turn in range(max_turns):
        r = client.messages.create(model=model, max_tokens=16000, system=system, tools=tools,
                                   messages=msgs, cache_control={"type": "ephemeral"})
        print(f"turn {turn}: context={context_size(r.usage)} cached={r.usage.cache_read_input_tokens}")
        msgs.append({"role": "assistant", "content": r.content})
        if r.stop_reason != "tool_use":
            return text_of(r)
        calls = [b for b in r.content if b.type == "tool_use"]
        msgs.append({"role": "user", "content": [execute(c) for c in calls]})
        if context_size(r.usage) > COMPACT_AT:
            msgs = [compact(task, msgs, system, tools, model)]
    return f"Stopped after max_turns={max_turns} without finishing."

Each technique answers a different problem:

TechniqueProblem it solves
clip() + spill to a fileOne huge tool output swamps the window. Keep a preview and a pointer to the rest.
grep and sed -n in the system promptJust-in-time retrieval: fetch the three lines you need, not the whole file.
AGENT.mdKnowledge that should survive between sessions: memory loaded once at the start.
cache_controlThe repeated prefix is billed and processed again every turn. Caching makes re-reading it cheap and fast.
compact()The history outgrows the window. Replace all of it with a summary and start clean.

Caching only works if the prefix stays byte-identical: the same system, the same tools, and earlier messages left alone. So the harness builds the system prompt once and only ever appends to msgs. The compaction shape follows the same rule. It replaces the whole history with one summary and replays nothing older. On current models a thinking block is valid only in the conversation that produced it, so “summarize the old turns but keep the recent ones verbatim” can be rejected outright.

Check

Run the agent with WORKDIR pointing at a copy of this vault’s content/ and a question that needs several big files. From the second turn on, cached should cover most of context. Lower COMPACT_AT to 8,000 and watch context drop back after a compaction while the agent carries on.

See it in Claude Code

  • /context shows what is using the window, including which CLAUDE.md files loaded. CLAUDE.md is your AGENT.md.
  • /compact focus on the failing test is your compact(), with instructions. Claude Code also compacts automatically as the window fills.
  • Large tool outputs are spilled into ~/.claude/projects/<project>/<session-id>/tool-results/, which is your clip().
  • Claude Code handles prompt caching for you. You can measure it from your own transcripts:
python3 - ~/.claude/projects/<project>/<session-id>.jsonl <<'EOF'
import json, sys
for line in open(sys.argv[1]):
    e = json.loads(line)
    if e.get("type") == "assistant" and "usage" in e["message"]:
        u = e["message"]["usage"]
        cached = u.get("cache_read_input_tokens") or 0
        print("context", u["input_tokens"] + cached + (u.get("cache_creation_input_tokens") or 0), "cached", cached)
EOF

(A response with several content blocks shows up as several lines.)

Break it

  1. Put datetime.now() into SYSTEM and rebuild it on every turn. cached drops to zero. On newer API accounts the request can be rejected outright, because changing the system prompt is an edit to history. The fix is to append a {"role": "system", "content": "..."} message at the point where the instruction changes, instead of rewriting the top.
  2. “Compact” by deleting the oldest five messages. The first tool_result left in the list now answers a tool_use that no longer exists, and the API returns an error.

Answer

Attention is finite. Irrelevant tokens dilute the relevant ones, and facts in the middle of a long context get used less well. Append-only keeps the cache warm and keeps the conversation valid on models that bind their thinking to the exact history.

Next: Step 5 — Subagents

5 - Step 5 — Subagents

Your run() called again with a fresh context, fewer tools and a cheaper model.

A subagent is not a new kind of thing. It is your run() called again with a fresh msgs, its own system prompt, fewer tools, and often a cheaper model. Only its final report comes back. The main reason to use one is to isolate context. Parallelism comes second.

By the end of this step you should be able to answer: when should you not use a subagent?

Build

MODELS = {"main": "claude-opus-5-5", "sub": "claude-haiku-5-5"}
READ_ONLY = [t for t in TOOLS if t["name"] in ("list_files", "read_file")]
SUB_SYSTEM = "You are a research subagent. Read only what the task needs, then report briefly."

def delegate(task):
    return run(task + "\n\nEnd with a short report: findings and file paths only.",
               tools=READ_ONLY, model=MODELS["sub"], effort="low", max_turns=15,
               agent="sub", system=SUB_SYSTEM)

TOOLS.append(tool(delegate,
    "Hand a self-contained, read-only research subtask to a subagent with a fresh context. "
    "It returns only a short report. Call it several times in one turn to run subtasks in parallel.",
    task="Complete instructions. The subagent sees nothing of this conversation."))
FUNCS["delegate"] = delegate

run() grows effort, agent and system parameters: use system = system or system_prompt(), and effort goes in as output_config={"effort": effort}. Then make one change so that parallel calls really run at the same time:

        with ThreadPoolExecutor() as pool:          # parallel tool calls run concurrently
            msgs.append({"role": "user", "content": list(pool.map(execute, calls))})

Note that READ_ONLY is taken before delegate is added, so subagents cannot spawn subagents.

Check

With WORKDIR on the vault copy, ask “Which pages discuss subagents, and what does each say about when to use them? Use one subagent per top-level section.” The main agent’s context stays small. The subagents read the pages. Then add up the tokens of every call: the total is higher than the same question answered by one agent. Anthropic reports that, in its data, multi-agent systems use about 15× the tokens of a chat. Isolation costs money.

See it in Claude Code

Create .claude/agents/reviewer.md:

---
name: reviewer
description: Reviews a diff for bugs. Use after code changes.
tools: Read, Grep, Glob
model: haiku
---
You review code changes for correctness bugs. Report file:line and one sentence per finding.

The frontmatter is your delegate() signature, and the body is its SUB_SYSTEM. Each subagent runs in its own context window. Its transcript lands in ~/.claude/projects/<project>/<session-id>/subagents/.

Break it

Let two subagents edit the same file at once. One overwrites the other. Then give a subagent the task “fix it” with no context. It has never seen the conversation, so it has no idea what “it” is.

Answer

Don’t use a subagent when the subtasks share state or must happen in sequence, when they write to the same files, or when the task is small enough that the extra tokens buy nothing.

Next: Step 6 — A model per role

6 - Step 6 — A model per role

Measure cost per finished task across models and effort levels, with computed ground truth.

Choosing a model is a measurement, not a feeling. The honest unit is cost per finished task, not price per token. A cheap model that needs three times the turns, or a second attempt, is not cheap.

By the end of this step you should be able to answer: when does the smaller model win overall?

Build

Add a trace line, and call log(agent, turn, r.usage) right after each create() in run():

def log(agent, turn, u):
    with open(WORKDIR.parent / "trace.jsonl", "a") as f:
        f.write(json.dumps({"agent": agent, "turn": turn, "context": context_size(u),
                            "cached": u.cache_read_input_tokens or 0, "output": u.output_tokens}) + "\n")

Then measure the same tasks across models and effort levels. The ground truth is computed from the files, never typed in by hand. The benchmark gives the agent only the read-only tools, so it cannot change anything, and the grading is strict on purpose: following the requested format is part of the job.

# bench.py — run with WORKDIR=vault (a copy of this vault's content/en)
import itertools, json, re, time
import agent

ROOT = agent.WORKDIR
def front(path, key):
    return re.search(rf"^{key}:\s*\"?(.+?)\"?$", (ROOT / path).read_text(), re.M).group(1)

TASKS = [
    ("How many .md files are under deep-dives/, including subfolders? Reply with the number only.",
     str(len(list((ROOT / "deep-dives").rglob("*.md"))))),
    ("What is the front-matter weight of building/agent-harness.md? Reply with the number only.",
     front("building/agent-harness.md", "weight")),
    ("What is the title of building/loop-engineering/levels.md? Reply with the title only.",
     front("building/loop-engineering/levels.md", "title")),
    ("Which page under deep-dives/ has the most lines? Reply with its path only.",
     str(max((ROOT / "deep-dives").rglob("*.md"), key=lambda p: len(p.read_text().splitlines())).relative_to(ROOT))),
]

for model, effort in itertools.product(["claude-haiku-5-5", "claude-sonnet-5-5", "claude-opus-5-5"],
                                       ["low", "medium"]):
    tag, ok, t0 = f"{model}/{effort}", 0, time.time()
    for i, (q, expected) in enumerate(TASKS):
        answer = agent.run(q, tools=agent.READ_ONLY, model=model, effort=effort,
                           max_turns=15, agent=f"{tag}#{i}")
        ok += answer.strip().strip("`'\".").lower() == expected.lower()   # strict on purpose
    rows = [json.loads(l) for l in open(ROOT.parent / "trace.jsonl") if tag in l]
    print(f"{tag:26} solved {ok}/{len(TASKS)}  turns {len(rows):3}  "
          f"context tokens {sum(r['context'] for r in rows):8}  output {sum(r['output'] for r in rows):6}  "
          f"{time.time() - t0:5.0f}s")

Check

You get a table of your own numbers: success, turns, tokens and seconds per model and effort. Multiply the tokens by the prices on the pricing page. No numbers are printed here on purpose. Yours are the ones that count, and they change with every model release.

See it in Claude Code

/model sonnet switches mid-session. The model: line in a subagent file is your MODELS["sub"].

Break it

Add a task that needs several hops, such as “which page links to the page with the most headings?” Watch the smallest model at low effort answer quickly and wrongly. Then check whether the biggest model at low effort beats the middle one at medium.

Answer

The small model wins on narrow, well-specified, high-volume work with checkable outputs, where it finishes in a similar number of turns. Measure cost per finished task.

Next: Step 7 — Harness controls

7 - Step 7 — Harness controls

Permission rules, hooks and saved sessions — guardrails that live in code, not in the prompt.

So far the model can run any shell command. A harness is defined by what it refuses to do, and those guardrails must live in code, not in the prompt.

By the end of this step you should be able to answer: why must the rule live in the harness and not in the prompt?

Build

Add permission rules, hooks and saved sessions:

RULES = [  # first match wins: (tool name or *, regex on the arguments, decision)
    ("run_bash", r"\brm\b|-delete|\bsudo\b|\bcurl\b|git\s+push", "deny"),
    ("run_bash", r"^(python -m pytest|ls|cat|grep|sed -n|wc)\b", "allow"),
    ("run_bash", r".*", "ask"),
    ("write_file", r".*", "ask"),
    ("*", r".*", "allow"),
]
ASK = threading.Lock()

def permit(call):
    args = " ".join(str(v) for v in call.input.values())
    for name, pattern, decision in RULES:
        if name in (call.name, "*") and re.search(pattern, args):
            if decision == "ask":
                with ASK:
                    return input(f"\nallow {call.name}: {args[:200]!r}? [y/N] ").strip().lower() == "y"
            return decision == "allow"
    return False

def audit(call, out):                      # a post-hook: one line per tool call
    with open(WORKDIR.parent / "audit.jsonl", "a") as f:
        f.write(json.dumps({"tool": call.name, "input": call.input, "chars": len(out)}) + "\n")

HOOKS = {"pre": [], "post": [audit]}       # a pre-hook returns a reason string to block

def result(call, content, is_error=False):
    return {"type": "tool_result", "tool_use_id": call.id,
            "content": content or "(empty)", "is_error": is_error}

def execute(call):
    if not permit(call):
        return result(call, "Denied by the harness permission rules. Choose another way.", True)
    for hook in HOOKS["pre"]:
        if reason := hook(call):
            return result(call, f"Blocked by a hook: {reason}", True)
    try:
        out, failed = FUNCS[call.name](**call.input), False
    except Exception as e:
        out, failed = f"{type(e).__name__}: {e}", True
    out = clip(call.id, out)
    for hook in HOOKS["post"]:
        hook(call, out)
    return result(call, out, failed)

A denial goes back to the model as an ordinary error result, so the model can choose another way. For sessions, store every message the moment it is appended, one per line, which is the same shape as Claude Code’s JSONL:

def load(session):                         # resume from the last compaction boundary
    path = WORKDIR.parent / "sessions" / f"{session}.jsonl"
    lines = [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else []
    start = max([i for i, m in enumerate(lines) if m["compacted"]], default=0)
    return [{"role": m["role"], "content": m["content"]} for m in lines[start:]]

def save(session, msg, compacted):         # append-only, one message per line
    path = WORKDIR.parent / "sessions" / f"{session}.jsonl"
    path.parent.mkdir(exist_ok=True)
    content = msg["content"]
    if not isinstance(content, str):
        content = [b if isinstance(b, dict) else b.model_dump(mode="json", exclude_none=True) for b in content]
    with open(path, "a") as f:
        f.write(json.dumps({"role": msg["role"], "content": content, "compacted": compacted}) + "\n")

In run(), add a session=None parameter. Start from msgs = load(session) if session else [], and route every append through one helper that also saves. A compaction becomes a boundary instead of a rewrite:

    def push(msg, compacted=False):
        msgs.append(msg)
        if session:
            save(session, msg, compacted)
    # ...append with push(...) everywhere, and on compaction:
            summary = compact(task, msgs, system, tools, model)
            msgs.clear()
            push(summary, compacted=True)

Check

Ask the agent to “delete the test file”. The rm is denied and the model reads the denial. Ask it to edit calc.py and you get a prompt. audit.jsonl has one line per call. Run run("How many files?", session="s1"), then run("Name them.", session="s1"). The second run knows what the first one found.

See it in Claude Code

  • Permissions live in settings.json as allow, ask and deny rules such as Bash(npm run test *) or Bash(rm *).
  • The permission modes are default, acceptEdits, plan, auto, dontAsk and bypassPermissions.
  • A PreToolUse hook that exits with code 2 blocks the call, and its stderr goes back to the model, just like your pre-hooks.
  • claude --continue and claude --resume are your load().

The docs say it directly: permission rules are enforced by Claude Code, not by the model.

Break it

  1. Remove the rm rule and write “never delete files” in SYSTEM instead. Then hand the agent a task where deleting looks helpful.
  2. Get past your own regex with python -c "import shutil; shutil.rmtree('x')" or python -m pytest && <anything>. Prefix rules match text, not intent. That is why real harnesses split compound commands and still run inside a sandbox.
  3. Claude Code evaluates deny, then ask, then allow, so an allow can never carve an exception out of a deny. Move your broad ("*", r".*", "allow") to the top of RULES and see why that precedence exists.

Answer

The model follows instructions most of the time, and a guardrail has to hold all of the time, including when a tool result carries a prompt injection. Only code can enforce that.

Next: Step 8 — Plug-ins, and the real thing

8 - Step 8 — Plug-ins, and the real thing

A hand-written MCP server, then the same agent on the Claude Agent SDK, compared line by line.

MCP is a tool registry at the other end of a pipe. The protocol does not change your loop. It only changes where the tool definitions come from and where the calls go.

By the end of this step you should be able to answer: what does the SDK do for you, and what is still your job?

Build

Here is a complete server:

# notes_server.py
import pathlib
from mcp.server.mcpserver import MCPServer

NOTES = pathlib.Path(__file__).with_name("notes.md")
server = MCPServer("notes")

@server.tool()
def add_note(text: str) -> str:
    """Append one note to the shared notes file."""
    with NOTES.open("a") as f:
        f.write(f"- {text}\n")
    return "saved"

@server.tool()
def read_notes() -> str:
    """Return every saved note."""
    return NOTES.read_text() if NOTES.exists() else "(no notes yet)"

if __name__ == "__main__":
    server.run()                       # stdio by default

Plug it into your harness. list_tools gives you the schemas and call_tool runs them. The loop does not change at all:

# mcp_bridge.py
import asyncio, sys
from mcp import Client, StdioServerParameters
import agent

async def main(task):
    server = StdioServerParameters(command=sys.executable, args=["notes_server.py"])
    async with Client(server) as mcp:
        loop = asyncio.get_running_loop()
        for t in (await mcp.list_tools()).tools:          # MCP schema -> API tool schema
            agent.TOOLS.append({"name": t.name, "description": t.description or "",
                                "input_schema": t.input_schema})
            def call(_name=t.name, **args):                # runs in a worker thread
                res = asyncio.run_coroutine_threadsafe(mcp.call_tool(_name, args), loop).result()
                return "\n".join(c.text for c in res.content if c.type == "text")
            agent.FUNCS[t.name] = call
        print(await asyncio.to_thread(agent.run, task))

if __name__ == "__main__":
    asyncio.run(main("Run the tests, save a one-line note with the result, then list all notes."))

Now rebuild the whole agent on the Claude Agent SDK, which is the Claude Code harness packaged as a library:

# sdk_agent.py
import asyncio, pathlib, sys
from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query

async def main():
    options = ClaudeAgentOptions(
        cwd="sandbox",
        model="claude-opus-5-5",
        allowed_tools=["Read", "Grep", "Glob", "Edit", "Bash(python -m pytest *)"],  # pre-approved
        disallowed_tools=["Bash(rm *)", "WebFetch"],
        permission_mode="default",
        max_turns=25,
        mcp_servers={"notes": {"command": sys.executable,
                               "args": [str(pathlib.Path("notes_server.py").resolve())]}},
    )
    prompt = "Make the tests pass, then save a one-line note about the fix."
    async for message in query(prompt=prompt, options=options):
        if isinstance(message, ResultMessage):
            print(message.subtype, message.num_turns, message.total_cost_usd)
            print(message.result)

asyncio.run(main())

allowed_tools pre-approves tools. It does not restrict the agent to them, which is what disallowed_tools and the permission mode are for.

Check

Reset calc.py to the buggy version and run both versions on the same task. Then fill in this table from your own code:

MechanismYour agent.pyClaude CodeAgent SDK
Looprun()built inquery()
ToolsTOOLS + FUNCSRead, Edit, Bash, Grep, Glob…allowed_tools, disallowed_tools
Contextclip(), compact(), AGENT.md, cache_controltool-results/, /compact, CLAUDE.md, automatic cachingbuilt in
Subagentsdelegate().claude/agents/*.mdagents=
Model per roleMODELS/model, model: in subagent filesmodel=, per-agent model
PermissionsRULES + permit()allow / ask / deny rules, permission modespermission_mode, can_use_tool
HooksHOOKSPreToolUse, PostToolUse…hooks=
Sessionssessions/*.jsonl~/.claude/projects/...jsonl, --resumeresume=
Plug-insmcp_bridge.pyclaude mcp addmcp_servers=

See it in Claude Code

The same server works unchanged in Claude Code:

claude mcp add notes -- python /absolute/path/to/notes_server.py

The -- separates Claude Code’s own options from the command that starts the server. Run /mcp inside a session to see the server and its tools. They appear with the server name as a prefix, mcp__notes__add_note, which is also the name you use in permission rules.

Break it

Add print("saving", text) inside add_note and run the bridge again. Over stdio, stdout is the protocol channel. Your print arrives as a line that is not JSON-RPC, and the client reports an Invalid JSON error for it. The Python SDK skips the line and carries on, but a stricter client could drop the connection. Log to stderr instead. Then give add_note the docstring "Does notes stuff" and see whether the agent still knows when to call it. MCP tool descriptions are prompts, exactly like the ones in step 2.

Answer

The SDK gives you the loop, the built-in tools, context management, subagents, permissions, hooks and sessions. What you still own is the task, the tools specific to your domain, the permission policy, and deciding whether the result is right.

Next: back to the lab overview and its four debugging questions.