Tool Use
How to design the tools an agent calls: tool size, input design, error messages, result size and safe retries for tools that change data.
On this page
- What the model sees of a tool
- Error messages the model can act on
- Result size
- Choosing the size of a tool
- Designing inputs that are hard to get wrong
- Writing the tool description
- How many tools to offer
- Read tools and write tools
- Pitfalls
- Debugging an agent that misuses a tool
- Check yourself
- What to practise next
A tool is a function that an AI agent can call, such as looking up an order or issuing a refund. Whether the agent uses a tool well depends mostly on how the tool is designed: its description, the inputs it accepts, and the text it returns, including its error messages. A model can only work with what a tool tells it, so a poorly designed tool produces wrong calls, repeated calls and wrong answers even when the model itself is capable.
As an example of what goes wrong, suppose a customer asks where order 1O42 is, typing a capital letter O instead of a zero. The agent calls getOrder("1O42") and receives Error: invalid input. The message does not say what was invalid, so the agent retries with the same ID and eventually tells the customer that the order system is down. A one-line change to the error message fixes this.
What the model sees of a tool
As Tools and MCP explains, the application describes each tool to the model, the model writes a request to call it, and the application runs the call and returns the result. From the model's side, a tool consists of three pieces of text. The description gives the tool's name, what it does and when to use it. The input definition says which parameters it takes and in what form. The output is either the result or an error message. If any of these is unclear, the model guesses, so designing a tool means writing these three pieces for a reader that follows them literally.
Error messages the model can act on
The trace below shows the same model and the same typo with two different error messages.
- version A: vague error
who text user Where is order 1O42? model getOrder("1O42") - attempts
- 1
- solved
- no
1The customer wrote "1O42" with a letter O, and the agent copies it into the call as written.
- version A: vague error
who text user Where is order 1O42? model getOrder("1O42") tool Error: invalid input - attempts
- 1
- solved
- no
2The message
invalid inputdoes not say whether the ID is wrong, the system is broken, or the call is badly formatted. - version A: vague error
who text user Where is order 1O42? model getOrder("1O42") tool Error: invalid input model getOrder("1O42") tool Error: invalid input model getOrder("1O42") tool Error: invalid input model Sorry, the order system seems to be down. - attempts
- 3
- solved
- no
3With nothing to go on, it retries the same call and finally gives up with a wrong explanation. It used three calls and gave no answer.
- version B: helpful error
who text user Where is order 1O42? model getOrder("1O42") tool "1O42" is not an order ID. IDs are 4 digits. Did you mean "1042"? - attempts
- 1
- solved
- no
4In version B, the tool explains what an ID looks like and suggests a likely fix.
- version B: helpful error
who text user Where is order 1O42? model getOrder("1O42") tool "1O42" is not an order ID. IDs are 4 digits. Did you mean "1042"? model getOrder("1042") tool order 1042: shipped, 3 items - attempts
- 2
- solved
- yes
5Now the model can act. It retries with
1042and gets the order. - version B: helpful error
who text user Where is order 1O42? model getOrder("1O42") tool "1O42" is not an order ID. IDs are 4 digits. Did you mean "1042"? model getOrder("1042") tool order 1042: shipped, 3 items model Order 1042 has shipped (3 items). - attempts
- 2
- solved
- yes
6It answers with the corrected ID, so the customer can spot a wrong guess. The result is two calls and a correct answer instead of a false report of an outage.
A good error message says what was wrong, what a valid input looks like and what to try next.
The error handling in code
The following tool implements version B. It checks the input before looking anything up, and every failure returns a sentence the model can act on. The data is made up.
const orders = { "1042": { status: "shipped", items: 3 } };
function getOrder(orderId) {
if (!/^\d{4}$/.test(orderId)) {
const guess = orderId.replace(/[oO]/g, "0");
const hint = /^\d{4}$/.test(guess) ? ` Did you mean "${guess}"?` : "";
return { error: `"${orderId}" is not an order ID. IDs are 4 digits.${hint}` };
}
const order = orders[orderId];
if (!order) {
return { error: `No order "${orderId}". Use findOrders(email) to list a customer's orders.` };
}
return { orderId, ...order };
}
console.log(getOrder("1O42")); // error, suggests "1042"
console.log(getOrder("1042")); // { orderId: '1042', status: 'shipped', items: 3 }import re
orders = {"1042": {"status": "shipped", "items": 3}}
def get_order(order_id):
if not re.fullmatch(r"\d{4}", order_id):
guess = re.sub(r"[oO]", "0", order_id)
hint = f' Did you mean "{guess}"?' if re.fullmatch(r"\d{4}", guess) else ""
return {"error": f'"{order_id}" is not an order ID. IDs are 4 digits.{hint}'}
order = orders.get(order_id)
if order is None:
return {"error": f'No order "{order_id}". Use find_orders(email) to list a customer\'s orders.'}
return {"order_id": order_id, **order}
print(get_order("1O42")) # error, suggests "1042"
print(get_order("1042")) # {'order_id': '1042', 'status': 'shipped', 'items': 3}The "not found" error names the tool that can look up the right ID, so the error also tells the agent how your tools fit together.
Result size
Every tool result stays in the context for the rest of the run. A search that returns 300 orders in full uses a large share of the context in one step and buries the few lines that matter. A tool should return the few items and fields that are useful and should say what it left out, so the model knows it can ask for more.
function limitResults(items, max = 5) {
if (items.length <= max) return { results: items };
return {
results: items.slice(0, max),
note: `Showing ${max} of ${items.length}. Add a status or date range to narrow it.`,
};
}
console.log(limitResults([1, 2, 3, 4, 5, 6, 7, 8]).note);
// Showing 5 of 8. Add a status or date range to narrow it.def limit_results(items, max_items=5):
if len(items) <= max_items:
return {"results": items}
return {
"results": items[:max_items],
"note": f"Showing {max_items} of {len(items)}. Add a status or date range to narrow it.",
}
print(limit_results([1, 2, 3, 4, 5, 6, 7, 8])["note"])
# Showing 5 of 8. Add a status or date range to narrow it.Without the note, the model might assume that the five orders it received are all there are.
Choosing the size of a tool
A tool should match one step that a person would take when doing the task. Both extremes cause problems.
Tools that are too small
A tool such as getCustomerField(id, field) returns a single field per call. Reading a customer's name, email and plan takes three calls, which means three chances for the model to make a mistake and three round trips of waiting.
Tools that are too big
A tool such as runSql(query) can do anything. The model has to write correct SQL for a schema it cannot see, and a wrong or malicious query can change or delete data. This kind of tool is hard to restrict, hard to test and hard to explain in a description.
Tools that are about right
A tool such as findOrders(email, status) matches one step, returns what that step needs and can do nothing else. Its name tells the model when to use it, and its limited power makes mistakes cheap.
Designing inputs that are hard to get wrong
Three habits remove most input errors. First, use fixed values instead of free text where the choices are known, for example a status that must be "packing", "shipped" or "returned". Second, put units in parameter names, such as timeoutSeconds instead of timeout, so the model does not have to guess. Third, ask for IDs that came from an earlier tool result instead of names the model has to type and might misspell.
Writing the tool description
The description is the only thing the model has when it decides whether to call a tool, so it needs to say more than the name does. A useful description states what the tool does, when to use it, and when not to use it, especially if another tool looks similar. For example, "Looks up one order by its 4-digit ID. Use findOrders instead when you only have the customer's email" lets the model choose correctly. A description such as "Does ticket stuff" forces the model to guess, and it will guess differently on different runs.
How many tools to offer
Each tool adds its description to the context and gives the model one more option to choose from. With a few clearly different tools, selection is reliable. With dozens of tools, or several tools whose descriptions overlap, the model starts picking the wrong one or alternating between two. If two tools are hard to tell apart in a sentence, merge them or rewrite their descriptions so that each says when the other should be used instead. Offering only the tools the current task needs is also a safety measure, because a tool that is not offered cannot be misused.
Read tools and write tools
A read tool such as getOrder is safe to call twice. A write tool such as refundOrder is not: if a refund call times out, the model cannot tell whether it succeeded, so it retries, and the customer may be refunded twice.
The fix is to make write tools idempotent, which means that doing the action twice has the same effect as doing it once. A tool can check whether the action already happened and return a message such as "order 1042 was already refunded on 3 March", or it can accept a request ID and ignore any call whose ID it has seen before. Guardrails covers which write tools an agent should get and which should need a person's approval.
Pitfalls
Debugging an agent that misuses a tool
When an agent misbehaves, read the tool calls and results before changing the prompt. Repeated identical calls usually point to an error message with nothing to act on, wrong arguments usually point to an input that allows free text where it should allow a fixed set of values, and a model that ignores a tool usually points to a vague description. Test each tool by reading its description and errors as if you had no other context, and fix whatever you would have to guess. The exercise below applies this to a badly designed tool.
An agent misuses this ticket tool: it invents actions, puts the whole conversation into data, and loops on ERR_22. Redesign it by deciding which tools to offer, what inputs they take, and what one error message should say.
Show a sample answer
Split it into tools that each match one step:
createTicket(title, priority)
priority: one of "low", "normal", "urgent"
title: one line, under 80 characters
Returns: { ticketId: "T-5521" }
closeTicket(ticketId, reason)
reason: one of "fixed", "duplicate", "won't fix"
Safe to repeat: closing a closed ticket returns
"T-5521 is already closed (fixed)."
Example error:
"T-552 is not a ticket ID. IDs look like T-5521.
Use findTickets(text) to search by title."This design works for four reasons:
- Each tool does one thing, so its name says when to use it, and there is no free-text
actionfor the model to invent. - Fixed values for
priorityandreasonrule out whole classes of bad input. - The error says what went wrong, what a valid ID looks like and which tool can help.
- Closing a ticket twice is harmless, so a retry after a timeout does no damage.
Check yourself
An agent calls a failing tool four times with the same input. What is the most likely fix?
Which tool is the best size for an agent that answers questions about customers' orders?
A refundOrder tool times out, and the agent calls it again. What design prevents a double refund?
What to practise next
Take a tool or API you use and write the error message you would want to receive if you were the model. Then continue with The Agent Loop, which covers the loop that calls these tools and decides when to stop.