Topic 4 of 5 · 5 min read
Keeping tool results compact
Goal: Rewrite a tool's output so results carry what the agent needs in a fraction of the tokens.
A tool should return what the agent needs for the next decision, not everything it could return. Results are context too, and they stay in the history on every later turn.
Check yourself · 1 of 3
Tool definitions cost about the same fixed amount on every turn. Why do tool results often end up costing more over a long agent session?
Why it matters
A tool that returns a full API response, a whole log file or a complete web page can use more of the window in one call than all the tool definitions together. That text then sits in the conversation and is re-read each turn. The model may lose track of the instruction at the top, miss the one useful line in the middle of noise, or hit the limit and have the history compacted. Anthropic's article on writing tools for agents recommends pagination, filtering and sensible defaults, and truncation with a hint on how to ask for more. The code execution with MCP article shows the same idea taken further: let code filter big data and pass only a summary back.
How to make results compact
- Return fields, not records. Send id, title and status, not forty fields per row.
- Filter at the source. Accept query parameters (date range, level, limit) so the tool does the filtering, not the model.
- Paginate with a small default. Return ten items and a cursor. Say how many exist in total.
- Truncate with a signal. Cut at a limit and say so: "showing 20 of 1,340 lines; pass
patternto narrow". - Use readable names. Names and short identifiers help the model more than long opaque ids.
- Clear old results. When a result is no longer needed, drop or summarise it (many agent frameworks can clear old tool results automatically).
Before and after
# Before: returns every field of every row
def list_orders(customer_id):
return db.query("SELECT * FROM orders WHERE customer_id = %s", customer_id)
# After: bounded, filterable, tells the agent what it did not see
def list_orders(customer_id, status=None, limit=10):
rows = db.query_orders(customer_id, status=status, limit=limit + 1)
page = [{"id": r.id, "total": r.total, "status": r.status} for r in rows[:limit]]
return {"orders": page, "has_more": len(rows) > limit}
What goes wrong
- Silent truncation. If the tool cuts output without saying so, the agent treats a partial list as complete.
- Too much trimming. Removing the field the agent needs forces extra calls.
- Error text hidden. Compact does not mean vague: keep error messages specific so the agent can recover.
Examples
A log tool with a cap
def read_log(path, pattern=None, max_lines=50):
lines = [l for l in open(path) if not pattern or pattern in l]
shown = lines[-max_lines:]
note = f"showing {len(shown)} of {len(lines)} matching lines"
return {"lines": shown, "note": note}
The agent gets the recent matching lines and a note that tells it more exist.
Filtering with code instead of the window
Instead of returning ten thousand spreadsheet rows to the model, the agent runs code that groups them and returns five lines of totals. The model reasons over the five lines. This is the idea in Anthropic's code execution with MCP article.
Key points
- Tool results stay in the history and are re-read on later turns, so a large result costs context repeatedly.
- Return only the fields needed for the next decision and let the tool filter at the source.
- Paginate with a small default and report the total or whether more exist.
- When truncating, say so and tell the agent how to narrow the request.
- Clear or summarise old tool results once they are no longer needed.
Common mistakes
- Returning the raw API response because it was the easiest thing to write.
- Truncating without telling the agent that data is missing.
- Cutting so much that the agent must call again for every detail.
- Leaving large old results in the history long after the agent finished with them.
Check yourself · 2 of 3
A tool returns 4,000 log lines. What is the best change?
Check yourself · 3 of 3
A list tool returns forty fields per order. The agent only needs id, status and total. What do you do?
Practice items, not counted towards your mastery.
Start here
- Introducing advanced tool use (Anthropic) (opens in a new tab)ArticleFree
Shows tool search, programmatic tool calling and tool-use examples, with Anthropic's own measurements of context saved.
- Code execution with MCP (Anthropic) (opens in a new tab)ArticleFree
Explains why many MCP tool definitions and large intermediate results waste context, and the code-execution fix.
- Tool search tool (Claude docs) (opens in a new tab)DocsFree
The API reference for deferring tool definitions and loading them on demand.
More for this topic
- Writing effective tools for AI agents (Anthropic) (opens in a new tab)ArticleFree
How to consolidate tools, name them clearly and return compact, useful results.