Claude API Agent Tool Chaining Tutorial
Tool chaining is what turns a Claude API call into an actual agent: instead of one request producing one answer, the model calls a tool, gets a result, decides whether it needs another tool, and keeps going until the task is done. This tutorial walks through the exact request/response loop you need to implement, with working code, so you can build agents that chain two, three, or more tool calls reliably.
If you've only used Claude for single-turn completions, the jump to tool chaining is mostly about understanding one thing: your application code is the orchestrator, not the model. Claude decides what to call and when to stop, but your backend has to execute the tool, format the result, and send it back. Get that loop right and arbitrarily complex chains fall out naturally.
The core loop
Every tool-chaining agent follows the same pattern:
- Send a message with a list of available
tools. - Claude responds with either a final text answer or a
tool_useblock asking you to run a specific tool. - You execute that tool in your own code and send the result back as a
tool_resultmessage. - Claude reads the result and either calls another tool or returns a final answer.
- Repeat steps 2–4 until there's no more
tool_usein the response.
This loop is identical whether you're calling one tool once or chaining five tools across ten turns. The only thing that changes is how many iterations you run before you get a final answer.
Defining tools
Tools are described with a name, a description, and a JSON schema for their input. Here's a minimal setup with two tools: a search tool and a calculator.
{
"tools": [
{
"name": "web_search",
"description": "Search the web for current information",
"input_schema": {
"type": "object",
"properties": {
"query": { "type": "string" }
},
"required": ["query"]
}
},
{
"name": "calculator",
"description": "Evaluate a basic arithmetic expression",
"input_schema": {
"type": "object",
"properties": {
"expression": { "type": "string" }
},
"required": ["expression"]
}
}
]
}
The description fields matter more than most developers expect. Claude uses them to decide which tool to call and in what order — vague descriptions lead to wrong tool selection or unnecessary chaining.
Running the chain
Here's a Node.js example that implements the full loop against the Messages API, handling multiple sequential tool calls:
async function runAgent(userMessage, tools, executeTool) {
let messages = [{ role: "user", content: userMessage }];
while (true) {
const response = await callClaude(messages, tools);
const toolUses = response.content.filter(b => b.type === "tool_use");
if (toolUses.length === 0) {
return response.content.find(b => b.type === "text")?.text;
}
messages.push({ role: "assistant", content: response.content });
const toolResults = [];
for (const use of toolUses) {
const result = await executeTool(use.name, use.input);
toolResults.push({
type: "tool_result",
tool_use_id: use.id,
content: JSON.stringify(result)
});
}
messages.push({ role: "user", content: toolResults });
}
}
executeTool is your own dispatcher — a switch on name that calls your actual search API, calculator, database query, or whatever backs that tool. The important detail is that messages accumulates the full history: the assistant's tool_use blocks and your tool_result blocks both need to stay in the conversation for Claude to reason correctly about what's already been done.
A concrete chained example
Suppose a user asks: "What's the population of Lisbon divided by the population of Porto?" A well-built agent will:
- Call
web_searchwith"Lisbon population". - Call
web_searchagain with"Porto population". - Call
calculatorwith the actual numbers once both are known. - Return a final text answer.
That's three sequential tool calls across three loop iterations, each depending on the result of the one before. Your loop code above handles this without any special-casing — it just keeps running until Claude stops requesting tools.
Common pitfalls
- Forgetting to echo tool_use_id: every
tool_resultmust reference the exactidfrom the matchingtool_useblock, or Claude can't match results to calls. - Dropping conversation history: if you don't push the assistant's tool_use message before the tool_result, the model loses context on why it called that tool.
- No loop limit: always cap iterations (10–15 is reasonable) to avoid infinite chains if a tool keeps returning ambiguous results.
- Parallel vs sequential calls: Claude can request multiple tools in a single response when they're independent (like the two population searches above). Execute those concurrently with
Promise.allinstead of looping one at a time — it's faster and doesn't change correctness. - Streaming complicates chaining: if you're using streaming responses, you need to buffer tool_use blocks until they're complete before executing them. See /docs/streaming for the event structure.
Where SubToAPI fits
If you're already building agents against the Claude API, SubToAPI gives you an HTTPS layer on top of your existing Claude access with application-specific keys (sub_live_...), so each agent or product you ship gets its own key, its own usage metadata, and its own rate limits — without sharing one raw credential across every service.
Tool use works exactly like the examples above; the full schema and request/response shapes are in /docs/tools. If you're chaining tool calls across long-running agents, /docs/streaming covers how to handle partial tool_use blocks as they arrive, and /docs/messages documents the base request format. Team and Scale plans add seat-based access so multiple developers can ship agents under one account — details on /pricing. You can test the full tool-chaining loop with a free trial at /signup.
Debugging a broken chain
When a chain doesn't terminate or returns a wrong answer, check these in order:
- Log every
tool_useandtool_resultpair — most bugs are mismatched IDs or malformed JSON in the result. - Verify your tool descriptions aren't ambiguous enough to cause Claude to call the wrong tool or call the same tool twice unnecessarily.
- Confirm your loop isn't silently swallowing the final text response because it's checking for
tool_useblocks in the wrong content array. - If using parallel tool calls, make sure you're returning all tool_results for a given turn before sending the next request — partial results will stall the chain.
Questions
How many tools can I chain in a single Claude API agent? There's no hard limit on chain length — it's governed by your own loop's iteration cap and context window size. Most practical agents resolve in 2–6 tool calls; beyond ~15 iterations you likely have a design problem rather than a genuinely long task.
Does Claude decide the order of tool calls automatically? Yes. Given clear tool descriptions, Claude determines which tool to call first and whether subsequent calls depend on prior results. Your code just executes whatever it requests and feeds results back — you don't hardcode the sequence.
Can I chain tools across a streamed response? Yes, but you must accumulate streamed tool_use deltas into a complete JSON object before executing the tool, since partial arguments aren't valid input. See /docs/streaming for the exact event types to watch for.