Build an AI Agent with Claude and Tools: Full Guide
Building an AI agent with Claude means giving the model a set of tools (functions) it can call, then handling the loop where Claude decides what to call, you execute the call, and you feed the result back until the task is done. This is different from a simple chatbot: an agent takes actions, checks results, and adapts its next step based on what happened.
This guide covers the actual mechanics — the request/response shape, the agent loop, common tool patterns (search, code execution, API calls, database reads), and the mistakes that make agents flaky in production. If you already know what "tool use" means and just want example JSON, skip to the code section below.
What "Agent" Actually Means Here
An AI agent built on Claude is not a separate product — it's a design pattern on top of the standard Claude API (or a wrapper like SubToAPI). The pattern has four parts:
- System prompt — defines the agent's role, constraints, and available tools.
- Tool definitions — JSON schemas describing each function Claude can call (name, description, parameters).
- The loop — Claude responds either with text or a
tool_userequest; your code executes the tool and sends the result back as atool_result; repeat until Claude returns a final text answer. - State — conversation history, intermediate results, and any memory you persist between turns.
The "intelligence" of the agent lives mostly in tool design and prompt instructions, not in exotic code. Claude is good at reasoning about when to call a tool and how to interpret the result — your job is giving it good tools and clear boundaries.
Defining Tools
Each tool needs a name, a description Claude can reason about, and a JSON schema for inputs. Vague descriptions are the #1 cause of agents calling the wrong tool or passing bad arguments.
{
"name": "search_orders",
"description": "Search the orders database by customer email or order ID. Returns up to 20 matching orders with status and total.",
"input_schema": {
"type": "object",
"properties": {
"email": { "type": "string" },
"order_id": { "type": "string" }
}
}
}
Good descriptions read like documentation for a new engineer, not marketing copy. Include constraints ("returns up to 20 results", "dates must be ISO 8601") directly in the schema so Claude doesn't guess.
The Agent Loop in Code
Here's a minimal loop using SubToAPI's Messages endpoint, which mirrors the standard Claude tool-use format — so the same logic works whether you're calling Claude directly or through a proxy:
const tools = [
{
name: "get_weather",
description: "Get current weather for a city",
input_schema: {
type: "object",
properties: { city: { type: "string" } },
required: ["city"]
}
}
];
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-5-sonnet-20241022",
max_tokens: 1024,
tools,
messages
})
});
const data = await res.json();
if (data.stop_reason === "tool_use") {
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)
}]
});
continue; // loop again
}
return data.content; // final answer
}
}
async function executeTool(name, input) {
if (name === "get_weather") {
return { temp_c: 18, condition: "cloudy" };
}
throw new Error(`Unknown tool: ${name}`);
}
This is the entire shape of a working agent. Everything else — more tools, retries, memory, multi-step planning — builds on this loop. See /docs/tools for the full schema reference and /docs/messages for request/response details.
Common Tool Patterns
Read-only data tools (search, lookup, database queries) are the safest starting point — low risk if Claude calls them unnecessarily.
Write/action tools (send email, create ticket, charge a card) need an extra confirmation step or a dry-run mode. Never let an agent execute irreversible actions without a check — either a human-in-the-loop step or strict input validation before execution.
Code execution tools let Claude write and run small scripts (e.g., math, data transforms). Sandbox these separately from your main infrastructure.
Chained tools — one tool's output feeds another (search → fetch details → summarize). Claude handles the chaining itself as long as each tool's description is accurate; you don't need to hardcode the order.
Reliability Tips for Production Agents
- Cap the loop. Add a max iteration count (e.g., 8) so a confused agent doesn't call tools forever.
- Validate tool inputs before executing — Claude can hallucinate a plausible-looking but invalid argument.
- Return structured errors, not exceptions, as tool results. Claude can recover from
{"error": "order not found"}better than from a crashed loop. - Log every tool call and result. When an agent misbehaves, the transcript is your only debugging tool.
- Stream when the agent is slow. If a tool takes seconds to run, stream intermediate text so the user isn't staring at a blank screen — see /docs/streaming.
Where SubToAPI Fits
If you're building an agent for a product (not just a personal script), you'll eventually need more than raw API access: per-application keys instead of one shared secret, usage metadata broken down by key, and team seats so multiple engineers can work without sharing credentials. SubToAPI wraps standard Claude access into that layer — same Messages and tool-use format shown above, plus a dashboard for keys and usage. Start with a free trial at /signup or check /pricing for plan details.
Questions
Do I need a special API or SDK to build an agent with Claude? No. Tool use is a standard feature of the Claude Messages API. You define tool schemas in your request and handle the tool_use/tool_result loop in your own code — no separate "agent SDK" is required.
How many tools can an agent have? There's no hard limit, but accuracy drops as tool count grows and descriptions overlap. Keep each agent focused on 5–15 well-described tools; split larger systems into multiple specialized agents if needed.
Can Claude call multiple tools in one turn? Yes, Claude can return multiple tool_use blocks in a single response if it determines several calls are needed before it can continue. Your loop should execute all of them and return all corresponding tool_result blocks together.