IamBishal

Module 1Lesson 2 of 2Hands-on

1.2 A minimal agent loop over MCP tools

Build the minimal agent loop for Helpline triage: discover the MCP tools with mcp.Client (following pagination), convert them to Claude tool definitions, handle every stop_reason, feed tool, protocol and transport failures back with is_error, test it all with a scripted FakeModel, and capture one real run on claude-opus-5-5 (5 steps, $0.0962).

Lesson 1 described the agent loop. This lesson builds it: an agent that reads Helpline's tools over MCP, hands them to Claude, runs the calls the model asks for, and stops when the model is done. It is deliberately minimal. Its only stop condition of its own is a safety cap on steps, which Lesson 3 replaces with real budgets.

By the end of the lesson you will be able to:

  • list every tool on an MCP server with mcp.Client, following pagination, and turn each into a Claude tool definition
  • write a Model protocol with a scripted FakeModel for tests and an AnthropicModel for real runs
  • write a loop that reads stop_reason before content and has an explicit action for every value
  • send every tool result of a step back in one user message, with failures flagged is_error, whether the tool or the connection failed
  • test all of that offline, then run it once against claude-opus-5-5 and price the run from its usage

Before you start. You need Lesson 1, Python 3.12 with uv, and basic asyncio: the loop and its tests are async, and the tests run on the anyio pytest plugin the folder installs. The tool names come from Helpline, the server built in Build a production MCP server; the companion folder carries an unchanged copy in helpline/, so you don't need to have built it. The real run in step 5 needs an Anthropic API key with credit; nothing else does. The folder pins the anthropic SDK at 2.12.0 and mcp at 2.3.0, and has 14 tests. Every listing and output below comes from it.

text
02-a-minimal-agent-loop-over-mcp-tools/
├── agent/
│   ├── models.py    # Usage, Turn, Model, FakeModel, AnthropicModel
│   ├── tools.py     # Helpline's MCP tools as Claude tool definitions
│   ├── loop.py      # the agent loop
│   ├── pricing.py   # cost from reported usage
│   └── triage.py    # the system prompt and the task
├── helpline/        # the MCP server, unchanged
├── run_real.py      # one run against Claude
└── tests/

1. Step 1: Connect to Helpline and list its tools

The agent package never imports Helpline's code; it only speaks MCP. The tests and run_real.py start the Helpline server object in the same process and hand it to the MCP SDK's Client, which connects to it in-process. Pointed at a URL instead, the same Client would use Streamable HTTP. Here is the test fixture:

python
@pytest.fixture
async def helpline():
    store = HelplineStore()
    async with Client(build_server(store, kb_delay_seconds=0)) as client:
        yield McpTools(client), store

tools.py starts with its imports and the outcome type:

python
from __future__ import annotations

from dataclasses import dataclass
from typing import Any

from mcp import Client
from mcp.shared.exceptions import MCPError

@dataclass(frozen=True)
class ToolOutcome:
    text: str
    is_error: bool

McpTools wraps that client. It lists the tools and turns each one into a Claude tool definition. MCP and Claude describe a tool the same way, so the conversion is a rename: the MCP input schema is already JSON Schema and carries over unchanged.

python
def to_claude_tool(tool: Any) -> dict[str, Any]:
    """MCP tool -> Claude tool definition. The JSON Schema carries over as it is."""
    return {
        "name": tool.name,
        "description": tool.description or "",
        "input_schema": tool.input_schema,
    }

class McpTools:
    def __init__(self, client: Client) -> None:
        self.client = client

    async def definitions(self) -> list[dict[str, Any]]:
        """Every tool on the server, following tools/list pagination to the last page."""
        tools, cursor = [], None
        while True:
            page = await self.client.list_tools(cursor=cursor)
            tools += page.tools
            cursor = page.next_cursor
            if not cursor:
                return [to_claude_tool(t) for t in tools]

    async def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome:
        try:
            result = await self.client.call_tool(name, arguments)
        except MCPError as exc:  # a protocol error: report it to the model as a failed call
            return ToolOutcome(f"Protocol error {exc.error.code}: {exc.error.message[:200]}", True)
        except Exception as exc:  # transport failure: a short, safe message, no server detail
            return ToolOutcome(f"{name} could not be reached ({type(exc).__name__}).", True)
        text = "\n".join(c.text for c in result.content if getattr(c, "text", None))
        return ToolOutcome(text, bool(result.is_error))

tools/list is paginated: a server may return its tools a page at a time, with a next_cursor for the rest. Helpline's five tools fit on one page, but a client that reads only the first page of a larger server loses the rest without any error, and the model never learns they exist. definitions keeps asking until there is no cursor. A test serves Helpline's real tools two to a page to prove it.

call returns a ToolOutcome: the text the model will read, and whether it is an error. Three kinds of failure end up there, and none of them raises inside the loop:

  • A tool-result error. Helpline answers a bad ticket id with an error that carries a hint ending "use search_tickets to look one up", and the model should see that hint.
  • A protocol error. The MCP layer refused the call. Its message is cut to 200 characters, because the model reads it and it came from another party.
  • A transport failure. The connection dropped, timed out or closed. The model gets a short message naming the tool and the exception type, and no server detail. A test with a client whose connection always drops gets get_ticket could not be reached (ConnectionResetError).

The first test checks what the model is offered:

python
async def test_mcp_tools_become_claude_tool_definitions(helpline):
    tools, _ = helpline
    defs = await tools.definitions()
    assert [d["name"] for d in defs] == [
        "search_tickets",
        "get_ticket",
        "search_knowledge_base",
        "draft_reply",
        "escalate_ticket",
    ]
    assert set(defs[0]) == {"name", "description", "input_schema"}
    assert defs[1]["input_schema"]["required"] == ["ticket_id"]

2. Step 2: One protocol, two models

The loop shouldn't care whether a real model or a script produced a response. So it depends on a small protocol, Model, with one method. That method takes the system prompt, the tool definitions and the messages, and returns a Turn. Here is everything except the real model:

python
@dataclass(frozen=True)
class Usage:
    input_tokens: int = 0
    output_tokens: int = 0
    cache_read: int = 0
    cache_write: int = 0

    def __add__(self, other: Usage) -> Usage:
        return Usage(
            self.input_tokens + other.input_tokens,
            self.output_tokens + other.output_tokens,
            self.cache_read + other.cache_read,
            self.cache_write + other.cache_write,
        )

@dataclass(frozen=True)
class Turn:
    """One model response: why it stopped, its content blocks, what it cost."""

    stop_reason: str
    content: list[dict[str, Any]]
    usage: Usage = field(default_factory=Usage)

    def tool_calls(self) -> list[dict[str, Any]]:
        return [b for b in self.content if b.get("type") == "tool_use"]

    def text(self) -> str:
        return "".join(b.get("text", "") for b in self.content if b.get("type") == "text")

class Model(Protocol):
    name: str

    async def complete(
        self, *, system: str, tools: list[dict[str, Any]], messages: list[dict[str, Any]]
    ) -> Turn: ...

# --- the fake ---------------------------------------------------------------

_ids = iter(range(1, 1_000_000))

def tool_use(name: str, **arguments: Any) -> dict[str, Any]:
    return {
        "type": "tool_use",
        "id": f"toolu_fake_{next(_ids):04d}",
        "name": name,
        "input": arguments,
    }

def calls(*blocks: dict[str, Any], text: str = "", usage: Usage | None = None) -> Turn:
    """A turn that asks for one or more tool calls."""
    content = ([{"type": "text", "text": text}] if text else []) + list(blocks)
    return Turn("tool_use", content, usage or Usage(1200, 80))

def answer(text: str, usage: Usage | None = None) -> Turn:
    """A final turn: the model is done."""
    return Turn("end_turn", [{"type": "text", "text": text}], usage or Usage(1500, 160))

Step = Turn | Callable[[list[dict[str, Any]]], Turn]

class FakeModel:
    """Replays a script of turns. A step may be a function of the messages so far."""

    name = "fake"

    def __init__(self, script: Sequence[Step]) -> None:
        self.script = list(script)
        self.requests: list[dict[str, Any]] = []

    async def complete(self, *, system, tools, messages) -> Turn:
        self.requests.append({"system": system, "tools": tools, "messages": list(messages)})
        if not self.script:
            raise AssertionError("FakeModel ran out of scripted turns")
        step = self.script.pop(0)
        return step(messages) if callable(step) else step

Turn is the code's name for one model response. In prose this tutorial says step for one model call plus the tool calls it asks for. FakeModel replays a script, so every test runs offline and identically. calls(tool_use("get_ticket", ticket_id="HL-1003")) is a scripted response that asks for one tool call, and answer("...") is a final one. Every request the loop sends is recorded in requests, so tests can check exactly what went to the model.

AnthropicModel is the real one. MODEL_ID at the top of models.py is "claude-opus-5-5":

python
class AnthropicModel:
    """Claude through the anthropic SDK (reads ANTHROPIC_API_KEY from the environment)."""

    def __init__(self, client: Any = None, model: str = MODEL_ID, effort: str = "medium") -> None:
        if client is None:
            import anthropic

            client = anthropic.AsyncAnthropic()
        self.client = client
        self.name = model
        self.effort = effort

    async def complete(self, *, system, tools, messages) -> Turn:
        response = await self.client.messages.create(
            model=self.name,
            max_tokens=16000,
            system=system,
            tools=tools,
            messages=messages,
            # Effort is the depth control on this model; manual thinking budgets return a 400.
            # tool_choice stays at its default, auto: forcing a tool returns a 400 here.
            output_config={"effort": self.effort},
        )
        u = response.usage
        return Turn(
            stop_reason=response.stop_reason,
            # Keep every block (thinking included) so it can be sent back unchanged.
            content=[b.model_dump(mode="json", exclude_none=True) for b in response.content],
            usage=Usage(
                u.input_tokens,
                u.output_tokens,
                u.cache_read_input_tokens or 0,
                u.cache_creation_input_tokens or 0,
            ),
        )

Three choices in that call follow from how claude-opus-5-5 behaves:

  • Effort is set explicitly. It controls how much the model thinks, and defaults to medium on this model. Thinking can't be turned off on claude-opus-5-5: a request that disables it is rejected at every effort level. Manual thinking budgets return a 400 too. So effort is the only depth control, and to spend less you lower the effort rather than switch thinking off.
  • tool_choice is left at its default, auto. Forcing a tool with any or tool returns a 400 on this model. The system prompt steers which tool to use.
  • Content blocks are kept exactly as received, thinking blocks included, so the next request can send the assistant's response back unchanged.

A test checks the request shape against a recording client, without calling the API. It expects model claude-opus-5-5, output_config {"effort": "medium"}, and no tool_choice or thinking key.

3. Step 3: The loop

loop.py defines the result type and the safety cap first:

python
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any

from agent.models import Model, Turn, Usage
from agent.tools import McpTools

SAFETY_CAP_STEPS = 25

class SafetyCapReached(RuntimeError):
    """The run hit the step cap. In a minimal loop this is the only brake."""

@dataclass
class RunResult:
    outcome: str  # done | truncated | refused | stopped:<reason>
    final_text: str
    steps: int
    usage: Usage
    trace: list[dict[str, Any]] = field(default_factory=list)
python
async def run_agent(
    model: Model,
    tools: McpTools,
    task: str,
    *,
    system: str,
    max_steps: int = SAFETY_CAP_STEPS,
) -> RunResult:
    definitions = await tools.definitions()
    messages: list[dict[str, Any]] = [{"role": "user", "content": task}]
    usage = Usage()
    trace: list[dict[str, Any]] = []

    for step in range(1, max_steps + 1):
        turn: Turn = await model.complete(system=system, tools=definitions, messages=messages)
        usage = usage + turn.usage
        record: dict[str, Any] = {
            "step": step,
            "stop_reason": turn.stop_reason,
            "usage": vars(turn.usage),
            "tool_calls": [],
        }
        trace.append(record)

        # Read stop_reason before content: it says what the content is.
        if turn.stop_reason == "end_turn":
            return RunResult("done", turn.text(), step, usage, trace)
        if turn.stop_reason in ("max_tokens", "model_context_window_exceeded"):
            # Cut off (output limit or context window): a half-written tool call must not run.
            return RunResult("truncated", turn.text(), step, usage, trace)
        if turn.stop_reason == "refusal":
            return RunResult("refused", turn.text(), step, usage, trace)
        if turn.stop_reason == "pause_turn":
            # A server-side tool paused the turn: send it back unchanged to continue.
            messages.append({"role": "assistant", "content": turn.content})
            continue
        if turn.stop_reason != "tool_use":
            return RunResult(f"stopped:{turn.stop_reason}", turn.text(), step, usage, trace)

        # The assistant turn goes back exactly as received, thinking blocks included.
        messages.append({"role": "assistant", "content": turn.content})
        results = []
        for call in turn.tool_calls():
            outcome = await tools.call(call["name"], call["input"])
            record["tool_calls"].append(
                {"name": call["name"], "input": call["input"], "is_error": outcome.is_error}
            )
            results.append(
                {
                    "type": "tool_result",
                    "tool_use_id": call["id"],
                    "content": outcome.text,
                    "is_error": outcome.is_error,
                }
            )
        # Every result for this turn goes back in one user message.
        messages.append({"role": "user", "content": results})

    raise SafetyCapReached(f"stopped after {max_steps} steps without finishing")

Every stop_reason gets an explicit action:

stop_reasonWhat the loop does
tool_useRuns every tool call, sends the results back, starts the next step
end_turnReturns done with the final text
max_tokensReturns truncated and runs nothing: a cut-off tool call is incomplete
model_context_window_exceededThe same: the docs say to treat the response as truncated
refusalReturns refused; the model declined, and stop_details says why
pause_turnSends the assistant content back unchanged and continues, which is how a paused server-tool loop resumes
stop_sequence, or anything newReturns stopped:<reason>

pause_turn only happens with server-side tools, which this agent doesn't use, and this loop doesn't turn on context compaction, so a compaction stop never arrives either. Handling it costs two lines, and it means a later change doesn't break the loop.

Three rules in the tool branch matter more than they look:

  • One user message per step. When the model asks for several calls at once, every tool_result goes back in a single user message, each matched to its call by tool_use_id. A test checks it: after a step with two calls, the next request ends with one user message holding two results whose ids match the calls.
  • Errors are flagged, not hidden. A failed call goes back with is_error: true and its text. In the test, the model asks for HL-9999, gets Helpline's hint back, and finds the right ticket on its next step.
  • Nothing runs after a cut-off. For max_tokens, model_context_window_exceeded, refusal and any unknown reason, the test checks that the requested escalate_ticket call never ran and no escalation exists.
The loop checks stop_reason first. Only tool_use runs tools, and all of a step's results go back in one message.

The error-feedback test, where the model recovers from a bad ticket id:

python
async def test_tool_errors_go_back_to_the_model_flagged(helpline):
    tools, _ = helpline
    model = FakeModel(
        [
            calls(tool_use("get_ticket", ticket_id="HL-9999")),
            calls(tool_use("get_ticket", ticket_id="HL-1003")),
            answer("Found it on the second try."),
        ]
    )
    result = await run_agent(model, tools, "Read the ticket.", system=SYSTEM)
    first_result = model.requests[1]["messages"][-1]["content"][0]
    assert first_result["is_error"] is True
    assert "use search_tickets to look one up" in first_result["content"]
    assert result.outcome == "done"

And the stop-reason test, which hands the loop a response that asks for escalate_ticket but stopped for another reason:

python
@pytest.mark.parametrize(
    ("stop_reason", "outcome"),
    [
        ("max_tokens", "truncated"),
        ("model_context_window_exceeded", "truncated"),
        ("refusal", "refused"),
        ("stop_sequence", "stopped:stop_sequence"),
    ],
)
async def test_other_stop_reasons_end_the_run_without_running_tools(helpline, stop_reason, outcome):
    tools, store = helpline
    cut = Turn(stop_reason, [tool_use("escalate_ticket", ticket_id="HL-1003")])
    result = await run_agent(FakeModel([cut]), tools, "Go.", system=SYSTEM)
    assert result.outcome == outcome
    assert result.trace[0]["tool_calls"] == []
    assert store.open_escalation("HL-1003") is None

The last line is the safety cap. If the model never finishes, SafetyCapReached is raised after 25 steps. A test with a model that searches forever confirms the loop sent exactly 25 requests. The cap has two flaws, and both are acceptable only because it is a placeholder. It says nothing about why the run should end. And it raises, so the trace and usage of the run you most want to inspect are lost. Lesson 3 replaces it with budgets that return a normal result with the trace attached.

The task itself is in triage.py:

python
SYSTEM = """You are Helpline's triage assistant. You help a support engineer with one ticket.
Use the tools to read the ticket, look for similar tickets and knowledge-base articles,
and save a draft reply with draft_reply. A person reviews and sends every draft.
Do not call escalate_ticket. If the ticket needs escalation, say so in your final answer.
Finish with a short summary: what you found, the draft id, and whether to escalate."""

def task_for(ticket_id: str) -> str:
    return f"Triage ticket {ticket_id}."

4. Step 4: Test it offline

This test scripts a whole triage through FakeModel against the real Helpline server:

python
async def test_happy_path_triage(helpline):
    tools, store = helpline
    model = FakeModel(
        [
            calls(tool_use("get_ticket", ticket_id="HL-1003")),
            calls(
                tool_use("search_tickets", query="webhook"),
                tool_use("search_knowledge_base", query="webhook 401 signing secret rotation"),
            ),
            calls(
                tool_use(
                    "draft_reply",
                    ticket_id="HL-1003",
                    message="Your receiver may still check the old secret.",
                    article_ids=["KB-103"],
                )
            ),
            answer("Draft 1 saved for HL-1003. Recommend escalation: orders are not syncing."),
        ]
    )
    result = await run_agent(model, tools, task_for("HL-1003"), system=SYSTEM)
    assert result.outcome == "done"
    assert result.steps == 4
    assert [c["name"] for s in result.trace for c in s["tool_calls"]] == [
        "get_ticket",
        "search_tickets",
        "search_knowledge_base",
        "draft_reply",
    ]
    assert store.db.execute("select count(*) from drafts").fetchone()[0] == 1

The model reads the ticket. In the next step it searches tickets and the knowledge base together, then saves a draft, then finishes. The test checks the outcome, the four steps, the order of the tool calls, and that exactly one draft exists in Helpline. The other tests cover pagination, parallel results, error feedback, each stop reason, the safety cap, cost, the request shape and transport failures:

bash
uv run pytest -v tests
text
tests/test_loop.py::test_mcp_tools_become_claude_tool_definitions PASSED
tests/test_loop.py::test_definitions_follow_pagination_to_the_last_page PASSED
tests/test_loop.py::test_happy_path_triage PASSED
tests/test_loop.py::test_parallel_results_go_back_in_one_user_message PASSED
tests/test_loop.py::test_tool_errors_go_back_to_the_model_flagged PASSED
tests/test_loop.py::test_other_stop_reasons_end_the_run_without_running_tools[max_tokens-truncated] PASSED
tests/test_loop.py::test_other_stop_reasons_end_the_run_without_running_tools[model_context_window_exceeded-truncated] PASSED
tests/test_loop.py::test_other_stop_reasons_end_the_run_without_running_tools[refusal-refused] PASSED
tests/test_loop.py::test_other_stop_reasons_end_the_run_without_running_tools[stop_sequence-stopped:stop_sequence] PASSED
tests/test_loop.py::test_pause_turn_is_sent_back_and_continued PASSED
tests/test_loop.py::test_without_a_brake_a_looping_model_only_stops_at_the_safety_cap PASSED
tests/test_loop.py::test_cost_from_usage PASSED
tests/test_loop.py::test_anthropic_model_request_shape_and_turn_conversion PASSED
tests/test_loop.py::test_transport_failure_becomes_a_short_tool_error PASSED
============================== 14 passed in 1.49s ==============================

5. Step 5: One real run

run_real.py runs the agent once against Claude. Helpline still runs in-process; only the model is real. The system prompt in triage.py asks for a triage, a saved draft and a summary, and it includes: "Do not call escalate_ticket. If the ticket needs escalation, say so in your final answer." That sentence is the only thing between the model and escalate_ticket in this lesson. Lesson 4 replaces it with an approval gate.

bash
cp .env.example .env    # then set ANTHROPIC_API_KEY
uv run --env-file .env python run_real.py HL-1003

The run captured for this lesson used claude-opus-5-5 at effort medium on 2026-11-20 (UTC). Its trace is in runs/HL-1003.json:

Stepstop_reasonTool callsInput tokensOutput tokens
1tool_useget_ticket1,77257
2tool_usesearch_knowledge_base, search_tickets2,211137
3tool_usesearch_tickets, search_tickets2,786178
4tool_usedraft_reply3,393789
5end_turn4,707675
text
done in 5 steps, {'input_tokens': 14869, 'output_tokens': 1836, 'cache_read': 0, 'cache_write': 0}, $0.0962

The input column grows every step, because each request resends the conversation so far. The output column includes the model's thinking: thinking tokens are billed as output tokens. The cost comes from pricing.py:

The captured run: parallel calls in step 2, a saved draft in step 4, and no escalation.
python
# model: (input, output, cache write 5m, cache hit)
PRICES = {
    "claude-opus-5-5": (4.00, 20.00, 5.00, 0.20),
    "fake": (0.0, 0.0, 0.0, 0.0),
}

def cost_usd(model: str, usage: Usage) -> float:
    price_in, price_out, price_write, price_hit = PRICES[model]
    total = (
        usage.input_tokens * price_in
        + usage.output_tokens * price_out
        + usage.cache_write * price_write
        + usage.cache_read * price_hit
    ) / 1_000_000
    return round(total, 6)

For claude-opus-5-5 the rates are $4 per million input tokens, $20 per million output tokens, $5 per million 5-minute cache writes and $0.20 per million cache hits, checked on 2026-11-21. This run used no caching, so 14,869 × $4 + 1,836 × $20, per million tokens, comes to $0.0962.

The final summary reported that draft 1 was saved and not sent, that the ticket needed escalating at urgent severity, and that the agent had not escalated it. It cited KB-103 ("Rotate a webhook signing secret") and KB-104 ("Webhook retry schedule"), and described HL-1010, the only other webhook ticket, as a routine question about retries from the same customer. It also warned the reviewer about the draft: the draft told the customer that engineering had already been asked to look, so it should only be sent once the escalation was filed. Nothing in the loop checked the draft, so the over-promise was saved. Lesson 4 adds a check that refuses a draft claiming an escalation that hasn't happened.

6. Common problems

A 400 after adding tool_choice. Forcing a tool isn't accepted on claude-opus-5-5. Remove the parameter and steer from the system prompt.

The API rejects a tool_result. Every tool_use_id must match a tool_use block in the previous assistant message, and all of a step's results must go back in one user message.

A 400 on a later request. Check that the assistant's response is appended exactly as received. The loop keeps every block, thinking included; rebuilding the message from selected blocks, or editing earlier messages, changes what the API sees.

Strange tool calls after a long answer. The code read the content before checking stop_reason and ran a tool_use block from a response that was cut off. Branch on stop_reason first.

run_real.py fails with an authentication error. The key is read from the environment. Copy .env.example to .env, set ANTHROPIC_API_KEY, and run with uv run --env-file .env. Never commit .env.

7. Exercise: a failing call inside a parallel step

Write a FakeModel test where one step asks for get_ticket on HL-9999, which doesn't exist, and search_knowledge_base together. The script then saves a draft and ends with answer(...).

Expected result. The request after that step ends with one user message holding two tool_result blocks, each matched to its tool_use_id. Only the get_ticket result has is_error set, and the run ends as done.

Hint. Copy test_parallel_results_go_back_in_one_user_message and change its script; model.requests holds every request the loop sent.

Verify. uv run pytest tests should report 15 passed.

Common mistake. Asserting on the error's wording instead of the is_error flag, so the test breaks when Helpline's message changes.

8. Why not the SDK's tool runner?

The anthropic SDK has a tool runner that drives this loop for you, and helpers that turn MCP tools into runner tools; they work with mcp 2.3.0. This tutorial builds the loop by hand anyway, because Lessons 3 and 4 put limits and gates inside every step, before each model call and each tool call. That takes a loop you own.

9. What comes next

The loop works, and nothing in it is bounded. A model that never finishes runs 25 steps before the cap stops it and throws its trace away. A failing tool gets called as often as the model likes, and a run's cost is known only afterwards. Lesson 3 replaces the cap with step, token, cost and time budgets, adds a circuit breaker per tool, and refuses the same call made a third time.

Key Takeaways

  • Discover every tool on an MCP server with mcp.Client, following tools/list pagination, and convert each to a Claude tool definition unchanged.
  • Implement a Model protocol twice: a scripted FakeModel for tests and an AnthropicModel that calls claude-opus-5-5 with effort set and tool_choice left at auto.
  • Write a loop that branches on stop_reason first, with an explicit action for tool_use, end_turn, max_tokens, refusal, pause_turn and anything else.
  • Send all of a turn's tool_results back in one user message, matched by tool_use_id, with is_error on failures.
  • Compute a run's cost from reported usage and the model's prices.
  • Explain why the tutorial writes the loop by hand instead of using the SDK tool runner.

Discussion

Ask questions, share what you learned, and help others.

    Loading discussion…

    Bishal SahaLet's build together

    Have a system to design, or an AI feature to get right?

    Tell me about the problem. You'll get a clear, honest view of the best way forward.

    • Reply within 24 hoursOn business days, with my honest view and a next step.
    • Accepting select engagementsArchitecture, AI features and full builds.
    • Remote, worldwideWorking with startups, SMEs and enterprises.