Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Design tools an AI agent can use well

Take one badly designed agent tool, fix its names, descriptions, arguments, errors and output size, and measure the difference with a small eval you can rerun.

By Intermediate1 h hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

An agent only knows a tool through its name, its description, its input schema, what it returns and what its errors say. Those five things decide whether the model picks the right tool, fills in the right arguments and recovers when something goes wrong. Good tool design means: a few task-shaped tools with namespaced names, descriptions that say when to use them and what they return, typed arguments with enums and defaults, error messages that say how to fix the call, and results that are small and high-signal.

This tutorial takes one bad tool, a thin wrapper around an order database, and rebuilds it step by step. Then it measures the change with a small eval: the same eight questions, run several times against each version, scoring correct answers, tool calls, tool errors and tokens. It is written for the Anthropic API, but the design rules apply to MCP servers and to any framework. It was written on 25 November 2026 with anthropic 2.13.0 and claude-haiku-5-5.

The bad tool

Here is a pattern seen in many first agents: expose the database, let the model work it out. Create shop.py with a small in-memory shop and version 1 of the tool:

"""A tiny order database and two versions of the same tool: before and after."""
import json
from datetime import date, timedelta

TODAY = date(2026, 11, 25)
CUSTOMERS = {
    "C-1001": {"name": "Ana Silva", "email": "ana@example.com", "tier": "gold"},
    "C-1002": {"name": "Ben Okafor", "email": "ben@example.com", "tier": "standard"},
    "C-1003": {"name": "Chloe Martin", "email": "chloe@example.com", "tier": "standard"},
}
ORDERS = [
    {
        "order_id": f"O-{5000 + i}",
        "customer_id": ["C-1001", "C-1002", "C-1003"][i % 3],
        "status": ["delivered", "shipped", "processing", "cancelled"][i % 4],
        "total": round(20 + i * 7.5, 2),
        "placed": (TODAY - timedelta(days=i * 3)).isoformat(),
        "items": [{"sku": f"SKU-{i}{j}", "qty": 1 + j, "warehouse": "LDN-2", "batch": f"B{i * 97 % 1000}"} for j in range(3)],
        "audit": [{"ts": f"2026-11-{(i % 24) + 1:02d}T10:00:00Z", "event": "status_sync", "actor": "system"}] * 5,
    }
    for i in range(40)
]

# ---------- Version 1: what a thin wrapper over the database looks like ----------

V1_TOOLS = [
    {
        "name": "query",
        "description": "Query the data.",
        "input_schema": {
            "type": "object",
            "properties": {
                "q": {"type": "string"},
                "t": {"type": "string"},
            },
            "required": ["q", "t"],
        },
    }
]


def v1_query(q: str, t: str) -> str:
    if t not in ("orders", "customers"):
        return "ERR 400"
    rows = ORDERS if t == "orders" else [{"id": k, **v} for k, v in CUSTOMERS.items()]
    hits = [r for r in rows if q.lower() in json.dumps(r).lower()]
    return json.dumps(hits)

Read it as the model would, knowing only the definition. What is t? What does q search? What comes back? Problems, one per design rule:

  1. Name. query says nothing about the domain. Next to a second “query” tool from another server, the model cannot tell them apart.
  2. Description. “Query the data” gives no hint of when to use it or what it returns.
  3. Arguments. q and t are opaque, and t accepts any string though only two values work. Orders hold customer ids, not names, so “Ana Silva” in q finds no orders at all.
  4. Errors. ERR 400 tells the model nothing about what to change.
  5. Output. Every field of every match, including line items and audit logs nobody asked for.

1. Measure the output before you change anything

Context is the agent’s working memory, and every tool result spends it. Anthropic’s guidance on writing tools says tools should “return only high signal information back to agents”, and notes that Claude Code caps tool responses at 25,000 tokens by default. Start by measuring. Create size.py:

"""Measure what each tool version puts into the model's context."""
import json

from shop import HANDLERS, TOOLS

print("tool definitions:", {v: len(json.dumps(t)) for v, t in TOOLS.items()}, "characters")
print("v1 orders for Ben:", len(HANDLERS["v1"]["query"]("C-1002", "orders")), "characters")
print("v2 orders for Ben:", len(HANDLERS["v2"]["shop_list_orders"]("C-1002")), "characters")
print("v1 error:", HANDLERS["v1"]["query"]("Ben", "order"))
print("v2 error:", HANDLERS["v2"]["shop_list_orders"]("Ben"))

It needs version 2 to exist, so run it after step 5. These are the numbers we got:

tool definitions: {'v1': 179, 'v2': 1064} characters
v1 orders for Ben: 9281 characters
v2 orders for Ben: 919 characters
v1 error: ERR 400
v2 error: Unknown customer_id 'Ben'. Ids look like C-1001. Call shop_find_customer with the person's name to get it.

The trade is visible already: version 2’s definitions are about six times longer, and its typical result is about ten times shorter. Definitions are paid once per request (and cache well); results are paid on every call and stay in the conversation. Characters are a rough proxy for tokens; use your provider’s token-counting endpoint if you need exact figures.

2. Shape tools around tasks, and namespace them

Replace one generic tool with tools that match what the agent is asked to do. Support questions start with a person (“Ana’s orders”) and end with orders, so the natural pair is “find a customer” and “list a customer’s orders”. Anthropic’s guidance puts it plainly: “More tools don’t always lead to better outcomes.” Two task-shaped tools beat one generic tool and beat ten thin wrappers around every endpoint.

Prefix the names with the service: shop_find_customer, shop_list_orders. In an agent connected to several MCP servers, prefixes stop the model confusing your list_orders with another system’s.

3. Write descriptions for a new colleague

A description should say what the tool does, when to use it, what it returns, and how it relates to the other tools. Add version 2 to shop.py:

# ---------- Version 2: designed for the agent ----------

V2_TOOLS = [
    {
        "name": "shop_find_customer",
        "description": (
            "Find a customer by name or email. Returns up to 5 matches with customer_id, name and tier. "
            "Use this first when the user names a person; other tools need the customer_id."
        ),
        "input_schema": {
            "type": "object",
            "properties": {"name_or_email": {"type": "string", "description": "Full or partial name, or an email address"}},
            "required": ["name_or_email"],
        },
    },
    {
        "name": "shop_list_orders",
        "description": (
            "List a customer's orders, newest first. Returns order_id, status, total (GBP) and placed date, "
            "10 per page. Set response_format to 'detailed' only if you need line items."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "customer_id": {"type": "string", "description": "For example C-1001, from shop_find_customer"},
                "status": {"type": "string", "enum": ["any", "processing", "shipped", "delivered", "cancelled"], "default": "any"},
                "page": {"type": "integer", "minimum": 1, "default": 1},
                "response_format": {"type": "string", "enum": ["concise", "detailed"], "default": "concise"},
            },
            "required": ["customer_id"],
        },
    },
]

Each sentence earns its place. “Use this first when the user names a person” tells the model the order of calls. “Newest first” answers “most recent order” questions without extra calls. “Total (GBP)” stops it guessing the currency. The description of customer_id gives an example value and says where the value comes from.

4. Make arguments hard to get wrong

The schema is part of the prompt. Rules that help:

  • Unambiguous names. name_or_email, not q. customer_id, not id.
  • Enums for closed sets. status lists the five values that exist, so the model cannot invent “complete” or “open”.
  • Defaults for the common case. status defaults to any, page to 1, response_format to concise. The simplest correct call is {"customer_id": "C-1001"}.
  • A detail switch instead of a second tool. response_format lets the model ask for line items when it needs them, an idea from the same Anthropic guidance.

5. Return small results and errors that teach

Add the handlers to shop.py:

def v2_find_customer(name_or_email: str) -> str:
    q = name_or_email.lower().strip()
    hits = [{"customer_id": k, "name": v["name"], "tier": v["tier"]} for k, v in CUSTOMERS.items()
            if q in v["name"].lower() or q == v["email"]]
    if not hits:
        return f"No customer matches '{name_or_email}'. Try part of the surname, or the exact email address."
    return json.dumps(hits[:5])


def v2_list_orders(customer_id: str, status: str = "any", page: int = 1, response_format: str = "concise") -> str:
    if customer_id not in CUSTOMERS:
        return (f"Unknown customer_id '{customer_id}'. Ids look like C-1001. "
                "Call shop_find_customer with the person's name to get it.")
    rows = [o for o in ORDERS if o["customer_id"] == customer_id and status in ("any", o["status"])]
    start = (page - 1) * 10
    chunk = rows[start:start + 10]
    keys = ["order_id", "status", "total", "placed"] + (["items"] if response_format == "detailed" else [])
    out = {"orders": [{k: o[k] for k in keys} for o in chunk], "page": page, "total_orders": len(rows),
           "more": start + 10 < len(rows)}
    return json.dumps(out)


HANDLERS = {
    "v1": {"query": v1_query},
    "v2": {"shop_find_customer": v2_find_customer, "shop_list_orders": v2_list_orders},
}
TOOLS = {"v1": V1_TOOLS, "v2": V2_TOOLS}

Three decisions to notice:

  • Errors are instructions. When the model passes a name where an id belongs, which it will, the error says what an id looks like and which tool returns one. The model fixes the call on the next turn instead of giving up or guessing.
  • Pagination with a total. Ten orders per page keeps results small, and total_orders answers “how many orders” without fetching every page. more tells the model whether another page exists.
  • Only the fields that answer questions. The audit log and warehouse batches are gone. If an agent ever needs them, that is a different task and probably a different tool.

Now run python size.py from step 1.

6. Measure the change with a small eval

Design changes are guesses until you measure them. Create tool_eval.py, which runs eight support questions with each version and scores them:

"""Run the same tasks with v1 and v2 tools and compare: correct answers, tool calls, errors, tokens."""
import json
import sys

import anthropic

from shop import HANDLERS, TOOLS

MODEL = "claude-haiku-5-5"
SYSTEM = "You are a support assistant for an online shop. Use the tools to answer. Be brief."

# (question, check on the final answer)
TASKS = [
    ("How many orders has Ana Silva placed in total?", lambda a: "14" in a),
    ("What is the status of Ben Okafor's most recent order?", lambda a: "shipped" in a.lower()),
    ("How many of Chloe Martin's orders were cancelled?", lambda a: "3" in a),
    ("Which of Ana Silva's orders are still processing? Give the order ids.",
     lambda a: all(o in a for o in ["O-5006", "O-5018", "O-5030"])),
    ("What was the total of Chloe Martin's most recent shipped order?", lambda a: "57.5" in a),
    ("Does a customer called Dmitri Ivanov have an account?", lambda a: "no" in a.lower() or "not" in a.lower()),
    ("Is Ben Okafor a gold customer?", lambda a: "no" in a.lower() or "standard" in a.lower()),
    ("How many orders does ben@example.com have that are shipped?", lambda a: "4" in a),
]


def run_task(client, version: str, question: str, max_turns: int = 8) -> dict:
    messages = [{"role": "user", "content": question}]
    stats = {"tool_calls": 0, "errors": 0, "input_tokens": 0, "result_chars": 0}
    for _ in range(max_turns):
        resp = client.messages.create(
            model=MODEL, max_tokens=1024, system=SYSTEM, tools=TOOLS[version], messages=messages,
        )
        stats["input_tokens"] += resp.usage.input_tokens
        if resp.stop_reason != "tool_use":
            answer = "".join(b.text for b in resp.content if b.type == "text")
            return {**stats, "answer": answer}
        messages.append({"role": "assistant", "content": resp.content})
        results = []
        for block in resp.content:
            if block.type != "tool_use":
                continue
            stats["tool_calls"] += 1
            try:
                out = HANDLERS[version][block.name](**block.input)
            except Exception as e:  # wrong argument names, missing arguments
                out = f"{type(e).__name__}: {e}"
            if out.startswith(("ERR", "Unknown", "No customer", "TypeError")):
                stats["errors"] += 1
            stats["result_chars"] += len(out)
            results.append({"type": "tool_result", "tool_use_id": block.id, "content": out})
        messages.append({"role": "user", "content": results})
    return {**stats, "answer": "(ran out of turns)"}


def main(runs: int) -> None:
    client = anthropic.Anthropic()
    for version in ("v1", "v2"):
        totals = {"correct": 0, "tool_calls": 0, "errors": 0, "input_tokens": 0, "result_chars": 0}
        n = 0
        for question, check in TASKS:
            for _ in range(runs):
                r = run_task(client, version, question)
                n += 1
                ok = check(r["answer"])
                totals["correct"] += ok
                for k in ("tool_calls", "errors", "input_tokens", "result_chars"):
                    totals[k] += r[k]
                if not ok:
                    print(f"  [{version}] FAIL {question!r} -> {r['answer'][:80]!r}")
        print(f"{version}: {totals['correct']}/{n} correct, "
              f"{totals['tool_calls'] / n:.1f} tool calls per task, {totals['errors']} tool errors, "
              f"{totals['input_tokens'] // n} input tokens per task, {totals['result_chars'] // n} result characters per task")


if __name__ == "__main__":
    main(int(sys.argv[1]) if len(sys.argv) > 1 else 3)

Run it three times per question:

pip install anthropic==2.13.0
export ANTHROPIC_API_KEY=sk-ant-...
python tool_eval.py 3

It prints one summary line per version and every failed answer above it. The four numbers tell you different things:

Metric What it tells you
Correct answers Whether the agent can do the job with these tools
Tool calls per task Whether it finds the right path, or flails
Tool errors Whether names, schemas and descriptions lead to valid calls
Input tokens per task What the design costs, including every result that piles up in the conversation

Read the failed answers, not just the totals. If v1 fails “How many orders has Ana Silva placed”, look at why: did it pass the name to q with t="orders" and get an empty list? That is the argument-design problem from the top of the page, now with evidence.

The checks are deliberately crude string matches. They are enough to compare two versions of a tool on questions with one right answer. For open-ended answers, use a calibrated judge as in LLM-as-a-judge.

7. Keep the eval and iterate

Change one thing at a time and re-run. Good experiments to try:

  • Delete the “Use this first” sentence from shop_find_customer and see whether tool errors rise.
  • Change the page size from 10 to 50 and watch input tokens.
  • Replace the instructive error with "Not found" and count how many tasks run out of turns.
  • Add a third, unrelated tool (say, shop_get_weather) to see whether a cluttered tool list changes the choices.

Run each question several times, because model behaviour varies between runs. When a real user hits a failure in production, add that question to TASKS. Over time this file becomes the regression suite for your tool design, in the same way evaluating AI agents grows a suite for the whole agent.

The rules in one place

Part Rule
Set of tools A few task-shaped tools, not one per endpoint; namespace with a service prefix
Name Verb and object (shop_list_orders), unique across every server the agent uses
Description What it does, when to use it, what it returns, which tool comes before it
Arguments Clear names, enums for closed sets, defaults for the common case, an example value
Errors Say what was wrong and how to fix the call; return them as results, not exceptions
Output Only high-signal fields, paginated, with totals; a detail switch for rare needs
For code callers Document the output format (field names and types), because code parses it

The last row matters more as agents call tools from code, as in Claude Code’s Code Mode and programmatic tool calling, where the model writes a script that parses your output. Code Mode and programmatic tool calling explains that shift.

Pitfalls

Optimising the description by feel. Descriptions that read well to you can still mislead the model. Run the eval after each change.

Returning raw API responses. Upstream APIs return everything. Map to the fields the agent needs, in your tool, before the model sees it.

Throwing exceptions for expected failures. A crash ends the turn in many frameworks. “No customer matches” is information the model can use.

Too many near-identical tools. get_order, fetch_order, order_lookup from three servers make choice harder. Remove or rename overlaps.

Testing only the happy path. Include questions about people who do not exist, ambiguous names and requests the tools cannot answer. That is where design differences show.

Next steps

Covers

Tools

Check your understanding

Design tools for AI agents quiz

What an agent knows about a tool, task-shaped and namespaced tools, descriptions, arguments with enums and defaults, errors that teach, small results, and measuring changes with an eval.

8 questions · pass mark 70%

Question 1 of 80 answered
  1. What does an agent know about a tool it can call?
  • Build your first agent in Python

    Three tools, a hard turn limit, a clear stop condition and a log of every tool call it makes.

    TutorialIntermediate1 h

  • Evaluate AI agents: outcomes, trajectories and tool use

    Build an agent eval harness that checks the final state, the tool-call trajectory and a judged transcript, run each task several times and read the traces.

    TutorialAdvanced1 h 30 min

  • Code Mode: when an agent writes code to call its tools

    Claude Code's experimental Code Mode has Claude write JavaScript that calls its tools. How it works and what it changes for permissions, hooks and sandboxing.

    Article

  • Tool calling

    A model emitting a structured request to call a defined function, which your code runs and whose result is then fed back to the model.

    Glossary

  • Build an MCP server in TypeScript

    Build a small MCP server with the official TypeScript SDK v2, test it from the command line and in MCP Inspector, then connect it to Claude Code or Cursor.

    TutorialIntermediate1 h

Back to top