CONTENTS
CHAPTER 6

Structured outputs and tools

6 MIN READ

So far the model has produced text for a human to read. The moment its output feeds into code (a parser, a database, an API call) the requirements change. Code doesn't forgive a missing bracket or a field named userId instead of user_id. This chapter covers the bridge between model and code: structured outputs and tools. They're the same idea from two angles.

From text to data

The naive approach is to ask nicely: "respond in JSON with fields name and email." It works most of the time, and "most of the time" is the problem (remember Chapter 1's compounding errors).

There are three levels of rigor:

  1. Prompted format. Ask for a format and parse it. Cheap, works on any model, fails occasionally.
  2. Validate and retry. Parse the output against a schema; on failure, send the error back to the model and ask again. Jason Liu's Instructor library popularized this pattern for Python: define a Pydantic model, and the library validates the response and re-asks on failure. Validation can include business rules, not just types ("end date must be after start date").
  3. Constrained decoding. The server restricts which tokens the model is allowed to generate at each step so the output cannot violate the schema. OpenAI's Structured Outputs (August 2024) works this way; they reported their model scoring 100% on their complex schema-following eval with it, versus under 40% for an older model without. Other providers offer similar features.

Constrained decoding guarantees shape, not truth. The JSON will parse; the email address in it may still be invented. You still need validation for meaning.

Common confusion: "Structured outputs make the model worse at reasoning." Forcing the answer into a rigid format immediately can hurt on hard problems, because the model loses room to think. The fix is to give it room: include a reasoning field before the answer fields, or let it reason first and extract the structure in a second step.

Concept deep dive: tools are just structured outputs

Dex Horthy's "12-Factor Agents" states this as Factor 4: "Tools are just structured outputs." It's worth internalizing because it demystifies everything that follows.

When a model "calls a tool", nothing magical happens. The model emits a structured message that says, in effect, {"tool": "get_weather", "args": {"city": "Lisbon"}}. Your code reads that, decides whether to run it, runs it, and puts the result back in the context. The model never touches your systems directly.

 your code                         model
    │  context + tool definitions    │
    ├───────────────────────────────►│
    │                                │  decides: call get_weather(city="Lisbon")
    │◄───────────────────────────────┤
    │  validate, authorize, execute  │
    │  append result to context      │
    ├───────────────────────────────►│
    │                                │  writes the answer using the result
    │◄───────────────────────────────┤

Three consequences:

  • You own execution. Every tool call passes through code you control, which is where validation, permissions, rate limits and human approval live. That's the most important security boundary in your system (Chapter 11).
  • A tool call is a decision, not an action. You can log it, dry-run it, ask a human about it, or refuse it.
  • Tool definitions are prompts. The model chooses tools by reading their names, descriptions and parameter schemas. Writing them is prompt engineering.

Designing tools: the agent-computer interface

Anthropic's "Building effective agents" introduced the term agent-computer interface (ACI) and argued it deserves as much design effort as a human-computer interface. Their anecdote: while building a coding agent for the SWE-bench benchmark, the model kept making mistakes with relative file paths after it had moved out of the root directory. They changed the tool to require absolute paths, and the model "used this method flawlessly." The model wasn't the problem; the interface was.

Their follow-up, "Writing effective tools for agents" (September 2025), is the best guide to the craft. Its main lessons:

Build tools for tasks, not endpoints. Don't wrap every API call. A list_contacts tool that returns 10,000 records forces the model to read them all; a search_contacts tool lets it find one. A schedule_event tool that checks availability and books in one call beats three tools the model must chain correctly.

Namespace related tools. With many tools, names like asana_search and jira_search help the model pick. They noted that even prefix versus suffix naming measurably changed results, so test.

Return meaningful context. Return names, not opaque IDs. Return what the model needs for its next decision. Offer a response_format option (concise or detailed); in their Slack example, the concise format used about a third of the tokens.

Be token-efficient. Paginate, filter and truncate by default. Claude Code caps tool responses at 25,000 tokens by default. When you truncate, say so, and say how to get more.

Write errors that teach. "Invalid date" is useless. "Date must be ISO 8601, e.g. 2026-11-17; you sent 17/11/2026" lets the model fix itself.

Use unambiguous parameters. user_id, not user. Describe units, formats and limits.

Evaluate tools like code. Build realistic multi-step tasks with verifiable outcomes, run agents on them, and read the transcripts. Track accuracy, tool calls per task, tokens and errors. They reported that having Claude itself rewrite tool descriptions, based on failed transcripts, cut task completion time by 40% in one case.

Here's a before and after:

{
  "name": "get_data",
  "description": "Gets data",
  "input_schema": {
    "type": "object",
    "properties": { "id": { "type": "string" } }
  }
}
{
  "name": "orders_search",
  "description": "Search a customer's orders. Use this before any refund or shipping question to find the order the customer means. Returns at most 10 orders, newest first, with status and items.",
  "input_schema": {
    "type": "object",
    "properties": {
      "customer_id": { "type": "string", "description": "The customer's ID, e.g. cus_8Hq2. Taken from the session, never from the message text." },
      "query": { "type": "string", "description": "Optional words to match against item names or order numbers." },
      "status": { "type": "string", "enum": ["any", "processing", "shipped", "delivered", "returned"] }
    },
    "required": ["customer_id"]
  }
}

The second tells the model when to use it, what it returns, and how to fill each argument. The note on customer_id hints at something better still: don't let the model supply it at all. Inject it from the authenticated session in your code. Anything the model doesn't need to decide, it shouldn't.

How many tools?

Every tool definition costs context and adds a chance of confusion (Breunig's context confusion). Practical guidance:

  • Prefer a small set of well-designed tools over a large set of thin ones.
  • If you have many, expose only the ones relevant to the current step or mode, or use a two-level design where the model first searches a tool catalogue.
  • Remember the caching cost of changing the tool list mid-session (Chapter 4).

The Model Context Protocol

Anthropic released the Model Context Protocol (MCP) in November 2024 as an open standard for connecting models to tools and data. Before MCP, every app wrote its own integration for every service. MCP defines one protocol (JSON-RPC 2.0, inspired by the Language Server Protocol that editors use) so that any MCP client (an app like an IDE or chat assistant) can use any MCP server (a wrapper around a service).

Servers can offer three kinds of things:

  • Tools: functions the model can call.
  • Resources: data the app can read into context.
  • Prompts: reusable templated messages or workflows.

Adoption was fast. In December 2025 the Linux Foundation formed the Agentic AI Foundation, with MCP as a founding project alongside Block's goose and OpenAI's AGENTS.md, and the announcement cited more than 10,000 published MCP servers.

For system design, think of MCP as a distribution format, not an architecture. It's how you make your service usable from many AI apps, or how your app gains many integrations cheaply. It doesn't change the rules in this chapter. A badly designed tool is still badly designed when served over MCP. And because MCP makes it trivial to plug third-party tools into an agent, it also makes it trivial to create the dangerous combinations Chapter 11 warns about. The MCP specification itself says hosts must get user consent before invoking tools and should treat tool descriptions from untrusted servers as untrusted.

Key takeaways

  • Model output that feeds code needs a schema. Use validation with retries, and constrained decoding where available. Shape isn't truth: still validate meaning.
  • Tools are structured outputs. The model proposes; your code validates, authorizes and executes.
  • Design the agent-computer interface: task-level tools, clear names, meaningful and compact results, teaching errors, unambiguous parameters.
  • Inject anything the model doesn't need to decide (user IDs, tenant IDs) from code.
  • MCP standardizes how tools are distributed; it doesn't make tool design or security easier.

Exercises

  1. Take three endpoints from an API you know and design agent tools for them. Merge or split them as needed. Write full descriptions.
  2. Write a validation function for a "book meeting" tool call that catches at least four kinds of bad arguments, each with an error message that tells the model how to fix it.
  3. List every value in your tool schemas that the model currently chooses. Which could your code supply instead?