Build an AI Agent with Tool Use in Claude: A Guide
Building an AI agent with tool use in Claude means giving the model a set of callable functions — database lookups, API calls, calculators, search — and letting it decide when and how to use them to complete a task. Unlike a simple chatbot that just generates text, an agent reasons about which tool to call, executes it, reads the result, and decides whether it needs another tool call or can answer directly.
This guide walks through the actual mechanics: defining tools, handling the request/response loop, managing multi-step execution, and avoiding the common mistakes that make agents flaky in production.
What "Tool Use" Actually Means
Claude's tool use (sometimes called function calling) works like this:
- You send a request with a list of tool definitions (name, description, JSON schema for inputs).
- Claude decides whether answering the user requires a tool. If so, it returns a
tool_useblock instead of plain text. - Your code executes the actual function — Claude never runs code itself, it only tells you what to call and with what arguments.
- You send the tool's result back to Claude in a
tool_resultblock. - Claude either calls another tool or produces a final answer.
This loop is the entire foundation of an agent. There's no magic beyond it — the "agent" behavior emerges from repeating steps 2–4 until the model is satisfied it has enough information.
Defining a Tool
A tool definition needs a clear name, a description written for the model (not for humans reading your code), and a strict input schema. Vague descriptions are the number one cause of wrong tool selection.
{
"name": "get_order_status",
"description": "Look up the current status of a customer order by order ID. Returns status, estimated delivery date, and tracking number.",
"input_schema": {
"type": "object",
"properties": {
"order_id": { "type": "string", "description": "The order ID, e.g. ORD-48213" }
},
"required": ["order_id"]
}
}
Keep descriptions specific about what the tool does and doesn't do. If you have multiple similar tools (search_orders vs get_order_status), spell out the distinction explicitly in each description — Claude will pick wrong otherwise.
The Execution Loop
Here's a minimal agent loop in JavaScript. This example uses the SubToAPI endpoint, but the pattern is identical against any Claude-compatible Messages API.
const tools = [{
name: "get_order_status",
description: "Look up order status by order ID.",
input_schema: {
type: "object",
properties: { order_id: { type: "string" } },
required: ["order_id"]
}
}];
async function runAgent(userMessage) {
let messages = [{ role: "user", content: userMessage }];
while (true) {
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "claude-3-7-sonnet",
max_tokens: 1024,
messages,
tools
})
});
const data = await res.json();
if (data.stop_reason !== "tool_use") {
return data.content; // final answer
}
const toolCall = data.content.find(c => c.type === "tool_use");
const result = await executeTool(toolCall.name, toolCall.input);
messages.push({ role: "assistant", content: data.content });
messages.push({
role: "user",
content: [{
type: "tool_result",
tool_use_id: toolCall.id,
content: JSON.stringify(result)
}]
});
}
}
async function executeTool(name, input) {
if (name === "get_order_status") {
return { status: "shipped", eta: "2025-06-14", tracking: "1Z999AA1" };
}
throw new Error(`Unknown tool: ${name}`);
}
This loop keeps running until stop_reason is no longer tool_use. For details on request formats and stop reasons, check /docs/messages and /docs/tools.
Common Mistakes When Building Agents
No turn limit. A buggy tool or malformed schema can cause infinite tool-call loops. Always cap iterations (e.g. 8–10 turns) and return a fallback message if exceeded.
Letting the model guess at missing data. If a tool requires an order ID and the user hasn't given one, the right behavior is for Claude to ask for it — not to invent a placeholder. Write descriptions and system prompts that make this explicit: "If required information is missing, ask the user before calling the tool."
Returning raw errors as tool results. If a tool call fails (API timeout, 404, bad input), don't crash the loop — return a structured error as the tool result so Claude can decide to retry, use a different tool, or tell the user it failed.
Over-scoping tools. One tool that does five unrelated things confuses the model's selection logic. Split responsibilities: search_products, get_product_details, check_inventory — each with one clear job.
No streaming for long agent runs. If your agent might take several tool-call rounds, stream the final response so the UI doesn't sit blank. See /docs/streaming.
Running Agents in Production
Once the loop works, production concerns show up fast: tracking token usage per agent run (tool calls add up quickly), rotating API keys across environments, rate limiting concurrent agent sessions, and giving team members visibility into what agents are actually doing.
This is where routing agent traffic through SubToAPI helps. You get a single sub_live_... key per application, per-key usage metadata so you can see exactly how many tokens and tool calls each agent run consumed, and team seats so multiple developers can share billing without sharing raw provider credentials. Plans start at Solo €9/month, with Team (€19/seat) and Scale (€49/seat) tiers for larger agent deployments — see /pricing. You can try the full API with a free trial at /signup, and the fastest way to see the tool-use loop working end to end is /docs/quickstart.
questions
Do I need a special framework to build an agent with Claude? No. The core agent loop — send request, check for tool_use, execute, send result back — is about 20 lines of code in any language that can make HTTP requests. Frameworks like LangChain can help with larger multi-agent systems, but a single-tool or few-tool agent is usually simpler to write by hand.
How many tools can I give Claude at once? There's no hard limit, but accuracy drops as the tool list grows and tool descriptions become similar. In practice, keep active tool sets under 15–20 for reliable selection, and group related tools logically rather than exposing every possible function at once.
How do I stop an agent from looping forever? Set a maximum number of tool-call rounds (commonly 5–10) in your execution loop, and have a fallback response ready if the limit is hit. Also validate tool inputs strictly so malformed arguments fail fast instead of triggering repeated retries.