Skip to content
Blog

Agents need contracts: three things to write down before the first tool call

Tool schemas, structured outputs with a refusal path, and a trace for every step. The boring paperwork that makes a multi-agent system debuggable once it runs thousands of times a day.

Mohamad Al Assaad6 min read

A demo agent is a loop: prompt, tool call, observation, repeat until the model says it is done. It works in the meeting because the meeting has one question and one person watching. In production the loop runs thousands of times a day, across tools nobody fully documented, and the question “why did it do that” arrives on a Friday with no trace to read.

The fix is rarely a smarter model. It is contracts: the agreements between the model, its tools, and the people who have to operate the system. Three of them are worth writing down before the first tool call.

1. A tool is an API. Write the schema first.

Every tool an agent can call is an API that a language model will use under pressure, with partial information, in ways you did not plan. Treat it like an API you would expose to a third party:

  • Typed input and output. A JSON schema for both, with descriptions written for the model, not for the engineer. “The customer’s identifier as shown on the invoice” beats “id”. Anthropic’s tool documentation calls detailed descriptions “by far the most important factor in tool performance”, and its guide to writing tools makes the same point about unambiguous parameter names such as user_id.
  • Idempotency. The model will retry. A retry of create_ticket must not create two tickets.
  • Timeouts and typed errors. A tool that hangs stalls the whole run. A tool that returns null on failure teaches the model to hallucinate the missing value. Return an error the model can act on.
  • Permissions. What the tool is allowed to touch, stated once, enforced outside the model.

The Model Context Protocol makes much of this explicit. In the current spec (revision 2026-07-28, as of October 2026), a server publishes each tool with an inputSchema, an optional outputSchema, and optional annotations such as readOnlyHint and idempotentHint. Errors the model can fix come back as a result with isError: true. The spec says clients must treat annotations as untrusted unless the server is trusted: a hint documents the contract, it does not enforce it. The same revision dropped protocol sessions, so state across calls travels as an explicit handle in the arguments, one more thing for the schema. Without MCP, write the same contract by hand.

from pydantic import BaseModel, Field

class SearchContractsInput(BaseModel):
    query: str = Field(description="Free-text question about a contract clause or amount.")
    customer_id: str | None = Field(default=None, description="Customer identifier as printed on the invoice.")
    limit: int = Field(default=5, ge=1, le=20)

class Passage(BaseModel):
    chunk_id: str
    document: str
    page: int
    text: str

class SearchContractsOutput(BaseModel):
    passages: list[Passage]
    truncated: bool = Field(description="True when more results existed than `limit`.")

@tool(idempotent=True, timeout_s=8)
def search_contracts(params: SearchContractsInput) -> SearchContractsOutput:
    ...

The decorator is pseudo-code, the discipline is not: the schema exists before the function body, and the error cases are part of the output type. SearchContractsInput.model_json_schema() gives you the inputSchema to publish.

2. Structured outputs and the refusal path

The final answer is also a contract. Free text is fine for a chatbot and useless for anything that feeds another system or has to be audited. The answer should be an object:

class AgentResult(BaseModel):
    # generated by the model
    answer: str
    citations: list[str]            # chunk ids the answer is grounded in
    confidence: float               # the model's own estimate, used for routing, never shown as a percentage
    insufficient_context: bool      # True when the agent could not find what it needed
    missing: str | None             # what would have been needed; null otherwise
    # filled in by the orchestrator, never by the model
    steps: int = 0
    cost_usd: float = 0.0

The major APIs can now enforce the shape: OpenAI’s Responses API with text.format of type json_schema and strict: true (guide), Anthropic’s Messages API with output_config.format (docs), and both with strict: true on tool definitions. OpenAI requires every field to be listed as required, so an optional field is a union with null; that is why missing has no default. Send only the model-generated fields as the schema and let the orchestrator fill in the rest. Constrained decoding guarantees the shape, not the content.

Two fields matter more than the rest.

insufficient_context is the refusal path. When retrieval returns nothing relevant, the contract says: say so, name what is missing, stop. Without an explicit refusal field the model improvises, because improvising is what it was trained to do. With it, the empty case becomes a normal, testable outcome instead of a hallucination. Keep it separate from the provider’s safety refusal, which arrives outside your schema (a refusal item at OpenAI, stop_reason: "refusal" at Anthropic) and needs its own branch, as does a response cut off at the token limit.

steps and cost_usd enforce the budget. Every run gets a ceiling: maximum steps, maximum tool calls, maximum tokens, maximum spend. When the ceiling is hit the agent returns a partial result with the reason, not an exception at step forty. A budget is the difference between a bad answer that costs two cents and a bad answer that costs twenty dollars.

3. Trace every step

An agent run is a tree: the user’s request, the steps the orchestrator took, the tools each step called, the sub-agents it delegated to, their steps. If you cannot see that tree afterwards, you cannot debug, you cannot evaluate, and you cannot explain a decision to the person it affected.

Record a span for every step, with a parent so the tree can be rebuilt:

from dataclasses import dataclass, asdict
import time, uuid

@dataclass
class Step:
    run_id: str
    span_id: str
    parent_id: str | None
    agent: str                      # "orchestrator" | "contracts-reader" | ...
    kind: str                       # "llm" | "tool" | "handoff"
    name: str                       # model name or tool name
    input_summary: str              # truncated, no secrets
    output_summary: str
    tokens_in: int
    tokens_out: int
    latency_ms: int
    cost_usd: float
    error: str | None = None

def emit(step: Step) -> None:
    tracer.write(asdict(step))      # OpenTelemetry, a table, a file: anything you can query

span = Step(run_id, uuid.uuid4().hex, parent_id, "contracts-reader", "tool", "search_contracts",
            input_summary=str(params)[:300], output_summary="", tokens_in=0, tokens_out=0, latency_ms=0, cost_usd=0)
t0 = time.perf_counter()
try:
    result = search_contracts(params)
    span.output_summary = f"{len(result.passages)} passages, truncated={result.truncated}"
except ToolError as e:
    span.error = str(e)
    raise
finally:
    span.latency_ms = int((time.perf_counter() - t0) * 1000)
    emit(span)

If you export to OpenTelemetry, borrow the names from its GenAI agent span conventions: invoke_agent and execute_tool as operations, gen_ai.usage.input_tokens and gen_ai.usage.output_tokens as attributes. As of October 2026 they are marked as in development, so pin the version you follow.

With the tree stored, two habits pay for the whole effort:

  • Dashboards on the fields that cost money and time: steps per run, cost per run, latency per tool, error rate per tool. A tool whose error rate doubles after a deploy is visible within the hour.
  • The weekly worst-answers review. Take the ten runs with the lowest judge score or the worst user feedback and read their traces end to end. Dashboards show that something is wrong; reading traces is how you find out what.

Multi-agent is the same contract, applied twice

When one agent delegates to another, the sub-agent is a tool. It gets a typed input, returns a typed output, has a budget, and emits spans under the parent’s span. Free-text handoffs (“here is what I found, take it from here”) are where multi-agent systems lose information and gain latency. Typed handoffs are boring and they are the only ones that survive.

What this looks like in practice

  1. A schema for every tool, with descriptions written for the model, idempotency and timeouts stated.
  2. A typed final answer with an explicit refusal field, enforced by the API’s structured output mode, and a budget that stops the run cleanly.
  3. A span for every step, a tree for every run, a weekly look at the worst ten.
  4. Sub-agents treated as tools, with the same three contracts.

None of this makes the model smarter. It makes the system something you can run.

Sources