IamBishal

Chapter 8 · Part II: Tools and the agent loop

Designing good tools: naming, descriptions, errors, idempotency and granularity

How to design tools a model uses correctly and that do no harm when it uses them wrongly. The chapter redesigns the Kestrel operations tools: clearer names and descriptions tested with a selection check, merged and split tools, validated and bounded inputs, recoverable error results, and outputs shaped by field selection, truncation and pagination. It ends with read tools free of side effects and an idempotent create_return_authorisation write tool.

35 min read · from Agentic AI Foundations

At the end of Chapter 7, The agent loop, the operations agent that investigates Tomasz Wójcik's late shipments had a correct loop. It runs inside a run budget, reports which limit stopped it, and hands tool failures to the model as error results. From here the quality of its work depends on its tools: what they are called, what they claim to do, what they accept and what they send back.

This chapter has two goals: tools the model uses correctly, and tools that do no harm when a call is wrong, because some calls will be. Both rest on the split from Chapter 6, Tool calling from first principles: the model only asks for a call, and the program decides whether to run it and does the running.

By the end of the chapter you will be able to:

  • rename and re-describe similar tools, and measure the effect on a fixed set of requests
  • merge chatty tools and split overloaded ones
  • validate and limit tool inputs
  • write error results the model can recover from
  • shape outputs with field selection, truncation and pagination
  • keep read tools free of side effects, and make a write tool, create_return_authorisation, idempotent with an idempotency key

We reuse the tool registry and dispatcher from Chapter 6 (in its tools.py, copied into Chapter 7), the agent loop from Chapter 7, and pydantic validation from Chapter 5, Structured outputs. The code is in books-code/agentic-ai-foundations/ch08-designing-tools/, which stands alone: the model client, fake model, settings, loop and run budget are copied from Chapter 7's folder. The tools call the Kestrel mock API that uv run kestrel up starts at http://127.0.0.1:8700.

Provider details below are as of November 2026 and change quickly; check the linked Anthropic page before relying on one.

1. Why the model gets tools wrong

Anthropic lists the most common tool failures as choosing the wrong tool and passing incorrect parameters, especially when tool names are similar (Introducing advanced tool use).

Both come from what the model can see: never your Python, only a name, a description, an input schema and the results. Wherever that text leaves room, the model guesses.

So the program does the other half of the work. It validates arguments before anything runs, keeps read tools free of side effects, and makes write tools idempotent. This is the principle behind Chapter 7's run budget: limits are enforced in code, not requested of the model.

Our "before" set is Chapter 7's three operations tools, copied unchanged into tools_v1.py, plus two support tools written the way a first draft usually is:

ch08-designing-tools/ch08/tools_v1.py (excerpt: the two first-draft tools)
class TicketIdArgs(BaseModel):
    ticket_id: str = Field(description="Ticket ID.")


class PolicyNameArgs(BaseModel):
    name: str = Field(description="Policy name.")

def first_draft_tools(http: httpx.Client) -> list[Tool]:
    """New in Chapter 8, written as a first draft: they work, but say little."""
    return [
        Tool("get_ticket", "Get a support ticket.", TicketIdArgs, partial(get_ticket, http)),
        Tool("get_policy", "Get a policy document.", PolicyNameArgs, partial(get_policy, http)),
    ]

Both work, but neither says what it returns, when to use it, or what to use instead. And Chapter 7's get_order and get_shipment both partly answer "is this order late?".

The figure follows one tool call through the program and marks the checkpoints this chapter adds.

flowchart LR
    M["Model"] -->|"tool call"| S["Selection:<br/>name + description"]
    S --> V{"Input validation<br/>(pydantic)"}
    V -->|"valid"| X["Execution"]
    V -->|"invalid"| E["Error result"]
    X -->|"failure"| E
    X -->|"output"| O["Output shaping:<br/>select, truncate, paginate"]
    O --> R["Tool result"]
    R --> M
    E --> M

Selection happens inside the model; every checkpoint after it runs in your code.

2. Names, descriptions and parameters the model can choose between

Here is where the chapter ends up. Four v2 read tools replace the five v1 tools, and one write tool is new:

v2 toolReplacesAnswers
get_delivery_statusget_order and get_shipmentIs this order, or this ticket's order, late?
list_shipmentssame name, enum carrier, pagesWhich shipments match these filters?
get_ticketsame name, messages optionalWhat does this ticket say?
get_policysame name, long text truncatedWhat does this policy say?
create_return_authorisationnewSet up a return for this ticket.

get_order's channel, total and currency are dropped on purpose: no request in the operations fixture needs them.

Anthropic's Writing effective tools for AI agents suggests namespacing tools by service and by resource, so related tools look related. The same article reports that prefix- and suffix-based namespacing had non-trivial effects on Anthropic's tool-use evaluations, and that the effect varied by model.

The tools in Chapters 6 and 7 are named verb first (get_order, list_shipments), and this chapter keeps that, adding detail only where verb and resource are ambiguous: get_order and get_shipment become get_delivery_status. A service prefix wouldn't help, because Kestrel's systems are too coarse to tell these tools apart. Whether resource-first names would suit your model better is open; the selection check below compares v1 with v2, but the same fixture can test a naming scheme.

Names also have a hard format, set by each provider. The Claude docs (Define tools) require tool names to match ^[a-zA-Z0-9_-]{1,128}$. Every name here is well inside it.

Descriptions carry most of the meaning. A useful one says what the tool returns, when to use it, which tool to use instead in the nearby cases, and what each parameter means. The merged tool's description:

ch08-designing-tools/ch08/tools.py (excerpt: a v2 description)
DELIVERY_STATUS_DESCRIPTION = (
    "Returns delivery status for one order: order_status, carrier, shipment_status (in_transit, "
    "delivered or lost), promised_by, delivered_at (null until delivered) and a late flag; an "
    "unshipped order has shipment null and its promised_date instead. Pass "
    "the id the user gave, either an order id (O-0013833) or a ticket id (T-000281); for a "
    "ticket, the tool finds the order itself. To read what a ticket says, use get_ticket. To "
    "find late shipments across many orders, use list_shipments."
)

Descriptions have a cost: every definition is sent with every model call, so each sentence is paid for on every step. Anthropic reports that loading the definitions of 50+ MCP tools upfront costs about 72K tokens. MCP is Book 3's subject, but the point holds for five tools: write what changes the model's choice, and nothing else.

Parameters need the same care. Name each one after the domain (order_or_ticket_id, not id), document its format, and use enums for closed sets such as carriers. The input schema is generated from a pydantic model (Chapter 6), so every Field description and constraint ends up in the text the model reads.

3. Measuring whether the rewrite helped

A better description is a guess until you test it. Anthropic's tools article says building an evaluation lets you measure tool performance systematically. The smallest useful version is a selection check: does the model's first tool call go to a right tool? A full eval, with golden tasks, pass rates, cost and steps, will come in Chapter 13, Testing your first agent.

The check reads a fixture: fixed Kestrel requests, each with the tools a first call may reasonably use under each set.

ch08-designing-tools/ch08/selection_fixture.jsonl (first three entries)
{"request": "Is order O-0013833 late?", "expected": {"v1": ["get_shipment", "get_order"], "v2": ["get_delivery_status"]}}
{"request": "Ticket T-000281 asks where the order is. Was it late?", "expected": {"v1": ["get_ticket"], "v2": ["get_delivery_status"]}, "ticket_to_delivery": true}
{"request": "What does ticket T-000281 say? Quote the customer.", "expected": {"v1": ["get_ticket"], "v2": ["get_ticket"]}}

Each entry lists acceptable tools per set. Under v1, calling get_order first for "Is order O-0013833 late?" is a sensible plan, not a mistake. An entry with no list for a set is skipped for that set, which is how the return request is checked only against v2.

Include near-misses: the second and third entries both mention T-000281, but only one asks about the delivery.

Define the metric before you run anything. Selection rate is the share of first calls that name an acceptable tool and pass arguments that validate against its input model.

ch08-designing-tools/ch08/selection_check.py (excerpt)
def score_first_call(
    call: ToolCall | None, acceptable: list[str], args_models: dict[str, type[BaseModel]]
) -> bool:
    """True if the first tool call names an acceptable tool with valid arguments."""
    if call is None or call.name not in acceptable:
        return False
    try:
        args_models[call.name].model_validate(call.arguments)
    except ValidationError:
        return False
    return True

It can't see a valid argument with the wrong value. Under v1, list_shipments takes the carrier as a free string, so carrier="Swiftway" scores as a pass although the mock matches no shipments for it. Under v2 the enum rejects it. Checking values means writing expected arguments into each entry, which Chapter 13's golden tasks will do.

A first-call metric also can't show the benefit of merging, fewer tool calls. So for entries marked ticket_to_delivery, the check runs the whole loop and counts tool calls in the step log. The tool design sets a floor:

text
Fewest tool calls for "Ticket T-000281 asks where the order is. Was it late?"

v1  step 1  get_ticket(ticket_id="T-000281")        returns order O-0013833
    step 2  get_shipment(order_id="O-0013833")      returns late: true
    step 3  answer

v2  step 1  get_delivery_status(order_or_ticket_id="T-000281")
    step 2  answer

v1 needs at least two tool calls in sequence, because get_shipment needs the order id that only get_ticket returns. v2 needs one.

The default run uses a scripted fake model, so you can see the report without a key. Its choices are written by hand (the carrier="Swiftway" call is its v1 choice) and say nothing about any real model; only the tool results are real. v2 is scored on one more request, the return, so the first-call counts aren't comparable here, and the tool-call count follows from the design:

text
$ uv run python -m ch08.selection_check --fake
[fake model: scripted tool choices; tool results from Kestrel]
runs per request: 1
set  acceptable first calls  tool calls to answer
v1     5/5                     2.0
v2     6/6                     1.0

With a key, --runs 5 sends each request five times per set, with the same model and settings for both; Chapter 2, How LLMs work, just enough, explained why one run proves little. Note the date, model and number of runs with every result, and read it as one day with one model.

To learn which change helped, change one thing at a time: descriptions, then names, then the merge. The fixture's expected map takes any set name, so an intermediate set is one more build_registry function and one more key per entry. Exercise 5 uses the same mechanism for a third set.

4. Granularity: merging chatty tools, splitting overloaded ones

Tool granularity is how much one tool does. Too fine, and the model needs many tool calls for an ordinary question. Too coarse, and the choices the model should make are hidden inside one tool, and errors become hard to report.

The operations agent often gets a ticket from Maya Okafor's support team and has to check whether the order behind it is late. With v1, that is the two-call chain above. Each call is another chance to pick the wrong tool or copy an id wrongly, and each step spends run budget. The join is ordinary code, and code should do it:

ch08-designing-tools/ch08/tools.py (excerpt: the merged tool)
class GetDeliveryStatusArgs(BaseModel):
    order_or_ticket_id: str = Field(
        pattern=r"^(O-\d{7}|T-\d{6})$",
        description="The id the user gave: an order id (O-0013833) or a ticket id (T-000281).",
    )

def get_delivery_status(http: httpx.Client, args: GetDeliveryStatusArgs) -> dict[str, Any]:
    order_id, ticket_id = args.order_or_ticket_id, None
    if order_id.startswith("T-"):
        ticket_id, order_id = order_id, order_for_ticket(http, order_id)
    order = http.get(f"/orders/{order_id}")
    if order.status_code == 404:
        if ticket_id:
            raise ToolError(
                f"Ticket {ticket_id} points to order {order_id}, which the orders "
                "system doesn't have. Tell the user; retrying won't help."
            )
        raise ToolError(
            f"No order {order_id}. Order ids look like O-0013833. "
            "If the user gave a ticket id, pass that instead."
        )
    order.raise_for_status()
    o = order.json()
    result = {"order_id": order_id, "order_status": o["status"]}
    ship = http.get(f"/orders/{order_id}/shipment")
    if ship.status_code == 404:  # not shipped: the order's promised date is all there is
        return {**result, "promised_date": o["promised_date"], "shipment": None}
    ship.raise_for_status()
    s = ship.json()
    return {
        **result,
        "carrier": s["carrier"],
        "shipment_status": s["status"],
        "promised_by": s["promised_by"],
        "delivered_at": s["delivered_at"],
        "late": s["late"],
    }

The dispatcher turns a ToolError into an error result carrying its message, as in Chapter 7. order_for_ticket, in lookups.py, does the ticket look-up the same way. Keeping shipment_status matters: a lost parcel and one in transit both have a null delivered_at.

http is an httpx.Client with timeout=5.0, bound in with functools.partial. That timeout applies to each request, and this tool makes up to three. Chapter 7's loop checks the wall-clock budget before each step, so time spent inside tools counts at the next check; the timeout keeps any one request from hanging, and a timeout comes back as an error result.

Merging can go too far. Picture operations_query(action, id, filters), covering orders, shipments, tickets and policies behind an action switch. Its schema can't say which fields each action needs, so the model fills filters by guessing, and one error message has to cover every kind of mistake. Splitting it gives each action a schema that states exactly what it needs: one id for get_delivery_status, a carrier enum and page size for list_shipments, a ticket id for get_ticket, a policy name for get_policy.

Draw tool boundaries around the question the agent is asked, not around your service's endpoints.

The merged tool's two-format id isn't the same smell: a regex tells the formats apart, and both lead to the same behaviour and result shape. An action switch changes which fields matter and what comes back.

I'd draw tool boundaries around the questions the agent answers, not around your service's endpoints. A tool should do one thing you can describe in a sentence, and fail for reasons it can name. If you can't write the sentence, the tool is overloaded. If the sentence is only useful when followed by another tool's sentence, the tools are too fine.

5. Validating and limiting tool inputs

Tool input validation means checking the model's arguments against the tool's input model, in your code, before the tool function runs. If they fail, the model gets an error result that names each invalid field.

The schema tells the model what to send, but nothing makes it comply: a model can see "pattern": "^O-\\d{7}$" and still send "42". Treat tool arguments like a request body from a public client.

The Chapter 6 dispatcher already validates before it calls a tool. This chapter tightens what each input model accepts:

ch08-designing-tools/ch08/tools.py (excerpt: input models)
Carrier = Literal["Northline Freight", "Swiftway Parcel", "Harbour Express", "Tallpine Logistics"]

class ListShipmentsArgs(BaseModel):
    carrier: Carrier | None = Field(default=None, description="Only this carrier.")
    late: bool | None = Field(default=None, description="true: late shipments only.")
    limit: int = Field(default=10, ge=1, le=50, description="Shipments per page, 1 to 50.")
    cursor: str | None = Field(
        default=None, pattern=r"^\d{1,4}$", description="next_cursor from the previous page."
    )

Literal makes carriers a closed set, so "Swiftway" never reaches the API. Every filter maps to a parameter the mock's /shipments takes, and the page size and cursor are bounded. The enum has a cost: if Kestrel adds a carrier, the model's call is rejected until you update the list, and that rejection costs a step. For a set of four that changes rarely, I'd pay it.

These limits also protect the systems behind the tools: trimming a limit=100000 response afterwards still puts the full load on the backend. The run budget caps how many calls happen; input limits cap how much each call can ask for.

File paths need one more check, previewed here because the capstone's read-file tool depends on it:

ch08-designing-tools/ch08/paths.py
from pathlib import Path


def resolve_inside(folder: str | Path, relative: str) -> Path | None:
    """Return the resolved path if it stays inside folder, else None."""
    root = Path(folder).resolve()
    candidate = (root / relative).resolve()
    return candidate if candidate.is_relative_to(root) else None

resolve() follows .. and symlinks, and joining an absolute path replaces the root, so ../secrets and /etc/passwd both come back as None before any byte is read. A file could still change between the check and the read, and this is a path check, not process isolation. Chapter 14, Capstone I, will turn it into the file sandbox.

6. Error results that tell the model how to recover

Chapter 6 settled where failures go: back to the model as tool results, not up the stack, and Chapter 7 relies on that inside the loop. For client tools, Anthropic's Handle tool calls page puts the error message in the result's content and sets is_error to true. Our ToolResult carries the same flag, and the Anthropic adapter maps it onto the tool_result block.

That decides where an error goes, not what it says. Anthropic's tools article advises replacing opaque error codes and tracebacks with specific, actionable messages. Write each error result to answer three questions: what was wrong, what is valid, and what to try instead. A model that gets 404 or get_ticket failed (HTTPStatusError)., which is what the first-draft get_ticket produces for an unknown id, has to guess its next call.

ch08/registry.py holds that registry and dispatcher, moved out of tools.py (which now holds the v2 tools), with two changes. A Tool can carry per-field hints, and invalid arguments come back one line per field:

ch08-designing-tools/ch08/registry.py (excerpt: the validation message)
def _shown(value: object, limit: int = 60) -> str:
    """The value the model sent, cut short so a huge argument isn't copied back."""
    text = repr(value)
    return text if len(text) <= limit else text[:limit] + "..."

def validation_message(tool: str, exc: ValidationError, hints: dict[str, str]) -> str:
    """Change 2: one line per invalid field, with the value received and an optional hint."""
    parts = []
    for err in exc.errors(include_url=False):
        name = ".".join(str(p) for p in err["loc"]) or "input"
        if err["type"] == "missing":  # pydantic's input here is the whole dict: don't echo it
            problem = "required, not provided"
        else:
            problem = f"{err['msg']}; got {_shown(err['input'])}"
        hint = hints.get(name, "")
        parts.append(f"{name}: {problem}. {hint}".strip())
    return f"Invalid arguments for {tool}. " + " ".join(parts)

A missing field says "required, not provided" instead of echoing the whole arguments dict, and echoed values are cut to 60 characters. The rest is Chapter 7's: a timeout says to retry once, and any other exception goes to the log with its traceback while the model gets only the tool and exception type. Three cases come up with the operations tools.

A bad id. A malformed id fails validation, and the hint lists both formats. From the tour script, which calls the tools through the registry with no model:

text
$ uv run python -m ch08.tour
get_delivery_status {'order_or_ticket_id': '42'}
  ERROR: Invalid arguments for get_delivery_status. order_or_ticket_id: String should match pattern '^(O-\d{7}|T-\d{6})$'; got '42'. Use O- and 7 digits or T- and 6 digits.
get_ticket {'ticket_id': 'T-999999'}
  ERROR: No ticket T-999999. Ticket ids look like T-000281; check the id the user gave. For an order id, use get_delivery_status.

A well-formed id the mock doesn't know hits a 404, and the message names the id, the format and the alternative. If a ticket points to an order the orders system doesn't have, the message says to report it rather than retry, because no argument the model could change would help.

An empty result. A filter that matches nothing hasn't failed. list_shipments then returns empty items, is_error false, and an applied_filters field naming the filters it used. Flagging it as an error would push the model to retry, rephrase or, worst of all, invent shipments. An empty list that names its filters is a complete answer.

Input out of range. limit=500 produces "Invalid arguments for list_shipments. limit: Input should be less than or equal to 50; got 500." Pydantic's full error entries, with their type codes and documentation links, stay out of the model's input.

Failures that aren't the model's mistake, such as a refused connection, won't be fixed by better arguments; Chapter 16, Capstone III, will cover when to retry those.

7. Shaping outputs: field selection, truncation and pagination

A tool result stays in the context window for every later step, so a bloated one is paid for on each model call. Anthropic's tools article recommends pagination, range selection, filtering and truncation, with sensible defaults, for tool results that could use a lot of context. It notes that Claude Code caps tool results at 25,000 tokens by default. Our only cap is Chapter 7's as_data backstop, which cuts any result past 8,000 characters, even mid-JSON; shaping inside the tool keeps results small and whole.

Field selection is the cheapest. A Kestrel ticket carries its whole message thread, but most questions need only the subject, status, priority and order id. So get_ticket leaves the messages out unless the model asks:

ch08-designing-tools/ch08/tools.py (excerpt: get_ticket)
TICKET_FIELDS = ("ticket_id", "subject", "status", "priority", "channel", "order_id")

def get_ticket(http: httpx.Client, args: GetTicketArgs) -> dict[str, Any]:
    r = http.get(f"/tickets/{args.ticket_id}")
    if r.status_code == 404:
        raise ToolError(
            f"No ticket {args.ticket_id}. Ticket ids look like T-000281; check the "
            "id the user gave. For an order id, use get_delivery_status."
        )
    r.raise_for_status()
    t = r.json()
    result = {k: t.get(k) for k in TICKET_FIELDS}
    if args.include_messages:
        result["messages"] = t.get("messages", [])
    return result

Customer messages are outside text. Chapter 7's dispatcher already wraps every result in <data> tags with tag characters escaped, Chapter 4's rule for untrusted input. It is a delimiter, not a defence: a message written to look like instructions can still influence the model.

list_shipments keeps seven fields per row and shows how selection, filtering and pagination fit together:

ch08-designing-tools/ch08/tools.py (excerpt: list_shipments)
def list_shipments(http: httpx.Client, args: ListShipmentsArgs) -> dict[str, Any]:
    filters: dict[str, Any] = {}
    if args.carrier is not None:
        filters["carrier"] = args.carrier
    if args.late is not None:
        filters["late"] = str(args.late).lower()
    r = http.get("/shipments", params={**filters, "limit": FETCH_CAP})
    r.raise_for_status()
    rows = [{k: s.get(k) for k in SHIPMENT_FIELDS} for s in r.json()]
    page = paginate(rows, args.cursor, args.limit, FETCH_CAP)
    return {**page, "applied_filters": filters}

Truncation is for long text that can't be trimmed field by field, such as a policy. Cap it, and say in the result that you did:

ch08-designing-tools/ch08/shaping.py (excerpt: truncate)
def truncate(text: str, max_chars: int, offset: int, tool: str) -> str:
    """Return text[offset:offset+max_chars], with a marker if anything is left."""
    if offset >= len(text) > 0:
        return f"[offset {offset} is past the end; the text has {len(text):,} characters]"
    chunk = text[offset : offset + max_chars]
    shown_end = offset + len(chunk)
    remaining = len(text) - shown_end
    if remaining <= 0:
        return chunk
    return (
        f"{chunk}\n[truncated: {remaining:,} of {len(text):,} characters not shown; "
        f"call {tool} with offset={shown_end} to continue]"
    )

get_policy truncates at 2,000 characters. The marker works only because GetPolicyArgs has an offset field: a marker must never point at a parameter the tool doesn't accept. Without a marker, a truncated policy looks complete, and the model answers from the first half. Kestrel's policies are short today, so the test uses a long one. Characters are a cheap stand-in for tokens; Chapter 2's token estimator gives a closer estimate.

Pagination handles lists. The mock's /shipments takes carrier, late and limit, but no offset or cursor. The mock also caps limit at 500 rows. So list_shipments fetches up to that cap and pages through the list locally:

ch08-designing-tools/ch08/shaping.py (excerpt: paginate)
def paginate(rows: list[dict], cursor: str | None, limit: int, cap: int) -> dict:
    """Slice an already-fetched list. The cursor is an offset into it."""
    start = int(cursor) if cursor else 0
    page = rows[start : start + limit]
    end = start + len(page)
    return {
        "items": page,
        "next_cursor": str(end) if end < len(rows) else None,
        "total": len(rows),
        "total_is_capped": len(rows) >= cap,
    }

Asked for two late Swiftway Parcel shipments, it returns two rows, "next_cursor": "2" and "total": 397. The costs: every page fetches the whole list again, total means "matching rows up to the cap" (hence total_is_capped), and if shipments change between pages, rows can be skipped or repeated. Against a real backend, I'd push for a server-side cursor rather than a bigger cap.

The model usually takes the default, so make it the small, common case: no message thread, a short page, capped text. Chapter 9 will widen the view from one tool result to everything that goes into the window on each call.

8. Side effects and an idempotent return authorisation

Read tools must have no side effects: no row written, no email sent, no ticket marked as seen. Then a confused model that fetches an order three times only wastes steps. A test holds the v2 read tools to this.

Writes can run more than once without anyone intending it: the model repeats a call after an ambiguous result, emits two identical calls in one response (Chapter 6's parallel tool calls), or the user asks again. A naive create_return_authorisation would give the customer two returns for one parcel.

An idempotency key is a value that identifies one intended operation, so a repeat can be recognised. A tool is idempotent when repeating the same call, with the same idempotency key, has the same effect as making it once. The key can come from the caller, from the application that starts the run, or from the program, derived from a normalised payload. If the model supplies it, a new suffix on a retry lets the duplicate through without any error. That asks the model to respect a rule instead of enforcing it.

The trade-off: two genuinely separate, identical returns for the same ticket collapse into one. I'd rather a person handles that rare case than clean up duplicates. Where repeats are normal, such as adding a note, the application could issue the key instead.

ch08-designing-tools/ch08/returns.py (excerpt: the write tool)
class ReturnLine(BaseModel):
    sku: str = Field(pattern=r"^SKU-\d{5}$", description="Product SKU, e.g. SKU-00042.")
    quantity: int = Field(ge=1, le=100)

class CreateReturnArgs(BaseModel):
    ticket_id: str = Field(pattern=r"^T-\d{6}$", description="The ticket asking for the return.")
    lines: list[ReturnLine] = Field(min_length=1, max_length=20)
    reason: str = Field(min_length=3, max_length=500, description="The customer's reason.")

def derive_key(args: CreateReturnArgs) -> str:
    totals: dict[str, int] = {}
    for line in args.lines:  # one line of 2 and two lines of 1 are the same return
        totals[line.sku] = totals.get(line.sku, 0) + line.quantity
    normalised = json.dumps({"ticket": args.ticket_id, "lines": sorted(totals.items())})
    return hashlib.sha256(normalised.encode()).hexdigest()

def create_return_authorisation(
    store: ReturnStore, http: httpx.Client, today: date, args: CreateReturnArgs
) -> dict[str, Any]:
    key = derive_key(args)
    if existing := store.find(key):  # a repeat gets what was created, even if the world moved on
        return {**existing, "already_existed": True}
    order_id = check_return(http, args.ticket_id, today)  # raises ToolError if not allowed
    created, row = store.insert_pending(key, order_id, args.model_dump_json())
    return {**row, "already_existed": not created}

check_return, in the same file, finds the ticket's order, requires it to be delivered, and checks the delivery date against the return window. The window comes from policy text: the mock's returns policy gives consumers 30 days and trade customers 14 "unless their contract says otherwise". So the extraction refuses to guess:

ch08-designing-tools/ch08/returns.py (excerpt: business rules)
CONSUMER_WINDOW = re.compile(r"consumers\b[^.;]*?within\s+(\d{1,3})\s+days", re.IGNORECASE)

def return_window_days(policy_text: str, channel: str) -> int | None:
    """The store-channel window in days if the policy states exactly one, else None."""
    if channel != "store":  # trade windows can change by contract, which the tool can't see
        return None
    found = {int(n) for n in CONSUMER_WINDOW.findall(policy_text)}
    return found.pop() if len(found) == 1 else None

The tool fails closed, meaning that when it can't confirm a rule it refuses: a trade order, a policy without a single consumer window, or a missing delivery date returns an error result instead of an authorisation. That costs a manual review now and then; failing open would authorise returns against a window nobody confirmed. today is a parameter, not the system clock, because the seeded orders are from 2025. The tests and the tour pass 2025-12-16, the date Chapter 1's examples use. The tour against the seeded data (the RA- id is random):

text
create_return_authorisation {'ticket_id': 'T-000410', 'reason': "Doesn't fit.", 'lines': [{'sku': 'SKU-00042', 'quantity': 2}]}
  ok: <data>{"ra_id": "RA-A7F28A6A", "order_id": "O-0013196", "status": "pending", "already_existed": false}</data>
create_return_authorisation {'ticket_id': 'T-000410', 'reason': "Doesn't fit.", 'lines': [{'sku': 'SKU-00042', 'quantity': 1}, {'sku': 'SKU-00042', 'quantity': 1}]}
  ok: <data>{"ra_id": "RA-A7F28A6A", "order_id": "O-0013196", "status": "pending", "already_existed": true}</data>
create_return_authorisation {'ticket_id': 'T-000122', 'lines': [{'sku': 'SKU-00007', 'quantity': 1}], 'reason': 'Changed my mind.'}
  ERROR: Order O-0015215's 30-day return window closed on 2025-12-13.
create_return_authorisation {'ticket_id': 'T-000458', 'lines': [{'sku': 'SKU-00105', 'quantity': 1}], 'reason': 'No longer needed.'}
  ERROR: The return window for order O-0007124 can't be confirmed from the order and the returns policy. Don't retry; tell the user a person will review the return.

The second call splits the same two units across two lines and gets the same authorisation back.

The tool can't check the lines: the mock's order record has none, so the person who approves the authorisation checks them. Idempotency stops a second call from adding to the first. It does nothing about a wrong first call: an idempotent tool that authorises the wrong SKU does so exactly once. Business rules and human approval guard the first call.

The key look-up comes before the checks on purpose. A repeat, whether the model retrying or the user asking again a week later, must get the authorisation that already exists. If the checks ran first, a repeat after the window closed would come back as an error, and the model would tell the customer no return is possible when one exists.

A repeat finds its key before any check runs, so it gets the stored authorisation and never a second one.

Chapter 7's loop runs one response's tool calls one after another, but a loop that ran them in threads, or two runs for the same ticket, could let two identical calls both find nothing and both pass the checks. The store settles it with a primary key on the idempotency key and INSERT … ON CONFLICT(idempotency_key) DO NOTHING, so one insert wins and the other call reads the winner's row with already_existed=true. return_store.py opens a connection per call, so it works from any thread. A production store would also need a retention period for keys.

Adding a write widens the agent's reach, what it can touch through its tools: it can now change the return store as well as read the mock. On the autonomy spectrum it stays at point 4, an agent with narrow tools and a tight budget, on purpose: cost stays inside the same run budget, the risk is one pending request a person must approve, and the derived key makes repeats predictable. The capstone's tools will be read-only, and Chapter 14 will say why.

9. Assembling ch08-designing-tools and verifying each rule

text
ch08-designing-tools/
├── ch08/
│   ├── agent.py, budget.py       # Chapter 7, copied (agent.py imports registry.py)
│   ├── model_client.py, anthropic_adapter.py, fake_model.py, settings.py, prompts.py
│   │                             # Chapter 7, copied unchanged
│   ├── registry.py               # Chapter 7's registry and dispatcher, two changes
│   ├── tools_v1.py               # the "before" set
│   ├── tools.py                  # v2 read tools, input models, descriptions, build_registry
│   ├── returns.py, return_store.py
│   ├── lookups.py, shaping.py, paths.py
│   ├── selection_check.py, selection_fixture.jsonl, scripted.py
│   ├── tour.py
│   └── prompts/ops_agent_v2.md
├── tests/
├── conftest.py
└── README.md

build_registry(http, store, today) in tools.py binds each tool's dependencies with functools.partial. The caller passes it to run_agent in place of Chapter 7's registry; the loop, run budget and step log don't change. The prompt moves to ops_agent_v2.md: the same six sections, a task that covers tickets, policies and returns, and no tool names, because the definitions carry them.

The tests use the seeded mock API, httpx MockTransport for cases the data doesn't contain, and the fake model:

  • Selection and granularity: right, wrong-tool and invalid-argument calls are scored correctly; T-000281 leads to ticket, order and shipment requests in that order.
  • Validation, errors, shaping: limit=500 is rejected before any request; path escapes are rejected; unknown ids, empty lists, truncation markers and cursors behave as described.
  • No side effects: every read tool runs behind a handler that fails on anything but GET, and the store's row count doesn't change.
  • Idempotency and rules: repeats (reordered, split, after the window closed, four concurrent calls) leave one row; each refusal writes nothing.
bash
cd books-code/agentic-ai-foundations/ch08-designing-tools && uv run pytest -q

The run reports 39 passed, 1 deselected; the deselected test is the live selection check, which needs your provider's key (uv run --env-file .env pytest -q -m live).

10. The rules the capstone's tools will follow

Chapters 14 and 15 will give Sam Adeyemi's research assistant four read-only tools: web search, read file, count rows and calculator. Chapter 14 will name and specify them; here are the design rules.

Web search. The description says when to search the web and when to read a local file instead. The input model bounds query length and result count. Each result is shaped to title, URL and snippet; the URL becomes a citation later.

Read file. A path relative to one allowed folder, checked with resolve_inside before any read. Long output is truncated with a marker that names an offset parameter the tool really accepts.

Calculator. Evaluate arithmetic without Python's eval and without any shell. One approach is to parse the expression with the ast module, allow only number and arithmetic-operator nodes, and cap exponents, since 9**9**9 would pin the process. Division by zero comes back as an error result that names the problem.

All three are read-only, so none needs an idempotency key.

11. Exercises

Work in ch08-designing-tools/ and keep the default tests passing.

  1. Add get_stock_levels for GET /stock/{sku} (SKUs like SKU-00042) and three stock requests with only a v2 list. Verify: a fake-model test scores a scripted get_stock_levels call as correct. Hint: copy get_ticket's 404 handling.

  2. Add list_tickets for GET /tickets?status=&limit=, with status an enum of open, pending and solved, a bounded limit, and no messages in the rows. Verify: the seeded API returns only open tickets, and status="closed" is rejected before any request.

  3. Page get_ticket messages. Add message_offset: int = Field(default=0, ge=0), return at most five messages per call, and add a marker such as [more messages: call get_ticket with message_offset=5] when more remain. Verify: a MockTransport test with a 12-message thread follows the markers to the last page.

  4. Send the same return twice, reordered and with one SKU split into two lines. Verify: same ra_id, already_existed=true, one row.

  5. Build the overloaded tool, operations_query(action, id, filters), as a third set with an overloaded list in the fixture, and script fake first calls for it. Verify: a call with the wrong action scores as incorrect. Common mistake: one error message for every action.

12. Summary and what comes next

The model chooses tools from text alone, so names, descriptions and schemas are the whole interface it sees. A rewrite is a hypothesis that the selection check tests, one change at a time, though it can't see wrong values that still validate. Tool boundaries follow the agent's questions. Arguments are validated in code; error results say what was wrong and what to do instead; results stay small through field selection, marked truncation and pagination. Read tools have no side effects. The write tool looks up its derived key first, checks business rules only for a new request, fails closed, and writes only a pending request.

Chapter 9 picks up where output shaping stops. A tool result is only one thing competing for the window. The next questions are what else goes in on each call, in what order, and at what size.

Bishal SahaLet's build together

Have a system to design, or an AI feature to get right?

Tell me about the problem. You'll get a clear, honest view of the best way forward.

  • Reply within 24 hoursOn business days, with my honest view and a next step.
  • Accepting select engagementsArchitecture, AI features and full builds.
  • Remote, worldwideWorking with startups, SMEs and enterprises.