Claude API Agent with Tool Use: A Working Example
What a "Claude API agent with tool use" actually means
If you're searching for this, you probably want one thing: a working pattern for having Claude decide when to call a function (a "tool"), execute that function in your own code, and feed the result back so Claude can finish the answer. That's the whole loop. There's no separate "agent API" — an agent is just the Claude Messages API plus a tools array plus a loop in your application code that handles tool_use responses.
Below is a complete, minimal example you can copy, followed by the parts people usually get wrong: multi-turn tool loops, parallel tool calls, and error handling when the tool itself fails.
The core building block: defining a tool
A tool is a JSON schema describing a function Claude can ask you to run. Claude never executes code — it only returns structured arguments, and your backend decides what to do with them.
{
"name": "get_weather",
"description": "Get the current weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": { "type": "string", "description": "City name" },
"unit": { "type": "string", "enum": ["celsius", "fahrenheit"] }
},
"required": ["city"]
}
}
The description field matters more than most people expect — Claude uses it, not the function name, to decide whether and how to call the tool. Vague descriptions lead to Claude guessing wrong inputs or skipping the tool entirely.
Step 1: send the message with tools attached
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"tools": [{
"name": "get_weather",
"description": "Get the current weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}],
"messages": [
{"role": "user", "content": "What is the weather in Lisbon right now?"}
]
}'
Claude's response will contain a stop_reason of tool_use and a content block like:
{
"type": "tool_use",
"id": "toolu_01A1B2C3",
"name": "get_weather",
"input": { "city": "Lisbon", "unit": "celsius" }
}
Step 2: run the tool and send the result back
Your code calls the real weather API (or database, or internal service), then sends a new message with a tool_result block referencing the same id:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A1B2C3",
"content": "18°C, partly cloudy, wind 12km/h"
}
]
}
You send the full conversation history again — including the assistant's tool_use message and your new tool_result message — and Claude produces the final natural-language answer. This is the entire agent loop: request, tool call, execute, respond, repeat until stop_reason is end_turn.
A minimal JavaScript agent loop
async function runAgent(messages, tools, callTool) {
while (true) {
const res = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"x-api-key": process.env.ANTHROPIC_API_KEY,
"anthropic-version": "2023-06-01",
"content-type": "application/json"
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
tools,
messages
})
});
const data = await res.json();
messages.push({ role: "assistant", content: data.content });
if (data.stop_reason !== "tool_use") return data;
const toolResults = [];
for (const block of data.content) {
if (block.type === "tool_use") {
const result = await callTool(block.name, block.input);
toolResults.push({
type: "tool_result",
tool_use_id: block.id,
content: String(result)
});
}
}
messages.push({ role: "user", content: toolResults });
}
}
This handles parallel tool calls too — Claude can request multiple tools in one turn, and your loop just resolves all of them before sending the batch back.
Common failure points to design for
- Tool errors: if your function throws, don't crash the loop — send back a
tool_resultwithis_error: trueand a short message. Claude will usually retry with different arguments or explain the failure to the user. - Missing required fields: validate
inputagainst your schema before executing. Claude is good but not perfect at matching schemas exactly. - Infinite loops: cap the number of tool-use iterations (5–10 is usually enough) so a confused agent doesn't burn through your token budget.
- Stale context: every loop iteration resends the full message history, so costs grow with conversation length — trim or summarize older turns if you're building long-running agents.
Running this through a hosted API endpoint
Everything above works identically if you're calling Claude through SubToAPI instead of directly — the /v1/messages request shape, tools array, and tool_use/tool_result loop are the same. The difference is you authenticate with an application key (sub_live_...) instead of a raw Anthropic key, which matters if you're shipping this agent inside a product and want per-app keys, usage metadata per request, and team seats rather than sharing one account credential across your codebase.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"tools": [{"name": "get_weather", "description": "...", "input_schema": {...}}],
"messages": [{"role": "user", "content": "Weather in Lisbon?"}]
}'
The full tool-use reference, including schema validation details and streaming behavior while a tool call is pending, is in /docs/tools. If you're wiring this into a production agent and want streaming responses alongside tool calls, /docs/streaming covers the SSE event format. General request/response shape is in /docs/messages, and /docs/quickstart walks through getting a key from scratch.
Questions
Do I need a special "agent" endpoint in the Claude API? No. There's a single Messages API. An agent is the pattern of attaching a tools array and looping on tool_use responses in your own application code — Anthropic doesn't offer a separate agent-specific endpoint.
Can Claude call multiple tools in one turn? Yes. A single response can contain several tool_use blocks. Your code should execute all of them and return all their results together in one tool_result message before the next API call.
What happens if the tool call has invalid or missing arguments? Claude usually matches your schema well, but you should still validate input server-side. If something's wrong, return a tool_result with is_error: true so Claude can self-correct instead of silently failing downstream.