How do you implement an agent loop?

Learning path, stage 4 of 5: Agents, tools and MCP · question 4 of 10

Call the model with tools. If it asks for tools, run them, append the assistant turn and the tool results to the messages, and call again. Stop when it finishes (end_turn) or a guard trips: a step limit, a token or cost budget, a timeout, or a refusal. Production loops add error handling, logging, and approval gates for risky tools.

Rules a correct loop must follow

  • Append the whole assistant content (thinking and tool-use blocks included), not just the text.
  • Return one tool_result per tool_use id, all in a single user message.
  • Pass tool failures back as is_error: true results. Don't crash the loop.
  • Handle every stop reason: end_turn, tool_use, max_tokens, pause_turn (server tools), refusal.
  • Limit everything: steps, wall time, spend.

Build or reuse

  • SDKs ship tool runners that do this loop for you.
  • Hosted agent platforms also run the loop and a sandbox for you.
  • Write it by hand when you need custom control flow.

Sources

Code example

tsx
1// A manual agent loop with guards and error results.
2import Anthropic from "@anthropic-ai/sdk";
3
4const client = new Anthropic();
5
6export async function runAgent(
7 goal: string,
8 tools: Anthropic.Tool[],
9 handlers: Record<string, (input: unknown) => Promise<string>>,
10 maxSteps = 15,
11) {
12 const messages: Anthropic.MessageParam[] = [{ role: "user", content: goal }];
13
14 for (let step = 0; step < maxSteps; step++) {
15 const res = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 16000, tools, messages });
16 messages.push({ role: "assistant", content: res.content });
17
18 if (res.stop_reason === "end_turn") {
19 return res.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
20 }
21 if (res.stop_reason === "refusal" || res.stop_reason === "max_tokens") {
22 throw new Error(`Stopped: ${res.stop_reason}`);
23 }
24 if (res.stop_reason === "pause_turn") continue; // server tool paused; resend to resume
25
26 const results: Anthropic.ToolResultBlockParam[] = [];
27 for (const call of res.content.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use")) {
28 try {
29 const handler = handlers[call.name];
30 if (!handler) throw new Error(`Unknown tool ${call.name}`);
31 results.push({ type: "tool_result", tool_use_id: call.id, content: await handler(call.input) });
32 } catch (e) {
33 results.push({ type: "tool_result", tool_use_id: call.id, content: String(e), is_error: true });
34 }
35 }
36 messages.push({ role: "user", content: results }); // all results in ONE message
37 }
38 throw new Error("Step limit reached");
39}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod @modelcontextprotocol/sdk, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app