Claude API Tool Calling for Multi-Step Agents
What "multi-step agent" actually means with Claude's tool use
If you're searching for this, you've probably already built a single tool call and now need something that chains several together — look up a customer, check inventory, then draft an email, all without a human re-prompting the model at each step. That's a multi-step agent: a loop where Claude decides which tool to call, your code executes it, the result goes back into the conversation, and Claude decides the next action until it has a final answer.
The short version: Claude's tool calling API doesn't run tools for you. It returns a tool_use content block describing which function to call and with what arguments. Your application executes the actual function (hitting a database, an internal API, a search index), wraps the result in a tool_result block, and sends the whole conversation back. Claude then either calls another tool or returns text. A "multi-step agent" is just this cycle repeated until the model stops requesting tools.
The core request loop
Every multi-step agent built on Claude's API follows the same shape:
- Send the user message plus your
toolsarray. - Check the response's
stop_reason. If it'stool_use, extract the tool call(s). - Execute the tool(s) in your own code.
- Append a
usermessage containingtool_resultblocks matched to eachtool_use_id. - Send the updated message array back.
- Repeat from step 2 until
stop_reasonisend_turn.
Here's a minimal implementation:
async function runAgent(client, model, tools, toolHandlers, messages) {
while (true) {
const response = await client.messages.create({
model,
max_tokens: 1024,
tools,
messages,
});
messages.push({ role: "assistant", content: response.content });
if (response.stop_reason !== "tool_use") {
return response;
}
const toolResults = [];
for (const block of response.content) {
if (block.type === "tool_use") {
const handler = toolHandlers[block.name];
const result = await handler(block.input);
toolResults.push({
type: "tool_result",
tool_use_id: block.id,
content: JSON.stringify(result),
});
}
}
messages.push({ role: "user", content: toolResults });
}
}
This is the whole pattern. Everything else — retries, step limits, logging, parallel tool calls — is engineering around this core loop.
Handling multiple tool calls in one turn
Claude can request several tools in a single response if the task allows parallelism (e.g., checking stock for three products at once). Each tool_use block has its own id, and you must return a matching tool_result for every single one in the same follow-up message — you can't answer half and leave the rest pending. If your handler for one tool throws, return an error string in that specific tool_result rather than failing the whole batch, so Claude can decide how to recover (retry, pick a different tool, or surface the error to the user).
Capping steps and detecting loops
A multi-step agent without a hard step limit is a liability — a confused model can call the same tool repeatedly. Set a maxSteps counter in your loop and break with a fallback response if it's exceeded:
let steps = 0;
const MAX_STEPS = 8;
while (steps++ < MAX_STEPS) {
// ... loop body
}
It's also worth logging each tool call with its arguments. When an agent misbehaves, the call history is almost always more useful for debugging than the final output.
Keeping state across steps
Multi-step agents accumulate context fast — every tool result gets appended to the message array, and that array is what you resend each turn. For long-running agents (document processing, multi-page lookups), watch your token budget: large tool outputs (raw API responses, full database rows) should be trimmed or summarized before being added as tool_result content, not dumped in raw.
If you're running this in production and need to see exactly how many tokens each step consumed, SubToAPI exposes per-request usage metadata on every call, which is useful for tracking whether a particular tool is driving up cost in long agent loops. See /docs/messages for the response format and /docs/tools for tool-use specific fields.
Streaming inside an agent loop
Streaming and tool calling work together, but there's a nuance: when streaming, tool_use blocks arrive incrementally as input_json_delta events, and you need to buffer and parse the JSON once the block closes rather than mid-stream. If you're building a chat UI on top of an agent, stream the text blocks to the user immediately but wait for complete tool_use blocks before executing anything — partial JSON will throw parse errors. SubToAPI's streaming endpoint follows the same event structure as the standard API, so existing stream-parsing code works without modification; details are in /docs/streaming.
Where SubToAPI fits
None of the above changes if you're calling Anthropic directly or going through SubToAPI — the tool-use protocol is identical, which is the point. What changes is operational overhead: SubToAPI gives each app or environment its own sub_live_... key, so your agent's production key, staging key, and a teammate's local dev key are isolated and individually revocable without touching a shared account. For teams running several agents across projects, that key-per-surface model avoids the common failure mode of one leaked key affecting every integration. Plans start at Solo €9/month, with Team (€19/seat) and Scale (€49/seat) adding multi-seat dashboards; there's a free trial at /signup and setup takes about the time it takes to read /docs/quickstart.
Common mistakes in multi-step agents
- Not validating tool input schemas strictly. Claude follows your JSON schema closely but not perfectly — validate before executing, especially for destructive actions.
- Forgetting
tool_use_idmatching. If the ID in yourtool_resultdoesn't match the originaltool_useblock, the API will reject the request. - Letting tool outputs balloon context. Summarize or truncate large results before feeding them back.
- No step cap. Always bound the loop, even generously.
- Treating tool execution as safe by default. If a tool can modify data, add a confirmation step or scope its permissions — the model will call it if it thinks that's the right move.
questions
Does Claude execute tools itself, or just tell me what to call? Claude only decides which tool to call and with what arguments. Your application code is responsible for actually running the function and returning the result as a tool_result block.
How many steps can a multi-step agent take before it's "too many"? There's no fixed limit from the API, but production agents should enforce their own cap (commonly 5–10 steps) to avoid runaway loops and unnecessary token cost.
Can I run a multi-step tool-calling agent through SubToAPI the same way as directly with Anthropic? Yes — the request and response structure for tool use is unchanged. You swap your endpoint and key for a sub_live_... key; see /docs/quickstart for setup.