Skip to content

Lesson 1 of 9 · 4 min read

Tool Contracts

Free lessonReviewed By the AIAgentInterviews editorial team
Reading position
In this lesson

TL;DR: The model chooses and calls tools using only what the contract says, and it rereads the contract every turn. Give each tool one job named as a verb and object, a description that says when to use it and when not to, a few required arguments with enums and formats, no identity parameters, and results trimmed to what the next decision needs. Mirroring an internal API one endpoint per tool is the most common way to get this wrong.

After this lesson, you should be able to write a tool definition a model uses correctly, decide the right granularity for a set of tools, estimate what tool definitions cost per run, and test tool selection with something better than watching a demo.

Before you read

Commit to an answer now. The lesson that follows explains it, and having guessed first, even wrongly, makes the explanation easier to remember.

  1. 1An agent has a tool update_order(order_id, fields) where fields is any JSON object. Asked to cancel an order, it sends fields={"status": "canceled"}. The order system expects "cancelled". What is the design problem?

The reader is a model

When a person calls your API, they read the documentation once, write code against it, and the code runs the same way every time. When an agent calls a tool, the model reads the tool's name, description and schema on every single turn, decides from that text whether this tool is the right one, and composes the arguments fresh each time. There is no compile step and no code review between the documentation and the call.

That changes what good looks like. A developer can cope with a vague parameter name because they will read the source when it breaks; a model will fill a vague parameter with something plausible and move on. A developer will notice two endpoints that do almost the same thing; a model will pick between them by surface similarity and be wrong some fraction of the time. Everything below follows from treating the contract as a prompt that is read on every turn.

What a good contract contains

name: orders_cancel
description: >
  Cancel an order that has not shipped. Use when the customer asks to cancel,
  not to return a delivered item (use returns_start for that). Fails if the
  order has shipped. Side effect: the customer is emailed a confirmation.
input_schema:
  type: object
  properties:
    order_id:
      type: string
      pattern: "^ord_[0-9]{6}$"
      description: The order id, for example ord_004471
    reason:
      type: string
      enum: [customer_request, duplicate, fraud_suspected]
  required: [order_id, reason]
  additionalProperties: false

(The same definition as JSON Schema; providers accept it as JSON, shown here in YAML so the description wraps.)

Each part does a job:

  • The name is a verb and an object, namespaced by service (orders_cancel, orders_get, returns_start). Names are the first thing the model matches on; process and handle match everything.
  • The description says what it does, when to use it, when to use something else instead, how it fails, and whether it has side effects. The "use returns_start for that" clause is the most valuable sentence in the definition, because it resolves the ambiguity the model would otherwise guess at.
  • The arguments are few, required where possible, constrained by enums, patterns and formats, and closed with additionalProperties: false. An example value in the description fixes the format faster than any prose.
  • What is absent matters as much. There is no customer_id: whose order this is comes from the session, so nothing the model reads can redirect it. There is no notify_customer flag: the side effect is policy, decided in code.

Results are part of the contract

The result is what the model reads next, so it is designed with the same care. Return what the next decision needs, not the raw record:

RAW = {"id": "ord_004471", "status": "processing", "customer": {"id": "c_8812",
       "email": "[email protected]", "addresses": ["..."] * 3},
       "lines": [{"sku": f"SKU{i}", "qty": 1, "price": 12.0} for i in range(40)],
       "audit": ["..."] * 200, "warehouse_notes": "..."}

def orders_get_result(order, max_lines=5):
    lines = order["lines"]
    return {
        "id": order["id"],
        "status": order["status"],
        "cancellable": order["status"] in ("pending", "processing"),
        "lines": [{"sku": l["sku"], "qty": l["qty"]} for l in lines[:max_lines]],
        "lines_total": len(lines),
        "more_lines": ("call orders_lines with page=2"
                       if len(lines) > max_lines else None),
    }

import json
print(len(json.dumps(RAW)) > 5 * len(json.dumps(orders_get_result(RAW))))  # => True
r = orders_get_result(RAW)
print(r["cancellable"], r["lines_total"])  # => True 40

Three habits are visible here. The result is projected down to fields the model will use, which saves tokens on every later turn because the history keeps it. It precomputes the fact the model would otherwise have to infer (cancellable), which turns a reasoning step into a lookup. And when it truncates, it says so and says how to get more, so the model never mistakes a partial list for the whole one.

Granularity: one tool per decision

The commonest design mistake is mirroring an internal API: one tool per REST endpoint. That produces dozens of fine-grained tools, several calls for every user intent, and many near-duplicates (get_order, get_order_v2, get_order_summary) for the model to confuse. The opposite mistake is the god-tool with a mode argument, which hides several decisions inside one schema the model has to understand completely to use correctly.

Aim between them: one tool per decision the model actually makes. "Find the customer's recent orders" is a decision; "look up customer id, then list orders by id, then fetch each order" is three implementation steps that belong inside one tool. "Cancel" and "start a return" are different decisions with different rules, so they are different tools even though both change an order's status.

SAME INTENT, TWO TOOL SURFACES
"Cancel my last order"

Mirror of the REST API

customers_lookup

orders_list

orders_get

orders_update

fields: any object

Model guesses the status value

Outcome, unsafe: 4 turns, one unconstrained write

Tools shaped around decisions

orders_recent

for the signed-in customer

orders_cancel

order_id, reason enum

Rules enforced in one place

Outcome, safe: 2 turns, a constrained write

What tool definitions cost

Tool definitions sit in the prompt on every turn, near the front, where they are usually part of the cached prefix:

40 tools × ~350 tokens each               = 14,000 tokens of definitions per turn
a 20-turn run                             = 280,000 tokens of definitions read
with a byte-stable prefix, most are cache reads; without one, all are full price
either way, the model attends over 40 options on every decision

The token bill is the smaller cost. The larger one is selection accuracy: more tools, and more overlapping ones, mean more wrong choices. When a surface grows past a few dozen tools, the fixes are consolidation, namespacing, and loading tools on demand (see Large Tool Surfaces).

Test tools like an interface

Watching a demo pick the right tool proves little. Build a small labelled set: user requests paired with the tool (and arguments) a correct agent would call, including deliberately ambiguous ones ("I want to send this back" should be returns_start, not orders_cancel). Run it after every change to a name or description, and read the confusion matrix: which tool gets chosen when another was right. Most fixes are a sentence in a description.

Say it in 30 seconds

"The model reads every tool's name, description and schema on every turn and picks by that text, so I write tools for that reader. One tool per decision the model makes, named verb-object with a service namespace; a description that says when to use it, when to use something else, how it fails and what it changes; few required arguments with enums and formats, and nothing that sets identity. Results are trimmed to what the next step needs, precompute obvious facts, and say when they are truncated. I test selection with a labelled set, not a demo."

Check yourself

Answer aloud or on paper before revealing. Producing the explanation unaided is exactly what a panel listens for.

  1. 1Two tools, search_orders and find_orders, return almost the same thing. The agent picks the wrong one 15% of the time. What do you change first?

  2. 2A tool returns a 30 KB customer record on every call. Why does that matter beyond the cost of one call?

  3. 3Should a send_email tool take a from_address argument?

Practise it as an interviewer asks it

Course lessons that teach this

Related lessons