Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet

A room-booking service answers with 2603 characters and 111 fields. Shaping the tool result down to 99 characters keeps the same decision, merging six overlapping tools into two cuts the tool list, and trimming too far shows why the id must stay.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Trim a raw service payload to the fields the next step needs
  • Keep a stable id in the result so the agent can act on it
  • Merge overlapping read tools into one, and keep writes separate
  • Measure the size before and after and check the decision did not change

Before you start

  • Tool input schemas and error responses
  • Basic Python dictionaries and JSON

You ask a booking assistant: find me a room for six at two o'clock. The booking service knows everything, so it answers with everything: 2603 characters and 111 fields. Claude has to dig the answer out of that.

This article covers three habits for tool results and tool lists: trim the result, merge the tools, and measure the effect.

The filing cabinet and the sticky note

At an office front desk you ask: any room for six at two o'clock? One clerk hands you the whole filing cabinet: every room, every booking, every serial number, every audit stamp. Another hands you a sticky note: Blue, floor three, eight seats, room id blue-3.

Same facts, two answers. The note is the one you can book from.

The handler decides what Claude reads Booking service raw payload 2603 characters 111 fields Our handler keeps what the next step needs Claude tool_result 99 characters 5 fields Same question, same answer, a much smaller message.
The handler sits between the service and Claude, so it decides what Claude reads. Sizes are characters of JSON from the lesson run.

What is in the raw payload

The stand-in booking service in raw_api.py returns, for every room, an internal reference, the building address and map coordinates, equipment serial numbers and service dates, an audit tag, and every booking with the organiser's email and the attendee list, plus paging links. None of that helps to pick a room or book one.

So ask: what does the next step need?

  • The room id, to book it.
  • The name, to say it.
  • The floor, to tell the user.
  • The seats, to check the size.

The rule: choose fields by what the next step needs, not by what the service happens to return.

shaping.py: the trim

"""Trim the booking payload to what the next step needs."""


def is_free(room, start, end):
    return all(b["end"] <= start or b["start"] >= end
               for b in room["bookings"])


def shape_rooms(raw, min_seats, start, end):
    keep = []
    for room in raw["data"]:
        seats = room["capacity"]["seated"]
        if seats < min_seats:
            continue
        if not is_free(room, start, end):
            continue
        keep.append({"room_id": room["slug"],
                     "name": room["name"],
                     "floor": room["floor"],
                     "seats": seats})
    return {"window": f"{start}-{end}", "rooms": keep}
  • Rooms that are too small, or busy at any point in the window, are skipped.
  • The room_id comes from the readable slug (blue-3), not the internal reference (obj_blue3_7f3a91). Stable, readable identifiers are easier for the model to carry into the next call.
  • An empty rooms list is a valid answer: nothing is free, and that is a success.

A lean tool set

The first version of the agent had six tools: list_rooms, get_room, get_room_bookings, check_room_free, find_free_room and book_room. Five of them answer the same question, which room is free?, and Claude has to choose between them on every request.

So we merge the five into one search tool, and keep the write on its own. The Claude docs advise consolidating related operations into fewer tools, because fewer, more capable tools reduce selection ambiguity.

BOOK = tool(
    "book_room",
    "Books one meeting room for a time window and "
    "returns a booking id. Input: a room_id from "
    "find_rooms, a start and an end time. Example: "
    "room_id blue-3, start 14:00, end 15:00. "
    "Not for searching: use find_rooms first.",
    {"room_id": ROOM, "start": TIME, "end": TIME},
    ["room_id", "start", "end"])

FIND = tool(
    "find_rooms",
    "Finds meeting rooms that are free for a whole "
    "time window and big enough. Returns only "
    "room_id, name, floor and seats, one entry per "
    "room. Input: a start, an end and the minimum "
    "seats. An empty rooms list is a valid answer: "
    "nothing is free in that window.",
    {"start": TIME, "end": TIME,
     "min_seats": {"type": "integer"}},
    ["start", "end", "min_seats"])

LEAN_TOOLS = [FIND, BOOK]

Two details matter. find_rooms says what it returns, so Claude knows what to expect back. And book_room stays separate because it writes: a write deserves its own tool and its own description.

Run it: measure, and check the decision

compare.py is a stand-in agent that runs without an API key. It prints the sizes, the agent's decision from the shaped result, and whether the raw payload leads to the same decision.

raw payload     -> 2603 characters, 111 fields
shaped result   -> 99 characters, 5 fields
shaped, agent   -> book_room(blue-3)
same decision   -> True
empty search    -> no free room: tell the user
too thin        -> cannot book: no room_id in the result
tool set before -> 6 tools, 2213 characters
tool set after  -> 2 tools, 1283 characters

Read it line by line:

  • The result went from 2603 characters to 99, and the decision stayed book_room(blue-3) both ways. Smaller is only half the check; the decision must not change.
  • Asking for 20 seats finds nothing, and the agent tells the user. A success, not an error. (Error results are covered in tool input schemas and error responses.)
  • The tool list travels with every request, and it dropped from 2213 characters to 1283.

Characters here are a stand-in for tokens. Against the real API, count tokens with client.messages.count_tokens before and after, and compare input_tokens. The count is an estimate.

Break it: trim too far

shape_too_thin keeps only the room name:

def shape_too_thin(raw, min_seats, start, end):
    """Over-trimmed on purpose: names only, no room_id."""
    full = shape_rooms(raw, min_seats, start, end)
    return {"rooms": [{"name": r["name"]}
                      for r in full["rooms"]]}

The room is called Blue, and the id is gone. The agent has nothing to book with, so the run prints cannot book: no room_id in the result. Put the id back and it books blue-3 again.

Minimal means enough to act on, not as small as possible.

Common mistakes

MistakeWhy it hurtsFix
Pass the raw service payload throughContext fills with fields nobody usesKeep only what the next step needs
Drop the id while trimmingThe agent can't act on the resultAlways keep a stable id
Use an opaque internal reference as the idHarder to carry into the next callUse a readable, stable identifier
Several read tools for one questionSelection ambiguity on every requestMerge into one capable tool
Merge a write into a read toolA risky action hides behind a searchKeep writes as their own tools
Only check that the result got smallerA smaller result can change the decisionCompare decisions before and after

Quick recap

HabitIn the lesson
Trim2603 to 99 characters: room id, name, floor, seats
Merge6 tools to 2: find_rooms and book_room
MeasureSizes before and after, and the same decision: book_room(blue-3)

Try it yourself

A user now asks for a room with a 4K screen. Which field from the raw payload would you add to the shaped result, and how would you name it so the result stays small and readable?

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 36 of 66

Previous
Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
Next post
Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Related posts

The Claude Messages API: Your First Call, Field by Field

One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.

Claude Tool Use: How tool_use and tool_result Work in the Messages API

Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.

Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared

Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.

Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move

Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.

On this page

  • The filing cabinet and the sticky note
  • What is in the raw payload
  • shaping.py: the trim
  • A lean tool set
  • Run it: measure, and check the decision
  • Break it: trim too far
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.