Two small weathered robots in front of a toy carousel

Claude asked for fourteen tool calls. My code ran every one of them. That gap between asking and doing is the key to understanding agents. An agent is a loop. The model asks for tools and your code decides whether to run them and when to give up.

To see that loop up close, I built a console app that sorts messages from a made-up dead-letter queue into categories based on their content. The app uses Anthropic’s official C# SDK and no agent framework. The full code is on GitHub. There is also a Java version built on Anthropic’s Java SDK. This post walks through the C# version.

What Makes It an Agent

“Agent” gets defined in several ways. Anthropic’s Building effective AI agents separates two designs. In a workflow, code sets the path ahead of time. In an agent, “LLMs dynamically direct their own processes and tool usage.”

In my app, the prompt asks Claude to triage seven messages. Claude chooses which tools to call. The app runs them and sends back the results. The API does not remember anything between calls. Each request from the app includes the full conversation history.

The Two Tools

I gave Claude two tools. get_dlq_message returns one message by its id from seven hard-coded messages that stand in for a dead-letter queue. There is no real queue behind it. classify records the category Claude picks for a message. Every request includes both tool definitions so Claude can decide which one to ask for.

Bad input and unknown tool names come back as a tool_result with is_error: true. This gives the model a chance to correct itself and try again. Tool input is model output, so I validate it like any other untrusted input.

ToolWhat it doesWhat can go wrong
get_dlq_message(id)Returns one fake message: error, delivery count, bodyUnknown or missing id
classify(id, category)Records transient, poison, code-bug, or unknownUnknown id, category outside the list

The Loop

The heart of the console app is the agent loop. Claude decides whether to ask for another tool. The for loop calls Claude at most ten times. Without that limit, a confused or manipulated model could keep running up the bill.

Here is how my run went:

  1. The loop sends the prompt and tool list through createMessage, my wrapper around the SDK’s client.Messages.Create. Claude asks for seven get_dlq_message calls and stops with tool_use.
  2. Dispatch runs seven times and produces one tool_result per request.
  3. The loop sends the prompt, Claude’s reply, all seven results in one user message, and the tool list. Claude asks for seven classify calls and stops with tool_use.
  4. Dispatch runs seven more times, and the results go into another user message.
  5. The loop sends the whole history and the tool list. Claude returns a text summary and stops with end_turn.
  6. The loop sees end_turn and returns.

Trimmed from the real code (setup, request building, logging, stop checks, and block copying left out):

for (int iteration = 1; iteration <= MaxIterations; iteration++)
{
    // build the request: model, tools, and the whole conversation so far
    var response = await createMessage(request);

    // refusal, max_tokens, or any unexpected stop reason: throw before running tools

    // start two empty lists: assistantContent and toolResults
    foreach (ContentBlock block in response.Content)
    {
        // copy every block into the assistant turn
        if (block.TryPickToolUse(out ToolUseBlock? toolUse))
        {
            var result = tools.Dispatch(toolUse.Name, toolUse.Input);
            toolResults.Add(new ToolResultBlockParam
            {
                ToolUseID = toolUse.ID,
                Content = result.Content,
                IsError = result.IsError
            });
        }
    }

    messages.Add(new AssistantMessageParam { Content = assistantContent });

    switch (response.StopReason)
    {
        case "tool_use":
            messages.Add(new UserMessageParam { Content = toolResults });
            break;
        case "end_turn":
            return;
    }
}

throw new InvalidOperationException($"No end_turn after {MaxIterations} iterations; stopping.");
The same loop in Java (click to expand)

Trimmed from the real code (setup and logging left out):

for (int iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
    // conversation is a builder that holds the model, tools, and history
    MessageCreateParams request = conversation.build();
    Message response = createMessage.apply(request);

    // refusal, max_tokens, an unexpected stop reason, or an unknown block: throw before running tools
    StopReason stopReason = requireSupportedStopReason(response);
    requireSupportedContent(response);

    // the SDK adds the whole reply as the assistant turn
    conversation.addMessage(response);
    if (stopReason.equals(StopReason.END_TURN)) {
        return;
    }
    // run every tool call and send the results in one user message
    conversation.addUserMessageOfContentBlockParams(runTools(response, tools));
}

throw new IllegalStateException("No end_turn after %d iterations; stopping.".formatted(MAX_ITERATIONS));

Two rules matter here. Every tool_use needs a tool_result in the next user message and Claude’s reply goes back into the history unchanged with its thinking blocks included.

Stop reasonWhat happens
tool_useRun the tools, send the results, call again
end_turnDone
refusalStop and report the category
max_tokensStop because the reply was cut off
Anything else, such as pause_turnStop

For the last three rows, the loop throws before running any tool.

The docs list more stop reasons than I handle. I fail on the rest instead of guessing.

One Real Run

  • Totals: 3 API calls, 14 tool calls, 6,052 input and 1,768 output tokens, about 15 seconds.
  • Cost: about $0.06 on claude-opus-5-5 at effort medium ($4 / $20 per million input / output tokens, pricing).
MessageWhat I wrote it to beWhat Claude said
SQL timeouttransienttransient
Truncated JSONpoisonpoison
Null shipping addresscode-bugcode-bug
503 from a downstream servicetransienttransient
Unknown event typepoisonpoison
Quantity of zero, divide by zerocode-bugcode-bug
Empty order linesambiguous, expected unknowncode-bug
Sequence diagram of one run: my loop calls Claude three times and runs fourteen tool calls between them, with the untrusted message bodies marked

What Surprised Me

The first surprise was how little back-and-forth this took. The fourteen tool calls needed only three round trips because Claude asked for seven get_dlq_message calls in one reply and seven classify calls in the next. Logging was also harder than I expected. Serializing the SDK’s request object logged a wrapper that included a headers field, and headers can carry credentials. The actual body is in request.RawBodyData. Those logs showed me that the history is the memory. Every request resends the whole conversation, so input grew from 621 tokens on the first call to 2,262 on the second and 3,169 on the third.

What This Doesn’t Mean

This task didn’t need an agent. The steps are fixed, so one call per message with structured output should do the job. It would also stop text in one message from influencing the label on another. I used the loop to learn how it works. Two runs gave the same labels but that’s too few to say how stable they are. This also isn’t production code. It has no retries of my own, no persistence, and no way to act on a label.

My Take

DecisionWhat I choseWhat it costs
LoopHand-written, no frameworkMore to get right yourself
RefusalsStop, with no fallback modelOne bad message ends the whole run
ConversationOne for all messagesText in one message could influence labels on others
Tool inputValidate and return errorsA wrong but allowed label still passes
LoggingFull bodies, never headersOnly acceptable because the data is fake

I’d write the loop by hand when I’m learning how agents work or need to control each step, such as checking the stop reason before any tool runs. For a routine agent without those needs, I’d try the SDK’s Tool Runner first.

This agent reads message bodies it didn’t write. It can also change state by recording labels. It has no private data and none of its tools can send anything out. The main risk is that a hostile message gets itself or another message the wrong label. It could also slant the written summary. That’s harmless here because the data is fake and the labels only live in memory. It would matter if a label decided whether a real message got resent or deleted. I haven’t attacked it with an injected message yet.

Summary

An agent is just a loop. My app made three round trips to Claude and ran the requested tools between calls until Claude ended its turn. Claude decided which tools to ask for and what label to give each message. My code decided whether to run each request, what input to accept, and when to give up.

The next step is to let the SDK’s Tool Runner drive the loop and then attack the agent with an injected message.

References