Skip to main content

AI Agent Tool Output Design: How to Return Results Your Agent Can Act On

Silent truncation, ambiguous empty lists, opaque IDs and dead-end errors. Why correct tool data still produces wrong agent decisions, and the five-clause contract that fixes it.

Updated 12 min readMarkdown
Part of seriesBuilding with AI
AI Agent Tool Output Design: How to Return Results Your Agent Can Act On
[]

That's the most dangerous thing a tool can hand an AI agent.

To you, an empty list is obviously ambiguous. Maybe nothing matched. Maybe the filter was wrong. Maybe the service account can't read that table, or the call timed out and a wrapper caught the exception. To the agent, it reads as a fact: there is nothing here. So it tells the user they have no open invoices, calmly and politely, whether or not that's true.

Nothing crashed. No error was logged. The tool returned "correct" data. And the agent was wrong.

This post is about the half of tool design most teams skip. Everyone works on the input side: tool names, schemas, descriptions. Very few people design the output, the text your function hands back. That text is what the agent decides from.

A tool result is a prompt

From the model's side, there is no difference between your system prompt and a tool result. Both are text in the context window. Both shape the next action.

The difference is authorship. The system prompt was written, reviewed and argued over. The tool result was written by json.dumps.

Agent loop: the model decides, the tool runs, the result is written back, the model re-reads everything and decides again. The result step is highlighted as the part nobody reviews.

Three properties of the agent loop make this matter more than it would for a human reader:

  • The agent can't see your system. It can't open the database or the dashboard. The result is its only view of what happened, so think of the tool as an instrument panel and the agent as a pilot flying through cloud.
  • The model re-reads everything, every turn. Old tool results don't scroll away; they're part of the prompt on every later call (why prompt caching makes this expensive).
  • Longer input is less reliable input. Chroma's 2025 Context Rot report tested 18 models and found performance becomes increasingly unreliable as input length grows, even on simple tasks.

If you want the full mechanics of the loop first, start with How AI Learned to Actually Do Things: Tool Calling and MCP Explained.

Five tool output failure patterns

In all five, the underlying data is accurate.

Pattern What the tool returns What the agent does
Flood Every field, every row Misses the one line that answers the question
Silent cut A list truncated with no notice Treats a partial list as complete
Ambiguous empty [] Reports "none" when it may mean "couldn't look"
Codes, not names ST_7, UUIDs, numeric tiers Guesses the meaning, fluently
Dead-end error 400 Bad Request Retries blind, or changes the wrong argument

A few of these have real numbers behind them.

Silent cuts cause wrong answers. In a write-up on CRMArena, a Salesforce benchmark of CRM tasks, researcher Xinyang Song triaged failed agent runs and found 9 of 15 failures came from tool output truncation. One query returned 198 cases as JSON, overflowed the limit, and the agent computed its answer from the partial list. After making the output more compact (field names declared once, shorter timestamps, shared ID prefixes), tokens per record dropped about 2.9x and success rose from 85.3% to 94.0%, averaged over three trials.

Floods are mostly unused. A November 2026 paper on agent harness costs found that agents later referred to only 27% of tool-output tokens on average, and 36% of tool outputs were never used at all, while the harness kept everything in context until the run ended.

Codes become hallucinations. Anthropic's September 2025 guide on writing tools for agents reports that resolving arbitrary alphanumeric UUIDs into more meaningful language significantly improves Claude's retrieval precision by reducing hallucinations.

Raw result vs designed result: status codes, silent truncation, bare empty list, UUIDs and a vague 400 on the left; a plain outcome sentence, announced truncation, an explained empty, resolved names and a corrective error on the right.

It's not about token count

The usual advice is "keep tool outputs small." That's not wrong, but it points at the wrong cost.

The TurnCost study (October 2026) analyzed 600 public coding-agent trajectories. The median tool observation was only 118 to 286 tokens. Turn count explained 84% of the variance in log trajectory cost; mean observation size explained 4%.

So the expensive thing is extra turns, and bad results are what create them: a vague error triggers a blind retry, a silent cut sends the agent back for data it didn't know it was missing, an ambiguous empty causes exploratory searches. When there's no extra turn, you get the worse outcome: a confident wrong answer.

The same study shows what a well-written result buys. When a tool truncated its output with guidance, 76.9% of the agent's next actions narrowed the query. After a bare truncation, 44.0% did.

The cost of a bad tool result isn't its tokens. It's the turn it causes, or the wrong answer when there's no next turn.

The Return Contract

Five clauses. Each one closes one of the failure patterns above.

The Return Contract: outcome first; bounded, and the cut announced; names over codes; empty with a reason; errors that point forward.

  1. Outcome first. One plain sentence on what happened, before any data.
  2. Bounded, and the cut announced. Cap the size; say how much was cut and how to get the rest.
  3. Names over codes. Resolve IDs and codes into words; keep a raw ID only if the next call needs it.
  4. Empty with a reason. Say what was searched, with which filters, and whether "empty" means none exist or couldn't look.
  5. Errors that point forward. What was wrong, what valid input looks like, an example, and whether retrying helps.

Implementing it in Python

A small result type keeps the contract in one place:

from dataclasses import dataclass, field

@dataclass
class ToolResult:
    outcome: str                      # clause 1: one sentence, always present
    rows: list[str] = field(default_factory=list)
    total: int | None = None          # clause 2: how many exist
    next_hint: str | None = None      # clause 2: how to get the rest
    handles: dict[str, str] = field(default_factory=dict)  # IDs the next call needs

    def render(self, limit: int = 20) -> str:
        lines = [self.outcome]
        shown = self.rows[:limit]
        if self.total is not None and self.total > len(shown):
            lines.append(
                f"Showing {len(shown)} of {self.total}. "
                + (self.next_hint or "Use a narrower filter to see more.")
            )
        lines += shown
        if self.handles:
            lines.append("IDs for follow-up calls (do not show to the user): "
                         + ", ".join(f"{k}={v}" for k, v in self.handles.items()))
        return "\n".join(lines)

Clause 3 lives in the code that builds rows: translate ST_7 to "shipped" and a customer UUID to "Acme Ltd" there, once.

Clause 4 is structural. Errors must never reach the "empty" path:

def search_invoices(customer_id: str, status: list[str], month: str) -> str:
    try:
        rows = billing.search(customer_id, status, month)
    except PermissionError:
        return ("Could not search invoices: this service account has no access "
                "to the billing schema. This is NOT an empty result. "
                "Tell the user you can't check invoices right now.")
    except TimeoutError:
        return ("Invoice search timed out after 10s. Nothing was checked. "
                "Retrying once with a single month usually works.")

    customer = customers.name(customer_id)
    if not rows:
        return (f"No invoices for {customer} in {month} "
                f"(statuses searched: {', '.join(status)}). Confirmed empty.")
    return ToolResult(
        outcome=f"Found {len(rows)} invoices for {customer} in {month}.",
        rows=[f"#{r.number}: {r.amount} {r.currency}, {r.status_label}" for r in rows],
        total=len(rows),
    ).render()

Clause 5, an error written as an instruction:

Error: invalid date "12/03/2026" for field "since".
Expected format: YYYY-MM-DD (example: 2026-12-03).
"12/03" is ambiguous: it could mean 3 December or 12 March. Ask the user if unsure.
Retrying with the same value will fail.

For logs and command output, truncate from the tail, not the head. Builds and test runners print the failure last:

def tail(text: str, max_chars: int = 4000) -> str:
    if len(text) <= max_chars:
        return text
    cut = len(text) - max_chars
    return (f"[First {cut} characters omitted. Showing the last {max_chars}. "
            f"Use read_log(offset=...) for earlier output.]\n" + text[-max_chars:])

Trade-offs worth knowing

  • Names vs IDs. Agents still need IDs to chain calls (search_user then send_message(id=...)). Keep them, but label them as handles so they don't leak into user-facing answers.
  • Concise vs detailed. If one tool serves both quick lookups and deep work, add a response_format parameter. In Anthropic's Slack example, the detailed response was 206 tokens and the concise one 72.
  • Caps. Anthropic notes Claude Code restricts tool responses to 25,000 tokens by default. That's a ceiling for a coding harness, not a target for a list endpoint.
  • Summarizing with a second model. Tempting, but summaries keep the typical and drop the exception, and in tool output the exception is often the answer (the Exception Pass). Reduce with code you can test.
  • Untrusted text. Fence content from web pages, tickets and emails and label it as data. It reduces confusion. It does not solve prompt injection.

How to test tool outputs

The Cold Read Test. Pull one real, messy result from your logs (a long list, an empty, an error). Give it to a colleague who doesn't know the system, with only the user's original request. Ask: "What would you do next, and how sure are you?" Every question they ask maps to a missing clause.

Unit tests for the contract. Assert the properties, not the exact wording:

def test_truncation_is_announced():
    out = ToolResult(outcome="Found 198 cases.", rows=[f"case {i}" for i in range(198)],
                     total=198).render(limit=20)
    assert "Showing 20 of 198" in out

def test_permission_error_is_not_empty(monkeypatch):
    def denied(*args):
        raise PermissionError("no access to billing schema")
    monkeypatch.setattr(billing, "search", denied)
    out = search_invoices("c_12", ["open"], "2026-11")
    assert "NOT an empty result" in out

Trace metrics, per tool: p95 result size in tokens, truncation rate, the share of calls that follow an error and retry the same tool, and the empty-result rate. Fix the worst tool first.

Key Takeaways

  • A tool result is a prompt. The agent decides its next action from it, and it re-reads it on every later turn.
  • The dangerous failures are silent: truncation without notice, empty lists without reasons, codes without names, errors without directions.
  • Token count matters less than turns. Bad results cause extra turns or confident wrong answers.
  • The Return Contract: outcome first; bounded and announced; names over codes; empty with a reason; errors that point forward.
  • Test with a cold read, assert the contract in unit tests, and track truncation, retry and empty rates per tool.

FAQ

What is tool output design for AI agents?

It's designing the text a tool returns to an LLM agent after it runs. Because the agent decides its next step from that text, the result should state the outcome, stay bounded, use human-readable names, explain empty results, and give actionable errors.

How should an AI agent tool handle large outputs?

Cap the output with a sensible default and announce any truncation: how many items were shown, how many exist, how they're sorted, and how to get the rest (pagination, a narrower filter, an offset). For logs, keep the tail. Silent truncation is the failure to avoid.

Should tool results return JSON or plain text?

Either can work. What matters is content, not syntax: an outcome sentence first, resolved names instead of internal codes, and only the fields the next decision needs. Compact text often uses fewer tokens than verbose JSON with repeated keys.

How should tools return errors to an LLM agent?

As instructions. State what was wrong, what valid input looks like, give one example, and say whether retrying can succeed. Never let an error be returned as an empty result.

Why does my AI agent say "no results" when data exists?

Usually because a permission failure, a timeout or a wrong filter was converted into an empty list somewhere in the stack. Make errors take a separate path and make empty results say what was searched.

Does reducing tool output tokens reduce agent cost?

Somewhat, but turns usually matter more. In one analysis of 600 coding-agent trajectories, turn count explained 84% of the variance in log cost versus 4% for observation size. Results that prevent retries and dead ends save more than trimming alone.

The bottom line

You already treat your system prompt as code. Give every return in your tools the same review. The agent reads those far more often than anything you wrote on purpose.

The model can only be as right as the last thing your tool told it.

Adam Jaber is a software engineer who writes Simply Explained: complex topics, made simple. No jargon, no hype. Get one of these in your inbox each week: subscribe on Substack.

About the author

  • I'm a senior software engineer. I write Simply Explained, a plain-English breakdown of how AI and software actually work, and the quiet ways they break: AI fixes that hide bugs, agents that pick the wrong tool, health checks that take down healthy servers. One symptom, one analogy, one fix per piece. New here? Start with the pinned Start Here guide, or get one breakdown a week by email.

No comments yet. Be the first to comment.

Building with AI

Part 15 of 15

Plain-English deep dives into how AI actually works under the hood — and how to build with it without the hype. Prompting that gets real results, how RAG systems retrieve before they answer, working with coding agents, and the compounding-error math behind why autonomous agents fail in production. For developers and the technically curious who want the practical layer beneath the buzzwords. No jargon, no hype — just clear mental models you can use.

Start from the beginningWhen AI's 'Thinking' Mode Actually Makes It WorseReasoning models are a genuine leap — on the right problems. On the wrong ones, thinking longer makes AI slower, pricier, and less accurate. Here's the test.