A buyer wrote to TinyTickets that she had paid the $1.50 booking fee on an order of four tickets. Nina pasted the complaint into a chat with the model and asked where the bug was. The model answered with a fix for src/fees.js, a file TinyTickets had never had.
“Did the robot read our code?” Leo asked.
“It can’t,” Nina said. “It has only seen what I typed.”
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
In Module 3 you put everything the model needed into one request. This module gives the model tools, so it can ask your program to read a file, change it or run the tests. A loop lets it keep asking until the job is done, and by the end you’ll have agent.ts, a small coding agent you understand line by line.
After this module, you can:
- define a tool with a name, a description and an input schema, and say what the model receives
- read a tool call in a response and send its result back in the shape the API requires, errors included
- write an agent loop and name every way it stops, including the stops your code must add
- choose between a workflow and an agent for a task
- build and run
agent.ts, which reads, edits and tests code, and asks you before it runs a command
A question about code the model has never seen
Suppose you ask the model about TinyTickets code from a program, as you did in Module 2. Here is the whole program:
// ask.ts: a question about code, with no way to read the code
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const model = process.env.MODEL ?? "claude-opus-5-5";
const response = await client.messages.create({
model,
max_tokens: 2000,
messages: [
{
role: "user",
content: "In my project, why do four tickets still pay the booking fee? The code is in tinytickets-mini.",
},
],
});
for (const block of response.content) {
if (block.type === "text") {
console.log(block.text);
}
}
The folder tinytickets-mini is on your disk, and the lab creates it. Its file src/sales/booking-fee.ts holds the bug.
Pause and predict. What will the model answer?
Answer
It can’t open the folder. The request holds one sentence, and the model reads the request and nothing else (Module 2). So it either says it can’t see the code, or it guesses: a likely bug, in a file whose name it makes up.
A guess can even be right. “The check uses <= where it should use <” is a common bug, so the model may name it. It is still a guess, because nothing in the request shows the code.
If you run ask.ts, compare its answer with the one above. Your answer will differ from run to run, because each one is sampled (Module 2). Figure 1 shows why no run can be right on purpose.
Context window of ask.ts
+------------------------------------------------------------+
| user: In my project, why do four tickets still pay the |
| booking fee? The code is in tinytickets-mini. |
+------------------------------------------------------------+
|
v
[Model] --> an answer about code it never read X
[[tinytickets-mini]] src/sales/booking-fee.ts: never sent
Figure 1: the code is on your disk, and the model sees only the request.
You could paste the file into the request, as Module 3 put everything into one request. That works when you know which file matters and it’s small. Here you don’t know which file holds the bug. Pasting a whole codebase costs tokens on every call, and Module 3 showed that text the task doesn’t need can make answers worse.
A better plan is to let the model ask for what it needs. So this module answers one question. How does a model that can only write text read files, change code and run tests, and what decides when it stops?
A tool is a function the model can ask for
A tool is a function in your program that the model can ask to run, by name, with arguments it chooses. The model never runs it. It writes a request for the call, and your code decides whether to run it and what to send back.
A tool definition is the description of one tool that you send in the request’s tools field. It has three parts:
name: what the model writes to ask for the tool, such asread_file.description: plain text that says what the tool does and when to use it.input_schema: a JSON Schema (Module 3) for the arguments.
Here is a request with one tool, as it goes over the wire (shortened):
{
"model": "claude-opus-5-5",
"max_tokens": 16000,
"system": "You are a coding agent working in the project folder ...",
"tools": [
{
"name": "read_file",
"description": "Read a text file of the project and return its contents. ...",
"input_schema": {
"type": "object",
"properties": { "path": { "type": "string" } },
"required": ["path"]
}
}
],
"messages": [{ "role": "user", "content": "Why do four tickets still pay the booking fee? The code is in src/sales/booking-fee.ts." }]
}
The tools field sits beside system and messages. Nothing in it is code. The model never sees your function, only its name, its description and its schema.
What the model receives
The model still reads only tokens. The define tools docs (checked 2026-11-22) say that the API builds a special system prompt from your tool definitions and your own system prompt. Figure 2 shows the context window of the request above.
Context window of one agent.ts request (claude-opus-5-5)
+-------------------------------------------------------------+
| system prompt built by the API: |
| "In this environment you have access to a set of tools" |
| tool definitions: name, description, input_schema each |
| your system prompt: the project folder and the rules |
|-------------------------------------------------------------|
| message 1 user: Why do four tickets still pay the fee? |
|-------------------------------------------------------------|
| output: thinking, then text or tool_use, at most max_tokens |
+-------------------------------------------------------------+
Figure 2: tool definitions are text in the context window, read before your system prompt on every call.
So tools cost tokens on every request. The tool use overview lists the API’s added text at 286 tokens on Opus 5.5, Sonnet 5.5 and Haiku 5.5 (checked 2026-11-22). Your definitions come on top, and both are billed as input. The order is the cache order from Module 3 (tools, system, messages), so changing a tool definition empties the cache.
When the model calls a tool
With the default setting, tool_choice: { type: "auto" }, the model decides. The overview says it calls a tool when the request matches a tool’s description and the answer isn’t already in the context window. Your system prompt can push it further, with a line such as “Use the tools to investigate before you answer.”
The description does most of the work. The define tools docs call detailed descriptions “by far the most important factor in tool performance”, and they suggest at least three or four sentences per tool. Say what the tool does, when to use it, when not to, and what each argument means.
You can’t force a call on the newest models. Module 3 showed that tool_choice set to any or tool returns a 400 error on Fable 5.1, Fable 5.2, Opus 5.5 and Sonnet 5.5. So agent.ts leaves tool_choice at auto.
The alternative to a tool is pasting the data in, as Module 3 did with emails. Paste it when the data is small, known in advance and needed on every call. Give a tool when the model must choose what to fetch, as with a bug in an unknown file.
What changed recently is the models more than the tools. Tool use left beta on May 30, 2024, and tool_choice: none arrived on February 27, 2025 (release notes). The forced choices stopped working with Opus 5.5 on September 22, 2026.
Rule: A tool is a name, a description and a schema in the context window; the model can only ask, and your code acts.
One tool call on the wire
The model answers a request with tools the same way it answers any request, with one response that holds content, stop_reason and usage. What changes is what can be in content.
A tool call is a tool_use block in the model’s response: the tool’s name, the arguments as an input object, and an id. Here is the shape for the request above, from the handle tool calls docs (checked 2026-11-22). It is not a real run; the IDs and counts are placeholders.
{
"id": "msg_...",
"type": "message",
"role": "assistant",
"model": "claude-opus-5-5",
"content": [
{ "type": "thinking", "thinking": "", "signature": "..." },
{ "type": "tool_use", "id": "toolu_...", "name": "read_file", "input": { "path": "src/sales/booking-fee.ts" } }
],
"stop_reason": "tool_use",
"usage": { "input_tokens": 0, "output_tokens": 0 }
}
Notice three things. stop_reason is "tool_use", which means the model stopped because it wants a tool. input is already a parsed object that matches the schema. And the thinking text is empty, because Opus 5.5 leaves it out of the response by default (Module 2). When you print a real response in the lab, check whether yours has the same fields.
Your program now runs read_file with that path. Then it sends the answer back.
A tool result is a tool_result block that your program sends in the next user message. It holds the tool_use_id of the call it answers and the content the tool returned. The next request keeps every earlier message, adds the model’s response unchanged as an assistant message, then adds the result:
{ "role": "assistant", "content": [ "...the response content above, unchanged..." ] },
{ "role": "user", "content": [
{ "type": "tool_result", "tool_use_id": "toolu_...", "content": "// An order of fewer than four tickets pays a $1.50 booking fee.\nexport function bookingFeeCents(..." }
] }
There is no special role for tools. The docs point out that some APIs use a tool or function role, while Claude puts calls in assistant messages and results in user messages. The request still carries the same tools, and the model then answers from the file’s text. Figure 3 shows the whole exchange.
(Developer) [agent.ts] [Claude API] [[project files]]
| task | | |
|----------->| 1 POST /v1/messages | |
| | tools, system, task ------>| |
| | | [Model] asks |
| | | for read_file |
| |<-- 2 stop_reason: tool_use --| |
| | 3 read src/sales/booking-fee.ts --------------->|
| |<---------------------------------- file text ---|
| | 4 POST /v1/messages | |
| | + assistant: tool_use | |
| | + user: tool_result ------>| |
| |<-- 5 stop_reason: end_turn --| |
|<-----------| text: the answer | |
| answer | | |
Figure 3: one tool call takes two requests, and your program does the reading in between.
The API checks the order strictly. Each tool_result must come in the user message right after the assistant message with the call. Inside that message, the results come first and any text after them.
Pause and predict. Your program gets the response with the tool_use block, then sends the next request with a new question and no tool_result. What happens?
Answer
The API refuses it with a 400 error. Every call must be answered in the very next user message. The handle tool calls docs quote the error: “tool_use ids were found without tool_result blocks immediately after”. This matters later, when the loop stops halfway through a call.
Calls that fail
A tool can fail, for example when the file doesn’t exist. You still answer the call, with a tool_result whose is_error field is true and whose content says what went wrong:
{ "type": "tool_result", "tool_use_id": "toolu_...", "is_error": true,
"content": "Error: ENOENT: no such file or directory, open '/home/you/tinytickets-mini/src/booking.ts'" }
The model reads the error and can try something else. The docs warn that it might call the tool again with new input, “so limit how many retries your loop allows”. They also advise error text that says what to try next, not a bare "failed".
Several calls in one response
Parallel tool calls are several tool_use blocks in one response, such as two read_file calls for two files. The parallel tool use docs (checked 2026-11-22) say Claude may do this by default. You answer them with one tool_result per call, all together in the next user message.
Sending each result in its own user message is the most common mistake, the docs say, and it teaches the model to stop making parallel calls. The API doesn’t fix the order in which you run the calls. Reads are safe to run at the same time; edits and commands are safer one after another.
agent.ts runs the calls one at a time, in the order the model wrote them. That keeps edits in order and lets it ask you about one command at a time. If you want one call per response, tool_choice has a disable_parallel_tool_use option, added on October 3, 2024.
The same idea in other APIs
Other model APIs have tool calls too, in other shapes. Figure 4 compares Claude’s with OpenAI’s Responses API (function calling guide, checked 2026-11-22).
| Part | Claude Messages API | OpenAI Responses API |
|---|---|---|
| The definition | { name, description, input_schema } |
{ type: "function", name, description, parameters } |
| The call | a tool_use block in the assistant’s content; input is an object |
a function_call item; arguments is a JSON string you parse |
| The result | a tool_result block in a user message |
a function_call_output item with the same call_id |
| One call at a time | disable_parallel_tool_use: true |
parallel_tool_calls: false |
Figure 4: the same four parts, with different field names and places.
Ollama’s own chat API uses a third shape, with a tool role. MCP, in Module 5, standardizes the tool side (how a program offers tools) and leaves these request formats as they are.
What changed recently is where this format runs. Ollama added an Anthropic-compatible /v1/messages endpoint in v0.14.0, on January 10, 2026 (Ollama docs). So agent.ts runs against a local model with no code change. One difference matters there: Ollama drops is_error before the model sees it, so agent.ts starts every error’s text with Error:.
The agent loop: act, observe, act again
One tool call answers “what’s in this file?”. A bug hunt needs more: list the files, read one, read another, change a line, run the tests. You don’t know the steps in advance, and neither does the model until it sees each result.
An agent loop is a loop in your program that calls the model, runs the tool calls in its response and sends back the results. It repeats until the model stops asking for tools. Here is the core of the one in agent.ts:
// Excerpt from agent.ts: the loop, shortened (the full file is in the lab)
for (let step = 1; step <= MAX_STEPS; step++) {
const response = await client.messages.create({
model: MODEL,
max_tokens: 16000,
system: SYSTEM,
tools: TOOLS.map((t) => t.definition),
messages,
});
messages.push({ role: "assistant", content: response.content });
const results: Anthropic.ToolResultBlockParam[] = [];
for (const block of response.content) {
if (block.type === "tool_use") {
results.push(await runTool(block));
}
}
if (results.length > 0) {
messages.push({ role: "user", content: results });
}
if (response.stop_reason !== "tool_use") {
return;
}
}
Each pass is one step. The model acts by asking for tools, the program runs them, and the model observes the results on the next call. The history grows by two messages per step, and the whole of it goes out every time, because the API is stateless (Module 2).
This is the picture the rest of the course grows. Figure 5 draws it for the first time: the developer on the far left, the context window, the model in the middle and the tools on the right.
context window
+-------------------+
| tool definitions | tool_use tools
| system prompt |--> [Model] ---------> [list_files]
(Developer) task -->| user: task | [read_file]
^ | assistant: calls | [edit_file]
| | user: results |<---- tool_result ---- [run_command]
| | ... more steps | |
+--- answer ---| assistant: answer | v
+-------------------+ [[project files]]
The context window and the tools live in agent.ts, on your machine.
Legend: (name) a person, [name] a program, [[name]] stored data,
--> a request, in the direction it travels, <-- a response
Figure 5: the agent loop; the model asks, agent.ts runs the tools, and every result goes back into the context window.
What an agent is
An agent is a program in which the model decides which steps to take and which tools to use, in a loop, until the task is done. Anthropic’s Building effective agents (December 19, 2024) puts it in one line: agents “are typically just LLMs using tools based on environmental feedback in a loop.” The environmental feedback is the tool results, such as a file’s text or a failing test.
A coding agent is an agent whose tools read and change code and run commands, such as the tests. agent.ts is a small one, and Claude Code, from Module 6, is a large one.
Karpathy’s 2025 LLM Year in Review (December 19, 2025) called Claude Code the first convincing demonstration of an LLM agent. He described it as something that “in a loopy way strings together tool use and reasoning”. The literal fact behind “loopy” is the for loop above. The model thinks and asks for a tool, your code runs it, and the loop sends the result back.
The plan for agent.ts follows Thorsten Ball’s How to Build an Agent (April 15, 2025). His summary is “It’s an LLM, a loop, and enough tokens.” His Go version reached about 300 lines with three tools. agent.ts is written in TypeScript from scratch. It adds what his version left out: a step limit, a command tool behind a prompt, and a check on every path.
What the loop costs
Every step resends the whole history, so input_tokens grows with each step. In a task of ten steps, your first message is billed ten times, and so is the first file the model read. agent.ts prints input_tokens after every step so you can watch it grow.
Prompt caching from Module 3 is the lever on this cost, because each request begins with the whole of the one before. agent.ts leaves caching out to stay short. It does cut big tool output, a file at 20,000 characters and a command’s output at 10,000. In September 2025, Claude Code limited a tool’s response to 25,000 tokens by default (Writing effective tools for agents).
A long run can also fill the window. Module 3’s “Going deeper” named the answers (compaction, notes, subagents), and Module 10 uses subagents.
Write the loop, or use one
You can write the loop yourself, as this module does, or use one that someone else wrote. A tool runner is a function in the SDK that runs the agent loop for you. You pass it the tools with their functions, and it calls the model and runs them until the model stops. “Going deeper” shows the TypeScript SDK’s one. Anthropic also offers the Claude Agent SDK, which is Claude Code as a library, and Claude Managed Agents (in beta), which runs the loop on Anthropic’s servers.
Building effective agents warns that frameworks “can obscure the underlying prompts and responses”, which makes them harder to debug. So write the loop by hand when you need to see and control each step, as you do while learning. A runner saves code once you know what it does for you.
What changed recently is that the loop moved into libraries. The SDK’s tool runner arrived in beta for TypeScript and Python on September 17, 2025, and it was still in beta on 2026-11-22.
Rule: An agent is a model, tools and a loop; the model chooses the next step, and your code runs it.
When the loop stops
What ends the loop: the model, or your program? Both, and you need both.
The model ends it through stop_reason. The stop reasons docs (checked 2026-11-22) list seven values. Figure 6 shows the ones agent.ts can meet, and the stops that only your program has.
| Who stops it | Signal | What agent.ts does |
|---|---|---|
| The model wants a tool | stop_reason: "tool_use" |
runs the tools, sends the results, loops again |
| The model has finished | stop_reason: "end_turn" |
prints the answer, waits for your next task |
| The reply hit your limit | stop_reason: "max_tokens" |
answers any cut-off call with an error, stops |
| The model declined | stop_reason: "refusal" |
prints what it has, stops |
| The window is full | stop_reason: "model_context_window_exceeded" |
stops |
| Your step limit | MAX_STEPS model calls |
prints “(stopped after 20 steps …)” |
| You | n at the command prompt, or Ctrl+C |
sends an error result, or exits |
Figure 6: the model stops the loop through stop_reason, and your code adds the stops the model can’t skip.
The other two values don’t come up here. stop_sequence needs stop sequences you set, and pause_turn comes from server tools that run on Anthropic’s side (“Going deeper”).
The step limit
A step limit is the most model calls your program allows for one task. agent.ts reads it from MAX_STEPS, with a default of 20. Building effective agents calls such stopping conditions “common” and says they keep you in control.
A model can retry the same failing call again and again, and nothing in stop_reason stops that. In a Claude Code bug report from December 31, 2025, a subagent retried the exact same npm install command more than 300 times. It ran for about 4.6 hours and used about 27 million tokens before it timed out.
That’s one report, not a rate, but it shows the shape of the failure. The defaults don’t protect you. Claude Code’s --max-turns, which works in print mode only, has no limit by default (CLI reference, checked 2026-11-22). Neither has the Agent SDK’s maxTurns. You catch a runaway loop in the trace: the same -> line again and again, and input_tokens climbing.
A limit has a cost too. A task that needs 25 steps stops at 20, so agent.ts tells you, and you can ask it to go on.
A call cut off by max_tokens
If the response stops at max_tokens while the model is writing a tool call, the call’s input may be incomplete. Running it is unsafe. Leaving it unanswered breaks the next request with the 400 from the last section. So agent.ts answers it with an error result, “not run, because your reply was cut off”, and stops.
The approval prompt
An approval prompt is a question your program asks a person before it runs a tool call, with the option to say no. Building effective agents describes agents that “pause for human feedback at checkpoints”. agent.ts asks before every shell command, because a command can do anything your user account can.
If you answer n, the program doesn’t run the command. It sends an error result, “The user declined to run this command.”, and the model decides what to do next. Ctrl+C ends the whole program.
After any stop, you can type a new task. The last message may be a user message with tool results, and your new task is another user message. The API merges consecutive messages with the same role (Messages API), so the history stays valid.
The defaults haven’t changed. A request for loop detection in Claude Code was closed as not planned (issue 4277, July 2025), so the step limit is still your job.
Rule: Every agent loop needs a stop the model can’t skip, so give it a step limit and ask a person before anything risky.
Tools the model can use well
The model fills in a tool’s arguments, and it can fill them in wrong. The tool use overview says Claude “might guess values you didn’t supply”. Ask about “the booking fee code” with only read_file, and the model may try a path such as src/booking.ts that doesn’t exist. The lab shows it.
The fix belongs in the tools. Four habits come from Anthropic’s docs and engineering posts:
- Give the model a way to find out. A
list_filestool shows the real paths, and one line in the system prompt says “Never guess a path.” - Write errors that say what to do next. “old_str not found in src/sales/booking-fee.ts. Read the file again and copy the text exactly.” gives the model its next step.
- Make wrong input hard to send. Building effective agents tells how a coding agent misused relative paths after it changed folders, until the team made the tool require absolute paths.
agent.tsreaches the same goal another way. It never changes folders, so every path is relative to the same project root. - Treat every argument as untrusted.
agent.tsresolves each path and refuses any that lead outside the project folder. A file can also contain text that tries to give the model orders, which Module 9 covers.
Edits fail in a way of their own. An edit tool that replaces text must find exactly the text the model remembers. Claude Code’s issue tracker has reports of edits that missed because of tabs and spaces (issue 753) or Windows line endings (issue 164).
So edit_file in agent.ts counts the matches first. With no match, or more than one, it refuses and says why. Ball’s version replaced every match, and Anthropic’s own text editor tool refuses, with errors such as “Found 3 matches for replacement text”.
Each habit has a cost. Every word of a description is input on every call. And every tool you add is one more choice the model can get wrong, so give it the tools the task needs and no more.
Rule: Design each tool so the easy call is the right one, and make every error say what to try next.
Workflows and agents
Should every task run in a loop like this? No, and Module 3’s email tagger shows why.
A workflow is a program in which your code fixes the steps and their order, and the model fills in one or more of them. Building effective agents defines workflows as systems where models and tools are “orchestrated through predefined code paths”. In an agent, the model directs its own steps. Figure 7 puts the two side by side.
Workflow: Module 3's tagger. The code fixes every step and their order.
email --> [Model] --> tag --> code routes it --> Leo or the team
Agent: agent.ts on the booking fee. The model picks each next step.
task --> [Model] --> list_files --> [Model] --> read_file --> [Model]
|
answer <----+
Figure 7: in a workflow your code decides what happens next; in an agent the model does.
The choice flips on one question. Do you know the steps before you start? Tagging an email is always one call, then a route, so it is a workflow. Finding a bug depends on what each file contains, so it needs an agent.
Agents cost more. The same post warns of “higher costs, and the potential for compounding errors”, because each step builds on the last. It recommends the simplest solution that works, and says that one call with good context is often enough. It also recommends testing agents in sandboxed environments, which Module 9 sets up.
The post names five common workflow shapes: prompt chaining, routing, parallelization, orchestrator-workers and evaluator-optimizer. The tagger is routing; the others are outside this course.
What changed recently is the tooling, not the definitions. The post is from December 2024, and its page now notes that much of the tooling it describes has changed. Its split between workflows and agents is the one this course uses.
One question through agent.ts
This trace follows one question through the finished agent.ts, run from the tinytickets-mini folder as step 1 of the lab creates it: “Why do four tickets still pay the booking fee?” Unlike the request in Figure 3, it doesn’t name the file. Figure 8 shows what goes to the model on each step.
step sent to [Model] reply input_tokens
1 tools + system + task list_files "." smallest
2 step 1 + call 1 + result 1 (file list) read_file larger
3 step 2 + call 2 + result 2 (the code) answer, end_turn largest
Figure 8: each step sends everything the last step sent, plus one call and one result.
Step 1: the first request. agent.ts sends the four tool definitions, the system prompt and your question. The system prompt says “Never guess a path”, and no path is in the question. So the model is likely to answer with stop_reason: "tool_use" and a call to list_files with {"path": "."}.
Step 2: the file list. agent.ts prints -> list_files {"path":"."} and runs the tool. It sends back seven lines, the folders and files of the project. The model now sees src/sales/booking-fee.ts and is likely to ask for read_file on it.
Step 3: the code. read_file returns the file’s four lines, comment included. The comment says “fewer than four tickets”; the code says ticketCount <= 4. The model answers in text, with stop_reason: "end_turn", and the loop returns.
When you run the lab, you see your own trace, with input_tokens on each [step] line. A model may take a different path, such as reading the test file too. That is the agent choosing its steps, and your trace can differ from this one.
Pause and predict. Step 3’s request holds the same system prompt and question as step 1. Why is its input_tokens larger?
Answer
Because it also carries both earlier replies, with their tool calls, and both results: the file list and the code. The API is stateless, so all of it is sent again, and billed again, on every step.
Lab: build agent.ts, a small coding agent
Time: about 30 minutes. You’ll ask a question without tools, then build agent.ts one tool at a time, watch it guess a path and miss an edit, and fix both.
You need:
- Node.js 26 LTS. On 2026-11-22 the newest release was v26.13.1 (Node.js releases), and the rest of the course keeps it. Node 26 runs
.tsfiles directly by removing the types, with no build step and no type check (Node.js TypeScript docs). That works only for TypeScript whose types can be deleted, soagent.tsuses noenum. - The API key from Module 2. It costs money per token (pricing). An agent costs more per task than Module 3’s tagger, because every step resends the history, and Opus 5.5 costs more per token than Haiku 5.5. Or use Ollama for free (see the note at the end of the lab).
Model used: claude-opus-5-5, checked on 2026-11-22. The models overview suggests starting with Opus 5.5 for most work. agent.ts reads the model from MODEL, so MODEL=claude-haiku-5-5 is a cheaper run. With a later model, only MODEL should change, because the loop, the tool shapes and the stop reasons belong to the API, not the model.
The steps describe what to look for, not a recorded run, so check each one against your own output.
Step 1: set up the agent folder and a small project
Why: the agent lives in one folder, and the project it works on lives in another, so the agent’s file tools can’t reach its own code.
mkdir agent-lab
cd agent-lab
npm init -y
npm pkg set type=module
npm install @anthropic-ai/sdk
export ANTHROPIC_API_KEY="your key here"
cd ..
mkdir -p tinytickets-mini/src/sales tinytickets-mini/src/shows
Now create four files in tinytickets-mini. The bug is on purpose. The rule says fewer than four tickets, and the code says four or fewer.
{ "type": "module" }
That is tinytickets-mini/package.json. Next, tinytickets-mini/src/sales/booking-fee.ts:
// An order of fewer than four tickets pays a $1.50 booking fee.
export function bookingFeeCents(ticketCount: number): number {
return ticketCount <= 4 ? 150 : 0;
}
Then its test, tinytickets-mini/src/sales/booking-fee.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { bookingFeeCents } from "./booking-fee.ts";
test("fewer than four tickets pay the fee", () => {
assert.equal(bookingFeeCents(3), 150);
});
test("four tickets pay no fee", () => {
assert.equal(bookingFeeCents(4), 0);
});
And tinytickets-mini/src/shows/show.ts, so the project has more than one folder:
export const show = {
name: "Songs of Spring",
date: "2027-03-14",
doorsOpen: "19:00",
seats: 200,
priceCents: 1200,
};
Run node --test inside tinytickets-mini. You should see one test pass and “four tickets pay no fee” fail, with pass 1 and fail 1 in the summary.
Step 2: ask without tools
Why: you see the problem from the first section on your own machine. Create ask.ts in agent-lab with the code from that section, and run node ask.ts there.
You should see an answer that says it can’t see the folder, or one that guesses a bug and names files. Write down any file name it gives, and check whether that file exists.
Step 3: a loop with one tool, and watch it guess
Why: this is the smallest agent, with one tool, the loop and the step limit. It fails on purpose, because the model has no way to find the right path. Create agent-lab/agent.ts:
// agent.ts, version 1: one tool, the loop and the step limit
import Anthropic from "@anthropic-ai/sdk";
import fs from "node:fs/promises";
import path from "node:path";
import readline from "node:readline/promises";
import { exec } from "node:child_process"; // used by run_command (step 6)
import { promisify } from "node:util"; // used by run_command (step 6)
const client = new Anthropic();
const MODEL = process.env.MODEL ?? "claude-opus-5-5";
const MAX_STEPS = Number(process.env.MAX_STEPS ?? 20);
const ROOT = process.cwd();
const sh = promisify(exec);
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.on("close", () => process.exit(0));
const SYSTEM = `You are a coding agent working in the project folder ${ROOT}.
Keep answers short, and name the files you read or changed.`;
type Input = Record<string, string>;
type Tool = {
definition: Anthropic.Tool;
run: (input: Input) => Promise<string>;
};
// Every path the model sends is untrusted: resolve it, and refuse anything outside ROOT.
function inProject(p: string): string {
const full = path.resolve(ROOT, p);
const rel = path.relative(ROOT, full);
if (rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) {
throw new Error(`${p} is outside the project folder.`);
}
return full;
}
const readFile: Tool = {
definition: {
name: "read_file",
description:
"Read a text file of the project and return its contents. " +
"Use it to look at code before you answer a question about it or edit it. " +
"Paths are relative to the project root. Do not use it on folders.",
input_schema: {
type: "object",
properties: {
path: { type: "string", description: "File path relative to the project root." },
},
required: ["path"],
},
},
async run(input) {
const text = await fs.readFile(inProject(input.path), "utf8");
if (text.length > 20_000) {
return text.slice(0, 20_000) + "\n[cut at 20000 characters]";
}
return text;
},
};
const TOOLS: Tool[] = [readFile];
function preview(text: string): string {
return text.replace(/\s+/g, " ").slice(0, 120);
}
// Run one tool call, and turn the outcome, success or error, into a tool_result block.
async function runTool(call: Anthropic.ToolUseBlock): Promise<Anthropic.ToolResultBlockParam> {
console.log(` -> ${call.name} ${JSON.stringify(call.input)}`);
try {
const tool = TOOLS.find((t) => t.definition.name === call.name);
if (tool === undefined) {
throw new Error(`There is no tool named ${call.name}.`);
}
const content = await tool.run(call.input as Input);
console.log(` <- ${preview(content)}`);
return { type: "tool_result", tool_use_id: call.id, content };
} catch (err) {
const content = `Error: ${(err as Error).message}`;
console.log(` <- ERROR ${preview(content)}`);
return { type: "tool_result", tool_use_id: call.id, content, is_error: true };
}
}
// The agent loop: call the model, run the tools it asks for, send the results back, repeat.
async function runTask(messages: Anthropic.MessageParam[]): Promise<void> {
for (let step = 1; step <= MAX_STEPS; step++) {
const response = await client.messages.create({
model: MODEL,
max_tokens: 16000,
system: SYSTEM,
tools: TOOLS.map((t) => t.definition),
messages,
});
// Keep the reply in the history unchanged, thinking blocks included.
messages.push({ role: "assistant", content: response.content });
const usage = response.usage;
const counts = `input_tokens=${usage.input_tokens} output_tokens=${usage.output_tokens}`;
console.log(`[step ${step}] stop_reason=${response.stop_reason} ${counts}`);
const results: Anthropic.ToolResultBlockParam[] = [];
for (const block of response.content) {
if (block.type === "text") {
console.log(`\nagent: ${block.text}`);
} else if (block.type === "tool_use" && response.stop_reason === "tool_use") {
results.push(await runTool(block));
} else if (block.type === "tool_use") {
// The reply was cut off (max_tokens), so this call may be incomplete: answer it, don't run it.
results.push({
type: "tool_result",
tool_use_id: block.id,
content: "Error: not run, because your reply was cut off.",
is_error: true,
});
}
}
if (results.length > 0) {
// All results go back together, in one user message.
messages.push({ role: "user", content: results });
}
if (response.stop_reason !== "tool_use") {
return;
}
}
console.log(`\n(stopped after ${MAX_STEPS} steps; ask again to continue)`);
}
const messages: Anthropic.MessageParam[] = [];
console.log(`Coding agent on ${MODEL} in ${ROOT}. Press Ctrl+C to quit.`);
while (true) {
const task = await rl.question("\nyou: ");
if (task.trim() === "") {
continue;
}
messages.push({ role: "user", content: task });
try {
await runTask(messages);
} catch (err) {
if (!(err instanceof Anthropic.APIError)) {
throw err;
}
console.error(`API error ${err.status}: ${err.message}`);
}
}
Notice four things. ROOT is the folder you start the agent from, not the folder of agent.ts. Each tool is one object that holds the definition the model reads and the function your code runs. runTool never throws; a failure becomes a tool_result with is_error: true. And messages lives outside runTask, so the next task continues the same conversation.
Run it from the project folder, with a low step limit:
cd tinytickets-mini
MAX_STEPS=5 node ../agent-lab/agent.ts
Pause and predict. Type “Why do four tickets still pay the booking fee?” Which paths will the model try?
You are likely to see read_file calls on paths the model made up, such as src/booking.ts, each followed by <- ERROR Error: ENOENT: no such file or directory. The run may end with “(stopped after 5 steps …)”. A strong model may stop and ask you for the path; that is the model choosing not to guess, and it still can’t find the file.
Step 4: add list_files
Why: the model guessed because it had no way to see what exists. Add this tool above readFile in agent.ts:
// Add above readFile in agent.ts (step 4)
const SKIP = /(^|[\\/])(node_modules|\.git)([\\/]|$)/;
const listFiles: Tool = {
definition: {
name: "list_files",
description:
"List the files and folders under a folder of the project, recursively. " +
"Folder names end with '/'. node_modules and .git are skipped. " +
"Use this before you read a file whose path you have not seen.",
input_schema: {
type: "object",
properties: {
path: { type: "string", description: "Folder relative to the project root. Default '.'" },
},
},
},
async run(input) {
const entries = await fs.readdir(inProject(input.path ?? "."), {
recursive: true,
withFileTypes: true,
});
const lines: string[] = [];
for (const entry of entries) {
const rel = path.relative(ROOT, path.join(entry.parentPath, entry.name));
if (SKIP.test(rel)) {
continue;
}
lines.push(entry.isDirectory() ? rel + "/" : rel);
}
return lines.slice(0, 300).join("\n") || "(empty folder)";
},
};
Then change two lines. Add the tool to the list, and add one rule as the second line of SYSTEM:
// Changes in agent.ts (step 4)
const TOOLS: Tool[] = [listFiles, readFile];
Use list_files to find files. Never guess a path; if a file is not listed, say so.
Start the agent again with node ../agent-lab/agent.ts (no limit this time), and ask the same question. You are likely to see -> list_files {"path":"."}, then -> read_file {"path":"src/sales/booking-fee.ts"}, then an answer that points at <= 4. Watch input_tokens grow on each [step] line.
Step 5: add edit_file, and make an edit miss
Why: the agent should fix the bug, and you should see what happens when the file changes under it. Add this tool below readFile:
// Add below readFile in agent.ts (step 5)
const editFile: Tool = {
definition: {
name: "edit_file",
description:
"Replace one exact piece of text in a file with new text. " +
"old_str must appear exactly once in the file, including spaces, tabs and line breaks. " +
"Read the file first and copy old_str from it. " +
"To create a new file, pass an empty old_str and the whole file as new_str.",
input_schema: {
type: "object",
properties: {
path: { type: "string", description: "File path relative to the project root." },
old_str: { type: "string", description: "The exact text to replace. Empty to create a file." },
new_str: { type: "string", description: "The text to put in its place." },
},
required: ["path", "old_str", "new_str"],
},
},
async run(input) {
const file = inProject(input.path);
if (input.old_str === "") {
await fs.mkdir(path.dirname(file), { recursive: true });
await fs.writeFile(file, input.new_str, { flag: "wx" }); // "wx" fails if the file exists
return `Created ${input.path}`;
}
const text = await fs.readFile(file, "utf8");
const count = text.split(input.old_str).length - 1;
if (count === 0) {
throw new Error(`old_str not found in ${input.path}. Read the file again and copy the text exactly.`);
}
if (count > 1) {
throw new Error(`old_str appears ${count} times in ${input.path}. Add nearby lines so it appears once.`);
}
// A function as the replacement keeps "$&" and "$1" in new_str literal.
await fs.writeFile(file, text.replace(input.old_str, () => input.new_str));
return `Edited ${input.path}`;
},
};
Change TOOLS to [listFiles, readFile, editFile], and add a third line to SYSTEM:
Read a file before you edit it, and copy old_str exactly from what you read.
Restart the agent. Now provoke a miss:
- Ask: “What is the bug? Don’t change anything yet.” The agent reads the file and explains.
- In your editor, rename
ticketCounttoticketsinbooking-fee.ts, in both places, and save. The model’s copy of the file is now out of date. - Ask: “Fix it.”
You are likely to see -> edit_file with an old_str that still says ticketCount <= 4, then <- ERROR Error: old_str not found in src/sales/booking-fee.ts. Read the file again .... Then the model calls read_file, and a second edit_file succeeds with <- Edited src/sales/booking-fee.ts. If the model reads the file again before its first edit, there is no miss; that is the system prompt’s rule at work.
Open the file. The line should now say tickets < 4.
Step 6: add run_command behind an approval prompt
Why: the agent should check its own fix, and you decide whether a command runs. Add this tool below editFile:
// Add below editFile in agent.ts (step 6)
const runCommand: Tool = {
definition: {
name: "run_command",
description:
"Run a shell command in the project root, such as the tests, and return its exit code and output. " +
"The user must approve every command and may decline. " +
"A command that runs longer than 120 seconds is stopped.",
input_schema: {
type: "object",
properties: {
command: { type: "string", description: "The command line to run, for example 'node --test'." },
},
required: ["command"],
},
},
async run(input) {
const answer = await rl.question(`\n Allow command: ${input.command}\n Run it? [y/N] `);
if (answer.trim().toLowerCase() !== "y") {
throw new Error("The user declined to run this command.");
}
try {
const result = await sh(input.command, { cwd: ROOT, timeout: 120_000 });
return `exit code 0\n${result.stdout}${result.stderr}`.slice(-10_000);
} catch (err) {
const e = err as { code?: number; killed?: boolean; stdout?: string; stderr?: string };
const code = e.killed ? "none (stopped after 120 s)" : e.code;
return `exit code ${code}\n${e.stdout ?? ""}${e.stderr ?? ""}`.slice(-10_000);
}
},
};
Change TOOLS to [listFiles, readFile, editFile, runCommand] and restart. A failing test is not a tool error. The command ran, so the exit code and output go back as a normal result. Output is cut to its last 10,000 characters, because a test runner prints its summary at the end.
Ask: “Run the tests.” You should see Allow command: node --test and Run it? [y/N]. Answer n once. You should see <- ERROR Error: The user declined to run this command. and the model’s reply to that. Ask again and answer y: exit code 0, with two passing tests.
Step 7: watch the step limit
Why: you should see the guard fire before you trust it. Restart with MAX_STEPS=2 node ../agent-lab/agent.ts, and ask: “Read every file and summarize the project.”
You should see two [step] lines, then “(stopped after 2 steps; ask again to continue)”. Type “go on”, and the agent continues from the same history.
The whole agent.ts after step 6
// agent.ts: a small coding agent. One model, one loop, four tools.
// Run it from the folder of the project it should work on.
import Anthropic from "@anthropic-ai/sdk";
import fs from "node:fs/promises";
import path from "node:path";
import readline from "node:readline/promises";
import { exec } from "node:child_process";
import { promisify } from "node:util";
const client = new Anthropic();
const MODEL = process.env.MODEL ?? "claude-opus-5-5";
const MAX_STEPS = Number(process.env.MAX_STEPS ?? 20);
const ROOT = process.cwd();
const sh = promisify(exec);
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.on("close", () => process.exit(0));
const SYSTEM = `You are a coding agent working in the project folder ${ROOT}.
Use list_files to find files. Never guess a path; if a file is not listed, say so.
Read a file before you edit it, and copy old_str exactly from what you read.
Keep answers short, and name the files you read or changed.`;
type Input = Record<string, string>;
type Tool = {
definition: Anthropic.Tool;
run: (input: Input) => Promise<string>;
};
// Every path the model sends is untrusted: resolve it, and refuse anything outside ROOT.
function inProject(p: string): string {
const full = path.resolve(ROOT, p);
const rel = path.relative(ROOT, full);
if (rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) {
throw new Error(`${p} is outside the project folder.`);
}
return full;
}
const SKIP = /(^|[\\/])(node_modules|\.git)([\\/]|$)/;
const listFiles: Tool = {
definition: {
name: "list_files",
description:
"List the files and folders under a folder of the project, recursively. " +
"Folder names end with '/'. node_modules and .git are skipped. " +
"Use this before you read a file whose path you have not seen.",
input_schema: {
type: "object",
properties: {
path: { type: "string", description: "Folder relative to the project root. Default '.'" },
},
},
},
async run(input) {
const entries = await fs.readdir(inProject(input.path ?? "."), {
recursive: true,
withFileTypes: true,
});
const lines: string[] = [];
for (const entry of entries) {
const rel = path.relative(ROOT, path.join(entry.parentPath, entry.name));
if (SKIP.test(rel)) {
continue;
}
lines.push(entry.isDirectory() ? rel + "/" : rel);
}
return lines.slice(0, 300).join("\n") || "(empty folder)";
},
};
const readFile: Tool = {
definition: {
name: "read_file",
description:
"Read a text file of the project and return its contents. " +
"Use it to look at code before you answer a question about it or edit it. " +
"Paths are relative to the project root. Do not use it on folders.",
input_schema: {
type: "object",
properties: {
path: { type: "string", description: "File path relative to the project root." },
},
required: ["path"],
},
},
async run(input) {
const text = await fs.readFile(inProject(input.path), "utf8");
if (text.length > 20_000) {
return text.slice(0, 20_000) + "\n[cut at 20000 characters]";
}
return text;
},
};
const editFile: Tool = {
definition: {
name: "edit_file",
description:
"Replace one exact piece of text in a file with new text. " +
"old_str must appear exactly once in the file, including spaces, tabs and line breaks. " +
"Read the file first and copy old_str from it. " +
"To create a new file, pass an empty old_str and the whole file as new_str.",
input_schema: {
type: "object",
properties: {
path: { type: "string", description: "File path relative to the project root." },
old_str: { type: "string", description: "The exact text to replace. Empty to create a file." },
new_str: { type: "string", description: "The text to put in its place." },
},
required: ["path", "old_str", "new_str"],
},
},
async run(input) {
const file = inProject(input.path);
if (input.old_str === "") {
await fs.mkdir(path.dirname(file), { recursive: true });
await fs.writeFile(file, input.new_str, { flag: "wx" }); // "wx" fails if the file exists
return `Created ${input.path}`;
}
const text = await fs.readFile(file, "utf8");
const count = text.split(input.old_str).length - 1;
if (count === 0) {
throw new Error(`old_str not found in ${input.path}. Read the file again and copy the text exactly.`);
}
if (count > 1) {
throw new Error(`old_str appears ${count} times in ${input.path}. Add nearby lines so it appears once.`);
}
// A function as the replacement keeps "$&" and "$1" in new_str literal.
await fs.writeFile(file, text.replace(input.old_str, () => input.new_str));
return `Edited ${input.path}`;
},
};
const runCommand: Tool = {
definition: {
name: "run_command",
description:
"Run a shell command in the project root, such as the tests, and return its exit code and output. " +
"The user must approve every command and may decline. " +
"A command that runs longer than 120 seconds is stopped.",
input_schema: {
type: "object",
properties: {
command: { type: "string", description: "The command line to run, for example 'node --test'." },
},
required: ["command"],
},
},
async run(input) {
const answer = await rl.question(`\n Allow command: ${input.command}\n Run it? [y/N] `);
if (answer.trim().toLowerCase() !== "y") {
throw new Error("The user declined to run this command.");
}
try {
const result = await sh(input.command, { cwd: ROOT, timeout: 120_000 });
return `exit code 0\n${result.stdout}${result.stderr}`.slice(-10_000);
} catch (err) {
const e = err as { code?: number; killed?: boolean; stdout?: string; stderr?: string };
const code = e.killed ? "none (stopped after 120 s)" : e.code;
return `exit code ${code}\n${e.stdout ?? ""}${e.stderr ?? ""}`.slice(-10_000);
}
},
};
const TOOLS: Tool[] = [listFiles, readFile, editFile, runCommand];
function preview(text: string): string {
return text.replace(/\s+/g, " ").slice(0, 120);
}
// Run one tool call, and turn the outcome, success or error, into a tool_result block.
async function runTool(call: Anthropic.ToolUseBlock): Promise<Anthropic.ToolResultBlockParam> {
console.log(` -> ${call.name} ${JSON.stringify(call.input)}`);
try {
const tool = TOOLS.find((t) => t.definition.name === call.name);
if (tool === undefined) {
throw new Error(`There is no tool named ${call.name}.`);
}
const content = await tool.run(call.input as Input);
console.log(` <- ${preview(content)}`);
return { type: "tool_result", tool_use_id: call.id, content };
} catch (err) {
const content = `Error: ${(err as Error).message}`;
console.log(` <- ERROR ${preview(content)}`);
return { type: "tool_result", tool_use_id: call.id, content, is_error: true };
}
}
// The agent loop: call the model, run the tools it asks for, send the results back, repeat.
async function runTask(messages: Anthropic.MessageParam[]): Promise<void> {
for (let step = 1; step <= MAX_STEPS; step++) {
const response = await client.messages.create({
model: MODEL,
max_tokens: 16000,
system: SYSTEM,
tools: TOOLS.map((t) => t.definition),
messages,
});
// Keep the reply in the history unchanged, thinking blocks included.
messages.push({ role: "assistant", content: response.content });
const usage = response.usage;
const counts = `input_tokens=${usage.input_tokens} output_tokens=${usage.output_tokens}`;
console.log(`[step ${step}] stop_reason=${response.stop_reason} ${counts}`);
const results: Anthropic.ToolResultBlockParam[] = [];
for (const block of response.content) {
if (block.type === "text") {
console.log(`\nagent: ${block.text}`);
} else if (block.type === "tool_use" && response.stop_reason === "tool_use") {
results.push(await runTool(block));
} else if (block.type === "tool_use") {
// The reply was cut off (max_tokens), so this call may be incomplete: answer it, don't run it.
results.push({
type: "tool_result",
tool_use_id: block.id,
content: "Error: not run, because your reply was cut off.",
is_error: true,
});
}
}
if (results.length > 0) {
// All results go back together, in one user message.
messages.push({ role: "user", content: results });
}
if (response.stop_reason !== "tool_use") {
return;
}
}
console.log(`\n(stopped after ${MAX_STEPS} steps; ask again to continue)`);
}
const messages: Anthropic.MessageParam[] = [];
console.log(`Coding agent on ${MODEL} in ${ROOT}. Press Ctrl+C to quit.`);
while (true) {
const task = await rl.question("\nyou: ");
if (task.trim() === "") {
continue;
}
messages.push({ role: "user", content: task });
try {
await runTask(messages);
} catch (err) {
if (!(err instanceof Anthropic.APIError)) {
throw err;
}
console.error(`API error ${err.status}: ${err.message}`);
}
}
Ollama note. Run the same file against a local model, on Ollama v0.40.17. Pull
qwen3-coder(about 19 GB), orqwen3:8b(about 5 GB) on a 16 GB machine. Start Ollama withOLLAMA_CONTEXT_LENGTH=64000 ollama serve, because the default window on most laptops is 4k tokens, and an agent’s history outgrows that in a few steps. Then, fromtinytickets-mini, runANTHROPIC_BASE_URL=http://localhost:11434 ANTHROPIC_API_KEY=ollama MODEL=qwen3-coder node ../agent-lab/agent.ts. Check the window withollama ps, in its CONTEXT column (context length).No code changes, but expect a weaker agent. Smaller models guess paths more often and follow “list first” less often. They sometimes write a tool call as plain text, so the loop sees
end_turnand ends with nothing done. Ollama ignoresis_error(hence theError:prefix) and has notool_choice. If the history outgrows the window, Ollama drops the oldest messages first without an error, and your task is the first to go. Check on your machine that Ollama accepts the SDK’s requests before you rely on the later steps.
Going deeper
The SDK’s tool runner
In @anthropic-ai/sdk, the tool runner is client.beta.messages.toolRunner(), in beta since September 17, 2025 (tool runner docs, checked 2026-11-22). You define each tool with betaTool(), which holds the definition and the function, much like agent.ts‘s Tool objects.
// Excerpt (not run): the tool runner with one tool; readFileTool is defined with betaTool()
const finalMessage = await client.beta.messages.toolRunner({
model: "claude-opus-5-5",
max_tokens: 16000,
max_iterations: 20,
tools: [readFileTool],
messages: [{ role: "user", content: "Why do four tickets still pay the booking fee?" }],
});
max_iterations has no default. In the SDK’s source (1.12.0), the runner loops for as long as the model asks for tools unless you set it. A max_tokens stop ends the runner without an error, so check stop_reason on the final message. The docs also say the input to a betaTool isn’t checked at runtime, so your function must check it.
strict: true
A tool definition can carry strict: true. The API then constrains the model’s input to the schema, the way structured outputs constrain an answer (Module 3). It guarantees that a required path string is present. It doesn’t guarantee that the file exists, so list_files and the error results are still needed.
Tools that Claude was trained on, and tools that run on Anthropic’s side
Anthropic defines a text editor tool and a bash tool with fixed schemas, which Claude models are trained to use (text editor tool). Your program still runs them, as with agent.ts‘s tools. This module wrote its own tools to show the mechanism.
Server tools, such as web search and code execution, run on Anthropic’s side, inside one request. When such a loop reaches its limit, the response stops with stop_reason: "pause_turn", and you send the request again to let it continue.
What Opus 5.5 shows between steps
On Opus 5.5, thinking is always on. The text the model writes between tool calls comes back as thinking blocks, and their text is empty by default. So your trace may show few agent: lines until the final answer. A beta setting returns that text as short progress updates. Count the agent: lines in your own trace to see how much text your runs return.
Common mistakes when you build a loop
- Sending each tool result in its own user message. Symptom: the model stops making parallel calls. Fix: send every result for one response in one user message, results before any text.
- Not answering every tool call. Symptom:
400with “tool_use ids were found without tool_result blocks immediately after”, often after amax_tokensstop. Fix: answer everytool_useblock, with an error result if you didn’t run it. - Throwing on a tool error. Symptom: one missing file ends the whole program. Fix: catch the error and send it as a
tool_resultwithis_error: trueand anError:prefix. - No step limit. Symptom: the same
->line again and again, andinput_tokensclimbing. Fix: stop afterMAX_STEPSmodel calls, and read the trace. - Trusting the model’s paths. Symptom: a read or write outside the project folder. Fix: resolve every path against one root and refuse the rest, as
inProjectdoes. - Replacing with a plain string. Symptom: new code that contained
$&or$1comes out changed. Fix: pass a function toreplace, asedit_filedoes. The SDK fixed the same bug in its own memory tool in version 0.136.0 (October 20, 2026). - Vague tool descriptions. Symptom: the model picks the wrong tool or guesses arguments. Fix: three or four sentences per tool, saying when to use it and when not.
- A small window on Ollama. Symptom: in a long run, the agent forgets its task, with no error. Fix: start Ollama with
OLLAMA_CONTEXT_LENGTH=64000.
Check yourself
Scenario. Omar gives his own agent a run_command tool with no approval prompt and no step limit, and asks it to make the tests pass. In the morning, the log shows the line -> run_command {"command":"npm test"} 212 times. Each one returns the same failing test, and input_tokens is far larger on the last step than on the first. What happened, which two parts of agent.ts would have stopped it, and what would you change in the tool’s result?
Answer
The agent ran away. The model kept asking for the same command, nothing in stop_reason ended the loop, and the history was resent on every step, so each call cost more than the last.
A step limit (MAX_STEPS) would have stopped it after 20 model calls. The approval prompt would have asked a person before every run, and the second identical run would have been easy to refuse.
In the result, return the exit code and the test output, cut to the end, where the failing test’s message is. Then the model sees what failed and can change the code before it runs the tests again. Running the same command on the same code can’t make the test pass.
- Which three parts does a tool definition have, and where do they end up?
- A response holds two
tool_useblocks. What does your next request add? read_filefails withENOENT. What do you send back, and why not stop the loop?- Name three ways the loop in
agent.tscan end. - Leo wants every buyer email tagged and sent to the right person. Workflow or agent, and why?
Answers
- A name, a description and an input schema; the API puts them, as tokens, in the system prompt it builds, before your own system prompt, on every request.
- The response, unchanged, as an
assistantmessage, then oneusermessage with twotool_resultblocks, each with thetool_use_idof its call. - A
tool_resultwithis_error: trueand the error text, because the model can read it and try another path. - Any three of these: the model answers with
end_turn, the step limit is reached, the reply stops atmax_tokens, the model refuses, the window fills, or you press Ctrl+C. - A workflow, because the steps are known in advance: one call to tag the email, then code that routes it.
Cheat sheet
Tools and the agent loop
- Tool definition:
name,description,input_schema, intools; tokens on every call. - Tool call: a
tool_useblock, withstop_reason: "tool_use". - Tool result:
tool_resultblocks with matchingtool_use_id, all in the nextusermessage, first. - Errors: answer anyway, with
is_error: trueand text that says what to try next. - Agent loop: call, run the tools, append, call again, until
end_turn. - Your stops: a step limit, an approval prompt before risky tools, and an answer for cut-off calls.
- Workflow or agent: steps known in advance, workflow; steps depend on results, agent.
- Cost: every step resends the history, so
input_tokensgrows each step.
Figure 9 is the whole module in one picture, on the layout of Figure 5.
context window
+-------------------+
| tool definitions | tool_use tools
| system prompt |--> [Model] ---------> [list_files]
(Developer) task -->| user: task | [read_file]
^ | assistant: calls | [edit_file]
| | user: results |<---- tool_result ---- [run_command]
| | ... more steps | asks you first
+--- answer ---| assistant: answer | |
+-------------------+ [[project files]]
The loop ends on end_turn, or when your code stops it: MAX_STEPS,
a cut-off call (max_tokens), a refusal, a full window, or Ctrl+C.
Each step resends the whole window, so input_tokens grows every step.
Figure 9: the model asks, your code runs the tools and sends the results back, and the loop ends when the model finishes or a guard stops it.
Next, Module 5 connects agent.ts to tools that other programs offer, through MCP, so one tool can serve many agents.
Sources
- Anthropic, Building effective agents, December 19, 2024; Writing effective tools for agents, September 11, 2025.
- Andrej Karpathy, 2025 LLM Year in Review, December 19, 2025.
- Thorsten Ball, How to Build an Agent, April 15, 2025.
- Claude documentation, checked 2026-11-22: tool use overview, define tools, handle tool calls, parallel tool use, stop reasons, build a tool-using agent, tool runner, strict tool use, text editor tool, Messages API, models overview, pricing, release notes.
- Claude Code: CLI reference, How the agent loop works (Agent SDK), and issues 15909, 753 and 164.
@anthropic-ai/sdkon GitHub, version 1.12.0 (the tool runner’s source and the changelog).- OpenAI, function calling guide, checked 2026-11-22.
- Node.js: TypeScript support, releases.
- Ollama docs: Anthropic compatibility, tool calling, context length.