Building a Reliable AI Agent with Claude Tool Use
An AI agent demo takes an afternoon. An agent you can put in front of customers or let near your data takes much more care. The difference is not the model. It is the tools you give it, the limits you set, and how you check its work.
This post walks through how I build agents with Claude: what an agent actually is, how to design its tools, a working agent in TypeScript, and the guardrails that make it safe to ship.
What an agent is (and when you need one)
An agent is a language model that can use tools in a loop. You describe some tools, such as search orders or send email. Claude reads the request, decides which tool to call and with what input, your code runs the tool and sends back the result, and Claude decides what to do next. This repeats until the task is done.
That flexibility is the point, and also the risk. If the steps of a task are always the same, a fixed automation workflow is simpler, cheaper and easier to test. Use an agent when the path really depends on what the agent finds along the way: support questions that could need any of a dozen lookups, research across several systems, or an internal assistant that answers questions from many sources.
How tool use works
Each tool has a name, a description and a schema for its input. When Claude wants to use one, the response stops with stop_reason: "tool_use" and contains the tool name and input. Your code runs the tool and sends back a tool_result. Claude can call several tools at once and continue for as many rounds as it needs.
The official SDKs include a tool runner that handles this loop for you, so your code is mostly the tools themselves.
Designing good tools
Most agent problems I debug are tool problems. The rules I follow:
- Fewer, clearer tools. Five well-named tools beat twenty overlapping ones. If two tools do nearly the same thing, the model will sometimes pick the wrong one.
- Write descriptions for a new colleague. Say what the tool does, when to use it, when not to, and what it returns.
- Strict, small inputs. Use enums for fixed choices and IDs instead of free text. Validate everything: the model's input is untrusted input.
- Return what the model needs, not everything. A short, relevant result is better than a 5,000-line JSON dump that fills the context window.
- Return useful errors. "Order 1234 not found. Order IDs look like ORD-123456." lets the agent fix its own mistake.
- Separate reading from acting. Lookups can run freely. Anything that changes data, spends money or contacts a customer should be its own tool with its own controls.
A working agent in TypeScript
Here is a small support agent for an online store with three tools: two that read and one that issues refunds, which needs a person's approval. It uses the Anthropic TypeScript SDK's tool runner with Zod schemas.
import Anthropic from "@anthropic-ai/sdk";
import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";
import { db, requestApproval, audit } from "./store"; // your own code
const client = new Anthropic(); // reads ANTHROPIC_API_KEY from the environment
const searchOrders = betaZodTool({
name: "search_orders",
description:
"Find a customer's orders by email address. Returns up to 5 recent orders with id, date, status and total. " +
"Use this first when the customer asks about an order but has not given an order id.",
inputSchema: z.object({ email: z.string().email() }),
run: async ({ email }) => {
const orders = await db.recentOrders(email, 5);
return orders.length ? JSON.stringify(orders) : `No orders found for ${email}.`;
},
});
const getOrder = betaZodTool({
name: "get_order",
description: "Get the full details of one order: items, payment, delivery status and tracking link.",
inputSchema: z.object({ orderId: z.string().regex(/^ORD-\d{6}$/, "Order ids look like ORD-123456") }),
run: async ({ orderId }) => {
const order = await db.order(orderId);
return order ? JSON.stringify(order) : `Order ${orderId} not found.`;
},
});
const issueRefund = betaZodTool({
name: "issue_refund",
description:
"Request a refund for an order. A staff member must approve it before any money moves. " +
"Only use this when the customer asks for a refund and the order is eligible under the refund policy.",
inputSchema: z.object({
orderId: z.string().regex(/^ORD-\d{6}$/),
reason: z.enum(["damaged", "not_delivered", "wrong_item", "changed_mind"]),
}),
run: async ({ orderId, reason }) => {
const approved = await requestApproval({ action: "refund", orderId, reason }); // a person decides
await audit("refund_requested", { orderId, reason, approved });
return approved
? `Refund for ${orderId} approved and started.`
: `A staff member did not approve this refund. Tell the customer a colleague will contact them.`;
},
});
export async function answer(question: string) {
const final = await client.beta.messages.toolRunner({
model: "claude-opus-5-5",
max_tokens: 16000,
max_iterations: 10, // a hard stop, so the agent can never loop forever
system:
"You are the support assistant for an online store. Be brief and friendly. " +
"Use the tools to look things up; never guess order details. " +
"Follow the refund policy: damaged, wrong or undelivered items within 30 days.",
tools: [searchOrders, getOrder, issueRefund],
messages: [{ role: "user", content: question }],
});
if (final.stop_reason === "refusal") return "Sorry, I can't help with that here. A colleague will follow up.";
return final.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n");
}The refund tool is the important part. The model can ask for a refund, but the money only moves after a person approves it, and both the request and the decision are recorded. The model never holds the power to act alone on anything that matters.
Guardrails that make an agent safe
Permissions
Give the agent its own credentials with the minimum access it needs. If it only reads orders, its database user should only be able to read orders. Do not rely on the prompt to stop it doing something its credentials allow.
Approval for risky actions
Classify every tool:
- Read: runs freely.
- Reversible write (adding a note, tagging a ticket): runs, and is logged.
- Irreversible or external (payments, emails to customers, deleting data): needs approval, or produces a draft that a person sends.
Limits
Set a maximum number of loop iterations, a max_tokens per response, a timeout for each tool, and a rate limit per user. An agent that gets stuck should fail quickly and hand over to a person.
Untrusted content
Anything the agent reads (emails, web pages, documents, even order notes) can contain text that looks like instructions. Treat tool results as data, keep powerful tools behind approval, and do not give an agent that reads public content the ability to send data out.
Logging
Log every request, every tool call with its input and result, and the final answer. When a customer says "the bot told me X", you need to see exactly why.
Test it with evals
Before launch, write down 30 to 100 realistic requests and what a good outcome is for each: which tools should be called, what must never happen, what the answer should contain. Include tricky ones: a refund request outside the policy, a question about someone else's order, a message trying to talk the agent into breaking the rules.
Run the agent on the whole set after every change to prompts, tools or models. Score the simple things automatically (did it call issue_refund for an ineligible order?) and review a sample of the rest by hand. This is the only way to know whether a change made the agent better.
Watch it in production
After launch, keep track of:
- the share of conversations the agent finished without handing over,
- how often people overrule its approval requests,
- tool errors and timeouts,
- cost and response time per conversation.
Read a handful of real conversations every week. They will show you the next tool to add, the next instruction to clarify, or the next thing to take away from the agent.
Summary
A reliable agent is a small set of clear tools, strict inputs, limits on every loop, approval for anything risky, full logs and a test set you run on every change. The model provides the reasoning. Your engineering provides the trust.
I build AI agents and LLM integrations for products and internal tools, from support assistants to agents that search your own documents. If you are planning one, let's talk about it.