Blog / AI agentsDebugging AI agents, part 2

Why your agent picks the wrong tool (or no tool at all)

Most "the model got it wrong" bugs are tool design bugs. Rewrite names, descriptions, schemas and error messages so your agent calls the right tool with the right input, and test it.

Debugging AI agents, part 2: Why your agent picks the wrong tool

In Part 1 we traced a support agent that told a customer their order had shipped when it hadn't. The trace showed the real cause. The model called search_orders with an exact order number, the fuzzy search returned a different order with two digits swapped, and the model reported that order's status.

Nothing was wrong with the model. Something was wrong with the tools we gave it.

This part is about the most common class of agent bug: the model calls the wrong tool, calls the right tool with the wrong input, or doesn't call a tool at all. In almost every case, the fix is in how the tools are named, described and shaped, not in the system prompt.

The tool definition is a prompt

Here are the two tools from the shipping bug, as they were originally written:

const tools: Anthropic.Tool[] = [
  {
    name: "search_orders",
    description: "Search orders.",
    input_schema: {
      type: "object",
      properties: { query: { type: "string" } },
      required: ["query"],
    },
  },
  {
    name: "order_info",
    description: "Get order info.",
    input_schema: {
      type: "object",
      properties: { id: { type: "string" } },
    },
  },
];

Put yourself in the model's position. A customer gives you "48213". You have "Search orders" and "Get order info". Both sound right. Nothing says the search is fuzzy, nothing says what id looks like, and nothing says which one to prefer. The model picked one. Half the time it will pick the other.

The model reads every word of a tool definition, every turn. The name, the description, every property name and every property description go into its context, the same as your system prompt. Writing them well is prompt engineering, and it is the highest-leverage prompt engineering you can do in an agent.

Here is the same pair, rewritten:

const tools: Anthropic.Tool[] = [
  {
    name: "get_order",
    description:
      "Look up one order by its exact order number. Use this whenever the customer " +
      "gives an order number (5 digits, e.g. 48213). Returns status, items, " +
      "shipping carrier and tracking number, or an error if no order has that number.",
    input_schema: {
      type: "object",
      properties: {
        order_number: {
          type: "string",
          description: "Exact 5-digit order number, digits only. Strip any # or spaces.",
          pattern: "^[0-9]{5}$",
        },
      },
      required: ["order_number"],
    },
  },
  {
    name: "find_orders_by_customer",
    description:
      "List a customer's recent orders when they do NOT have an order number. " +
      "Matches on email address. Returns up to 10 orders, newest first. " +
      "Never use this to look up a specific order number: use get_order.",
    input_schema: {
      type: "object",
      properties: {
        email: { type: "string", description: "Customer's email address." },
      },
      required: ["email"],
    },
  },
];

What changed:

  • Names say what the tool does and how. get_order and find_orders_by_customer can't be confused. search_orders and order_info can.
  • Descriptions say when to use it, and when not to. "Use this whenever the customer gives an order number" and "Never use this to look up a specific order number" do more than any system prompt rule.
  • Descriptions say what comes back. If the model knows the tool returns "an error if no order has that number", it is ready for that case instead of being surprised by it.
  • Parameters have descriptions and formats. order_number with "5 digits, digits only, strip any #" heads off a whole family of bad inputs.
  • The fuzzy search is gone. It turned out nobody needed fuzzy matching on order numbers. Customers either have the number or they have their email address. Removing a tool is often the best fix.
Diagram of a tool call round trip between the model and your code, including an is_error result
The model only sees the definition and the result. Both are prompts. Write them for a reader.

Make bad inputs impossible

Descriptions steer the model. Schemas enforce. You want both.

On current Claude models you can set strict: true on a tool. The API then guarantees that the input of every tool_use block matches your schema exactly: required fields present, types right, no surprise extra fields. Strict mode needs additionalProperties: false and an explicit required list:

{
  name: "refund_order",
  description:
    "Refund an order in full or in part. Only use after get_order has confirmed " +
    "the order exists and its status is 'delivered' or 'returned'.",
  strict: true,
  input_schema: {
    type: "object",
    properties: {
      order_number: { type: "string", description: "Exact 5-digit order number." },
      amount_pence: {
        type: "integer",
        description: "Amount to refund in pence. Must not exceed the order total.",
      },
      reason: {
        type: "string",
        enum: ["damaged", "not_received", "wrong_item", "changed_mind"],
      },
    },
    required: ["order_number", "amount_pence", "reason"],
    additionalProperties: false,
  },
}

Notice the money is amount_pence as an integer. Floats and currency strings ("£12.50", "12.5", "12,50") are an endless source of agent bugs. Pick one unambiguous representation and say it in the name.

Notice also the enum for reason. When a field has a fixed set of values, list them. The model will pick from the list instead of inventing "item arrived broken".

Strict mode guarantees the *shape* of the input. It does not guarantee the input is *true*. The model can still pass a well-formed order number that belongs to a different customer. So validate inside the tool as well, exactly as you would for any untrusted request coming into an API:

async function refundOrder(input: RefundInput, ctx: { customerId: string }) {
  const order = await db.orders.findByNumber(input.order_number);
  if (!order || order.customerId !== ctx.customerId) {
    return toolError(`No order ${input.order_number} on this customer's account.`);
  }
  if (input.amount_pence > order.totalPence) {
    return toolError(
      `Refund of ${input.amount_pence}p is more than the order total of ${order.totalPence}p.`,
    );
  }
  // ...issue the refund
}

Errors the model can act on

When a tool fails, what you send back decides what happens next. Compare these two results for the same failure:

{ "type": "tool_result", "tool_use_id": "toolu_01", "content": "Error: 404" }
{
  "type": "tool_result",
  "tool_use_id": "toolu_01",
  "is_error": true,
  "content": "No order with number 48231. Order numbers are 5 digits. Ask the customer to check the number on their confirmation email, or use find_orders_by_customer with their email address."
}

With the first, the model has to guess. It might retry the same call, apologise vaguely, or (the worst case) carry on as if it had the data. With the second, it knows exactly what went wrong and what to do next. In traces, you will see the model follow that advice almost every time.

Write tool errors the way you would write an error message for a junior colleague: what happened, why, and what to try instead. A small helper keeps it consistent:

type ToolOutput = { content: string; isError?: boolean };

const toolError = (message: string): ToolOutput => ({ content: message, isError: true });

// In the loop from Part 1:
const out = await runTool(block.name, block.input);
results.push({
  type: "tool_result",
  tool_use_id: block.id,
  content: out.content,
  ...(out.isError ? { is_error: true } : {}),
});

The same goes for empty results. [] is technically correct and practically useless. "No orders found for jane@example.com in the last 12 months" tells the model what was searched and lets it say something sensible to the customer.

When the model doesn't call a tool at all

The other half of this bug family is the agent that answers without looking anything up. The customer asks for their order status and the model replies "Orders usually arrive in 3 to 5 working days" without calling get_order.

Usually this is one of three things.

1. The tool doesn't obviously match the question. If the customer says "where's my stuff?" and the only tool is described as "Get order info", the link is weak. Descriptions written from the user's point of view ("Use this whenever the customer asks where their order is, or gives an order number") make the link obvious.

2. The system prompt doesn't say the agent must look things up. Be explicit about the rule and the reason:

You are the support agent for Northwind Home. You can see orders only through
your tools. Never state an order's status, delivery date or contents unless a
tool returned it in this conversation: your general knowledge about shipping
times is not about this customer's order. If you can't look it up, say so and
offer to pass the question to the team.

3. You are relying on forcing a tool call. Older code often set tool_choice to force a particular tool. On the newest Claude models (Opus 5.5, Sonnet 5.5), forcing a specific tool or "any tool" is rejected by the API. The supported pattern is tool_choice: { type: "auto" } (the default), clear descriptions, a clear instruction in the prompt, and a check in your code.

That last part matters. If an answer *must* be grounded in a tool, check that the tool actually ran before you show the answer:

const calledTools = new Set(
  messages.flatMap((m) =>
    m.role === "assistant" && Array.isArray(m.content)
      ? m.content.flatMap((b) => (b.type === "tool_use" ? [b.name] : []))
      : [],
  ),
);

const mentionsOrder = /\b\d{5}\b/.test(userInput);
if (mentionsOrder && !calledTools.has("get_order")) {
  // Don't show the answer. Ask the model to look it up, once.
  messages.push({
    role: "user",
    content:
      "Before answering, look up the order with get_order. Do not state order details you have not looked up.",
  });
  // ...run another turn of the loop
}

It looks crude. It is also the difference between "usually grounded" and "grounded or it doesn't ship".

Fewer, sharper tools

Every tool you add makes the choice harder. If two tools overlap, the model will sometimes pick the wrong one, and the more tools there are, the more overlaps there are. Before adding a tool, ask:

  • Could an existing tool do this with one more parameter? get_order with an optional include_history: boolean beats a separate get_order_history.
  • Is the difference between two tools clear from their names alone? If you need to read both descriptions to tell them apart, the model is in the same position.
  • Is this tool ever the right answer? Look at your traces. A tool that never gets called, or is only ever called by mistake, should go.

Test tool choice like any other code

You will change descriptions, add tools and switch models. Each change can quietly break tool choice for cases you are not looking at. The cheap protection is a tiny eval: a list of user messages, each with the tool you expect the model to call first. It doesn't have to be fancy to be useful.

const cases = [
  { input: "Where is order 48213?", expect: "get_order" },
  { input: "where's my order #48213", expect: "get_order" },
  { input: "I ordered a lamp last week, it hasn't come. jane@example.com", expect: "find_orders_by_customer" },
  { input: "My mug arrived smashed, order 51007, I want my money back", expect: "get_order" },
  { input: "Do you ship to Ireland?", expect: null }, // no tool: answer from the FAQ in the prompt
];

async function firstToolFor(input: string) {
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 16000,
    system: SYSTEM_PROMPT,
    tools,
    messages: [{ role: "user", content: input }],
  });
  const call = response.content.find((b) => b.type === "tool_use");
  return call?.type === "tool_use" ? call.name : null;
}

const RUNS = 3; // output varies between runs, so check each case more than once
let failures = 0;
for (const c of cases) {
  for (let i = 0; i < RUNS; i++) {
    const got = await firstToolFor(c.input);
    if (got !== c.expect) {
      failures++;
      console.log(`✗ "${c.input}" → ${got ?? "no tool"} (expected ${c.expect ?? "no tool"})`);
    }
  }
}
console.log(`${cases.length * RUNS - failures}/${cases.length * RUNS} passed`);

Start with ten cases taken from real conversations, especially the ones that went wrong. Every time a trace shows a bad tool choice, add that message to the list. After a month you have a regression suite for the part of your agent most likely to break, and you can change a description with confidence instead of hope.

Note that the refund case expects get_order first, not refund_order. The refund tool's description says to confirm the order before refunding, and this test checks the model actually does that.

Checklist

When an agent picks the wrong tool, or no tool:

  • Read the trace first (Part 1). Confirm which tool was called, with what input, and what came back.
  • Rename tools so their names alone say what they do and how they differ.
  • Write descriptions that say when to use the tool, when not to, and what it returns.
  • Describe every parameter. Give formats, examples and units. Use enums for fixed sets.
  • Turn on strict: true with additionalProperties: false, and still validate inside the tool.
  • Return errors with is_error: true and a message that says what to do next.
  • Replace empty results with a sentence.
  • Don't rely on forcing tools. Use clear instructions plus a check in code.
  • Merge or remove overlapping tools.
  • Keep a small tool-choice eval and add every bug you find to it.

Next in this series: the agent that never stops. Part 3 looks at loops that repeat the same tool call, conversations that outgrow the context window, and how to make long-running agents finish cleanly.

  • ai agents
  • debugging
  • tool use