Designing tools for agents

A tool is a contract between predictable software and a caller that is not predictable. Design it for a reader with a small working memory and no inside knowledge, and then measure how real agents use it.

Tool design in 60 seconds

  • What: a tool is a contract between deterministic code and a caller that may use it well, badly or not at all.
  • Shape for the task: a few distinct tools built around what the agent is trying to achieve beat many thin wrappers over every endpoint.
  • Return less, but better: high-signal fields, readable names, hard size caps and errors that say what to change.
  • Describe like an onboarding note: explicit descriptions and strict schemas, with parameters that cannot be misread.
  • Improve by measurement: run realistic tasks, read transcripts and change one thing at a time.

The problem it solves

Most teams build first tools by wrapping existing endpoints. It is the fastest route, and it builds in a mismatch. An endpoint was designed for a developer who reads the docs once and holds state in variables. An agent reads the description fresh on every run, has a limited window, and decides on each step whether to call the tool at all.

A conventional function is a contract between two pieces of deterministic software. A tool is a contract between that software and a caller that may call it, skip it, call it with a guess, or ask the user a question instead. You are writing for a reader, not only a compiler.

Shape tools around the task, not the endpoint

Memory is cheap for software and scarce for an agent. A function that returns every contact costs a program nothing. It forces an agent to read every record in its window, with the answer buried in the middle.

So prefer tools that do the narrowing for the agent. A search tool takes a name and returns a few matches, where a list tool returns the lot. A schedule tool that finds a free slot replaces three separate calls to list people, list events and create an event, and removes two chances to go wrong. A log tool can return the matching lines with a little context around each, where a raw log reader returns the file. A customer tool can compile the recent orders, open tickets and account status in one result.

One task-shaped tool replaces a chain of thin wrappers, which cuts calls, tokens and chances to go wrong.

Do not overdo it. A giant tool with twenty modes is as confusing as twenty overlapping tools. Aim for a small set where each tool has one clear purpose and a boundary you can state in a sentence.

  • Namespace by service and resource: names such as billing_invoice_search and billing_invoice_refund group related tools and make the right choice easier when the toolset grows.
  • Test the naming scheme: whether the service comes first or last in a name can shift selection accuracy, and the effect differs between models. Measure it instead of assuming.
  • Split by risk: keep read-only and destructive actions in separate tools, so permissions and approvals can differ.

What a tool returns

Every token in a result competes with the instructions and history around it. Return what the next decision needs and little else. Flags the agent cannot act on are noise, and noise invites mistakes.

Opaque identifiers deserve special care. An agent handed a long random string must copy it exactly, and sooner or later it will not. Resolve identifiers to meaningful names, and keep the raw ID only where a follow-up call needs it. Even a numbered index that maps to the real ID on the server reduces invented values. Where some callers need the ID, add a response format parameter with concise and detailed settings, and default to concise. Test JSON against markdown too, since the best output shape varies by task.

Token efficiency and error messages

Give every tool that can return a lot of data pagination, filtering or truncation, with safe defaults. Add a hard cap on response size that no parameter can override. It protects you from the one query that matches half the database.

When you truncate, say so, and say how to narrow the request. A message such as "Showing 25 of 1,840 matches. Add a date range or a customer name to reduce the list" turns a dead end into a next step. Errors deserve the same care. A stack trace or a bare code teaches the agent nothing. A sentence that names the bad parameter, states the accepted range and gives a valid example usually fixes the problem on the next call.

A next-step hint is a cheap extra: after a search, mention which tool opens a record or fetches the next page.

Descriptions and schemas

Write each description as an onboarding note for a sharp new colleague who knows nothing about your systems. State what the tool does, when to use it, when not to, and what each parameter means. Spell out what feels obvious to you: query syntax, internal terms, how entities relate. Include an example and an edge case, and name the neighbouring tool for the case this one does not cover.

Schemas should be strict. Use enumerations where the options are known, mark required fields, and name parameters without ambiguity: customer_id rather than customer, start_date_utc rather than start. Small wording changes can move accuracy a surprising amount, so descriptions belong under evaluation.

Then make mistakes hard to make. If relative file paths cause bugs when the working directory changes, require absolute paths. If a date can be read two ways, require one format and reject the other with a helpful message. Choose input formats that a model finds natural to write: leave room to reason before committing to an answer, stay close to ordinary text, and avoid asking the model to count lines or escape long blocks of code.

Improving tools with an evaluation loop

You will not get a tool right by thinking about it. Build a quick prototype, then test it against realistic work. Write tasks that need several tool calls, grounded in real data. Give each an outcome that code can check, such as a record in the right state. Avoid verifiers so strict that they reject a correct answer phrased differently, and tasks that assume only one route to the result.

Tools improve through a loop of prototype, task run, transcript review and refinement, checked against a held-out set.

Run each task through a plain agent loop and record accuracy, time per call and per task, number of tool calls, tokens used and tool errors. Ask the agent where the tool confused it, then read the transcripts, including what it chose not to do.

  • Many repeated calls: the tool probably needs better pagination, a larger default limit or a filter.
  • Invalid parameter errors: the description or the schema is unclear, or two parameters look alike.
  • Wrong tool chosen: two tools overlap, or one description does not say what it is not for.
  • Tool never called: the description does not match how users phrase the need.

Keep a held-out set of tasks that you never tune against, so you can tell real gains from overfitting.

Writes, safety and change

Read tools are forgiving. Write tools are not, and agents retry. Give every tool that changes state a request ID supplied by the caller, and have the server return the earlier result when it sees the same ID again. See idempotency. Offer a dry-run mode for destructive actions that returns what would change without changing it, so the agent, or a person, can inspect the plan first. Mark destructive or outward-reaching tools so the harness can require approval.

Scope credentials to the tool and the task. A tool that reads invoices should hold a token that can only read invoices, for the tenant on whose behalf it acts. Never let the agent choose its own privilege level through a parameter. The security page covers the wider threat model.

Tools used by deployed agents are an API, so treat changes like API changes. Version the schema, keep the old version working for a notice period, and tell agents about the new one through the description. Group tools of one domain behind a single protocol server, such as one for billing and another for support, rather than one for the whole company. See tool calling and MCP.

A worked example

Acme Logistics runs a support agent with three tools wrapping its order service: list_orders, get_order and list_events. In an internal test of 60 tasks, the agent completed 38, which is 63 percent. Transcripts showed list_orders returning an average of 4,200 tokens per call, with the agent often paging through three calls to find one order. Some 14 percent of calls failed with an invalid order ID, because the agent copied 36-character identifiers imperfectly.

  • Change one: replace list_orders with find_orders, which takes a customer name or reference and a date range, and returns at most 10 results with a readable summary and a short index. Average result size fell from 4,200 to 380 tokens.
  • Change two: merge get_order and list_events into order_status, with a response_format of concise by default. The concise form returns state, promised date and the last event.
  • Change three: rewrite errors. "Invalid ID" became "No order with reference AC-1042. References look like AC-1234. Use find_orders to search by customer."
  • Result: on the same 60 tasks, completion rose to 52, or 87 percent. Calls per task fell from 7.1 to 3.4, and invalid parameter errors dropped from 14 percent to 2 percent. On a held-out set of 25 tasks the gain was smaller, 71 percent to 84 percent, which was still worth shipping.

Building it

A task-shaped search tool with limits, hints and clear errors (illustrative) (python)
import re

MAX_RESULTS = 10          # hard cap, no parameter can raise it
DEFAULT_RESULTS = 5       # safe default if the agent says nothing
REF_PATTERN = re.compile(r"^AC-\d{4}$")

def find_orders(customer_name: str, date_from: str, date_to: str,
                limit: int = DEFAULT_RESULTS, response_format: str = "concise"):
    """Find orders for one customer in a date range.

    Use this to locate an order. To see full detail for one order, call
    order_status with its reference. Dates are ISO format, e.g. 2026-03-01.
    """
    if response_format not in ("concise", "detailed"):
        return error("response_format must be 'concise' or 'detailed'.")
    if not customer_name.strip():
        return error("customer_name is required, e.g. 'Dana Smith'.")

    limit = min(max(limit, 1), MAX_RESULTS)           # clamp, never trust input
    rows = orders.search(customer_name, date_from, date_to)   # placeholder store
    shown = rows[:limit]

    lines = []
    for i, o in enumerate(shown, start=1):
        # Readable names first. The raw internal id stays on the server.
        line = f"{i}. {o.reference} | {o.status} | {o.item_summary}"
        if response_format == "detailed":
            line += f" | placed {o.placed_on} | total {o.total}"
        lines.append(line)

    note = ""
    if len(rows) > len(shown):
        # Tell the agent how to narrow the request, not just that it was cut.
        note = (f"Showing {len(shown)} of {len(rows)} matches. "
                "Narrow the date range to see fewer.")
    return {"results": lines, "note": note}

def error(message: str):
    # Say what to change. No stack traces, no bare codes.
    return {"error": message}

orders.search is a placeholder for your own data layer.

Design decisions

  • Tool boundaries: draw them around tasks and domains. Decide who owns each tool and each protocol server, and keep one server per domain with a clear purpose.
  • Permission model: least privilege per tool and per task, with credentials issued for the acting tenant. Destructive and open-world tools sit behind approval gates.
  • Latency budgets: give each tool a time budget and timeout, and turn slow work into an asynchronous job with a status tool.
  • Cost and rate limits: set per-tool and per-run ceilings. Some tools are cheap to call and some trigger paid downstream work, and the agent cannot tell which. See rate limiting.
  • Versioning policy: schemas are versioned, old versions have a notice period, and descriptions are reviewed like code.
  • Write semantics: every state-changing tool accepts a request ID and is safe to retry.
  • Review scorecard: before a tool ships, check purpose, overlap with existing tools, result size, error quality, description clarity, permissions, idempotency and a passing evaluation.

Measuring it

  • Task success rate: on realistic multi-step tasks with verifiable outcomes, tracked on a tuning set and a separate held-out set.
  • Tool calls per task: a rise usually points to missing filters, poor pagination or unclear selection.
  • Tool error rate by type: invalid parameters, not found, timeouts and permission denials, each with its own fix.
  • Tokens per result: the mean and 95th percentile of what each tool puts into the context.
  • Selection accuracy: how often the agent picks the intended tool when two plausible ones exist.
  • Time per call and per task: tail latency matters, because one slow tool dominates the run.

When to use it, and when not to

SituationApproachWhy
A new agent over an existing APITask-shaped tools, not wrappersWrappers push the narrowing work onto the agent and fill its context.
The agent often needs one fact from a large datasetA search tool with a hard capThe agent reads a few relevant results, not the whole set.
Actions that change money or dataIdempotent write tools with a dry run and approvalRetries stay safe and people see the plan first. See idempotency.
Tools shared by many teams and agentsA domain server, versioned schemas and a scorecardMany callers depend on the contract, so changes need care.

Trade-offs

DimensionEffectWhat to do about it
Build effortTask-shaped tools take more design than wrapping endpoints.Start with the three or four tasks that matter most and shape those first.
MaintenanceDescriptions and schemas become a contract that must be versioned.Assign owners and review changes with the evaluation set.
QualityBetter tools raise task success and cut calls and tokens.Measure on a held-out set, not only on tasks used for tuning.

A conventional API assumes a developer who reads the documentation once. A tool assumes a reader that sees the description on every run, in a limited window. Tool calling and MCP describes how tools are exposed and invoked. This page is about what goes inside them. Context engineering decides what the model sees overall, and tool results are one of its largest inputs. The harness decides which tools are available and when approvals apply.

What this means for your role

Common mistakes

Further reading

A good tool is easy to choose, hard to misuse and kind in how it fails. Shape it around the task, keep its output small and readable, and let real transcripts tell you what to fix next.

Search topics

↑↓ to move · Enter to open · Esc to close