Skip to content

Drive the agent loop on stop_reason

Write an agentic loop that keeps going while stop_reason is "tool_use", ends on "end_turn", and appends every tool result to the conversation before the next request.

Scenario

Your Customer Support Resolution Agent has four MCP tools: get_customer, lookup_order, process_refund and escalate_to_human. In testing, a customer asks for a refund on a broken kettle.

Claude replies: "Once the order is confirmed as resolved on our side, I'll start your refund." and asks for lookup_order in the same response.

The loop checks the reply for the word "resolved", decides the work is done, and closes the chat. The order was never looked up. The model told the loop exactly what it wanted; the loop was listening to the wrong thing.

Explanation

The loop. Claude can't run your tools itself. When you call the Messages API with your own tools, your code drives a loop (the Agent SDK runs the same loop for you):

  1. Send the conversation and the tool definitions.
  2. Read stop_reason on the response.
  3. If it is "tool_use": run every tool_use block in the response, then append two messages: the assistant response as it came back, and a user message holding one tool_result per call, each with the matching tool_use_id. Go to 1.
  4. If it is "pause_turn": a server tool such as web search hit its iteration limit mid-turn. This is not a failure: append the assistant response as it came back and send again, and Claude continues. Go to 1.
  5. If it is "end_turn": Claude has finished. Return the final text.

Any other stop reason ("max_tokens", "model_context_window_exceeded", "refusal", "stop_sequence") also leaves the loop, but it is not success: handle it on purpose. A response cut off at max_tokens or at the context window may hold an unfinished tool call.

History is the agent's memory. Each request is stateless. Claude knows what get_customer returned only because that result sits in the messages you send. The tool results go first in the user message, before any text, and directly after the assistant turn that asked for them.

Let the model decide the next step. Claude chooses the next tool from what the results so far show: a damaged item may need lookup_order twice, a billing dispute may end in escalate_to_human. A hard-coded sequence (always customer, then order, then refund) can't adapt to that.

Three stop conditions that look right and aren't:

Anti-pattern Why it fails
Parse the text for "done", "resolved", "anything else?" Phrasing varies; Claude often writes text and a tool call in one response
Stop when the response contains text Same reason: text and tool_use blocks share responses
Stop after N iterations A counter doesn't know whether the work is done

A turn limit still has a place: as a backstop against runaway loops, set well above normal use and treated as a failure. The Agent SDK works the same way: its maxTurns option ends a session with an error_max_turns result, not a success.

Worked example

Before: a loop the support team shipped first.

while (true) {
  const res = await callClaude(messages);
  const text = textOf(res);
  if (text.includes("resolved")) break;
  const results = await runTools(res.content);
  messages.push({ role: "user", content: results });
}

Two faults: it stops on a word in the text, and it never appends the assistant turn, so the history never shows which tool calls the results answer.

After:

const more = ["tool_use", "pause_turn"];
let res = await callClaude(messages);
while (more.includes(res.stop_reason)) {
  messages.push({
    role: "assistant", content: res.content });
  if (res.stop_reason === "tool_use")
    messages.push({ role: "user",
      content: await runTools(res.content) });
  res = await callClaude(messages);
}
if (res.stop_reason !== "end_turn") {
  return handleStop(res);
}
return textOf(res);

The model's own signal drives the loop, every result is in the history before the next call, a pause_turn goes back as it is so a server tool can finish, and stops other than end_turn go to a handler (retry with more tokens, log a refusal) instead of being shown to the customer as an answer. In production you would also count turns and fail loudly at, say, 40, far above what any real case needs.