Claude Tool Design: Descriptions, Response Shaping and Errors
👋 In plain words: A tool works only if Claude understands when to call it, what to pass, and what comes back. Most tool bugs are design bugs: vague descriptions, ambiguous parameters, huge responses and unhelpful errors. This lesson fixes each of these, one step at a time, on a real support-agent tool.
The CCDV-F skill “Tool Design and Response Shaping” covers the whole life of a tool: the schema, a description that drives correct invocation, a response that gives Claude a minimal actionable result, error handling, where the tool runs, approval for risky actions, and assembling the tool set. In this lesson you will diagnose a tool that Claude keeps calling with the wrong argument, fix it in the right place, shape its responses and errors, and add an approval gate.
🔑 Key terms
- Invocation: Claude choosing to call a tool with specific inputs.
- Response shaping: deciding what your tool returns so Claude gets only what it needs.
- Structured error: an error result with a clear code, message and hint, rather than a stack trace.
- Approval gate: a check that pauses a risky tool call until a person confirms it.
🪜 Step 1: Reproduce the bad behaviour
An order-support agent has one tool. Its description is short, and traces show Claude often passes the customer’s name as the order ID:
📄 bad_tool.py
import anthropic
client = anthropic.Anthropic()
BAD_TOOL = {
"name": "get_order_status",
"description": "Looks up an order.",
"input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]},
}
r = client.messages.create(
model="claude-opus-5-5", max_tokens=1000, tools=[BAD_TOOL],
messages=[{"role": "user", "content": "Hi, I'm Priya Sharma. Where is my order?"}],
)
for b in r.content:
if b.type == "tool_use":
print("Claude called:", b.name, b.input)⌨️ Terminal
python bad_tool.py🖥️ Output (sample run)
Claude called: get_order_status {'order_id': 'Priya Sharma'}
The lookup then fails, and the agent tells the customer their order “cannot be found”. The model is not broken; the tool told it almost nothing.
🪜 Step 2: Fix the description and the schema
Anthropic’s own exam guide uses this scenario in a sample item: the fix belongs in the tool definition, because the description and schema are what Claude reads when deciding how to call a tool. Name the identifier, its format, an example, and what to do when it is missing:
📄 good_tool.py
import anthropic
client = anthropic.Anthropic()
GOOD_TOOL = {
"name": "get_order_status",
"description": (
"Get the shipping status of ONE order by its order ID. "
"order_id is the alphanumeric order identifier, not a customer name or email: it starts with 'ORD-' "
"followed by digits, for example ORD-48213. If the customer has not given an order ID, "
"ask them for it instead of calling this tool."
),
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "string", "pattern": "^ORD-[0-9]{4,10}$",
"description": "Order ID such as ORD-48213 (from the confirmation email)"},
},
"required": ["order_id"],
"additionalProperties": False,
},
}
r = client.messages.create(
model="claude-opus-5-5", max_tokens=1000, tools=[GOOD_TOOL],
messages=[{"role": "user", "content": "Hi, I'm Priya Sharma. Where is my order?"}],
)
print(r.stop_reason, "->", r.content[0].text)⌨️ Terminal
python good_tool.py🖥️ Output (sample run)
end_turn -> I can check that for you. Could you share your order ID? It starts with ORD- and is in your confirmation email, for example ORD-48213.
Why the other “fixes” from that sample item are weaker:
- A general system-prompt rule (“always use identifiers”) is further from the decision than guidance attached to the tool itself.
- Forcing the tool call does not change the argument Claude supplies (and forced
tool_choiceis rejected on current models anyway). - Adding a lookup-by-name tool widens the tool surface, can return another customer’s order for a common name, and hides the missing-ID case.
🪜 Step 3: Return structured errors
When a call fails, return an error that tells Claude what went wrong and how to recover. Compare:
📄 errors.py
import json
import re
def get_order_status(order_id: str) -> dict:
if not re.fullmatch(r"ORD-\d{4,10}", order_id):
return {"error": {"code": "INVALID_ORDER_ID", "message": f"'{order_id}' is not an order ID.",
"expected_format": "ORD- followed by 4-10 digits, e.g. ORD-48213",
"hint": "Ask the customer for the order ID from their confirmation email."}}
if order_id != "ORD-48213":
return {"error": {"code": "ORDER_NOT_FOUND", "message": f"No order {order_id}.",
"hint": "Check the digits with the customer."}}
return {"order_id": order_id, "status": "shipped", "eta": "2026-11-27"}
for oid in ["Priya Sharma", "ORD-99999", "ORD-48213"]:
result = get_order_status(oid)
is_error = "error" in result
print(f"{oid:<13} is_error={is_error!s:<5} {json.dumps(result)}")⌨️ Terminal
python errors.py🖥️ Output
Priya Sharma is_error=True {"error": {"code": "INVALID_ORDER_ID", "message": "'Priya Sharma' is not an order ID.", "expected_format": "ORD- followed by 4-10 digits, e.g. ORD-48213", "hint": "Ask the customer for the order ID from their confirmation email."}}
ORD-99999 is_error=True {"error": {"code": "ORDER_NOT_FOUND", "message": "No order ORD-99999.", "hint": "Check the digits with the customer."}}
ORD-48213 is_error=False {"order_id": "ORD-48213", "status": "shipped", "eta": "2026-11-27"}
- Send these back as
tool_resultblocks with"is_error": Truewhen there is anerrorkey. - Codes (
INVALID_ORDER_IDvsORDER_NOT_FOUND) let Claude react differently: ask for the ID versus ask to check the digits. - Never return raw stack traces: they waste tokens, leak internals and rarely help the model.
🪜 Step 4: Shape the response
Internal APIs return far more than Claude needs. Every extra field costs tokens on every later turn of the conversation and can distract the model. Return the minimum that lets Claude act:
📄 shape.py
import json
raw_api_response = {
"order": {"id": "ORD-48213", "status_code": 3, "status_label": "SHIPPED", "carrier": "BlueDart",
"tracking": "BD123456789IN", "eta_epoch": 1795996800,
"warehouse": {"id": "WH-7", "address": "Plot 22, Phase II", "manager": "R. Iyer"},
"items": [{"sku": f"SKU-{i}", "qty": 1, "price_paise": 49900} for i in range(12)],
"audit": [{"ts": 1795400000 + i, "event": "scan"} for i in range(40)]},
}
def shape(raw: dict) -> dict:
o = raw["order"]
return {"order_id": o["id"], "status": o["status_label"].lower(), "carrier": o["carrier"],
"tracking_number": o["tracking"], "eta": "2026-11-27", "item_count": len(o["items"])}
print("raw characters :", len(json.dumps(raw_api_response)))
print("shaped characters:", len(json.dumps(shape(raw_api_response))))
print(json.dumps(shape(raw_api_response)))⌨️ Terminal
python shape.py🖥️ Output
raw characters : 2339
shaped characters: 144
{"order_id": "ORD-48213", "status": "shipped", "carrier": "BlueDart", "tracking_number": "BD123456789IN", "eta": "2026-11-27", "item_count": 12}
Shaping rules of thumb:
- Human-readable values (
"shipped", a date) instead of internal codes and epoch seconds. - Summaries and counts instead of long lists; add a
limit/pageparameter if Claude sometimes needs more. - No internal or personal data the task does not need (warehouse manager names, audit logs).
🪜 Step 5: Choose where the tool runs, and gate risky ones
Execution side. Client tools run in your code, with your credentials and network. Server tools (web search, code execution) run on Anthropic’s infrastructure (next lesson). Keep anything that touches your private systems or secrets on the client side.
Approval pattern. For tools that change things (refunds, deletions, deployments), make the decision deterministic in code, not in the prompt:
📄 approval.py
RISKY = {"issue_refund", "delete_account"}
def execute(tool_name: str, tool_input: dict, approve) -> dict:
if tool_name in RISKY and not approve(tool_name, tool_input):
return {"error": {"code": "REJECTED_BY_HUMAN", "message": f"{tool_name} was not approved."}}
if tool_name == "issue_refund" and tool_input["amount"] > 100:
return {"error": {"code": "LIMIT_EXCEEDED", "message": "Refunds over 100 need a supervisor."}}
return {"ok": True, "tool": tool_name}
def reviewer(name, args): # in a real app: a UI prompt, Slack approval, etc.
return args.get("amount", 0) <= 50
print(execute("get_order_status", {"order_id": "ORD-48213"}, reviewer))
print(execute("issue_refund", {"order_id": "ORD-48213", "amount": 30}, reviewer))
print(execute("issue_refund", {"order_id": "ORD-48213", "amount": 80}, reviewer))⌨️ Terminal
python approval.py🖥️ Output
{'ok': True, 'tool': 'get_order_status'}
{'ok': True, 'tool': 'issue_refund'}
{'error': {'code': 'REJECTED_BY_HUMAN', 'message': 'issue_refund was not approved.'}}
The limit and the approval live in code, so no prompt, and no instruction hidden in a customer message, can bypass them. Lesson 50 builds this into hooks for agents.
🪜 Step 6: Assemble a lean tool set
- Few, distinct tools. Overlapping tools (
get_order,lookup_order,find_order_by_id) make Claude guess. Merge them or make their descriptions clearly different. - Consistent naming. Verb first, one object:
get_order_status,create_ticket. - Large catalogues. With dozens of tools, Anthropic’s tool search tool lets you mark tools
defer_loading: trueso only relevant ones are loaded. At least one tool must stay non-deferred. - Strict schemas (
"strict": True) when argument shapes must be exact (Lesson 22).
🌍 Real-world example: Ravi’s Jira tool
Ravi’s create_ticket tool returned Jira’s full 6 KB JSON on every call. After ten tickets, the agent’s context was mostly Jira metadata. He shaped the response to {key, url, status}, added an INVALID_PRIORITY error with the allowed values, and the agent stopped inventing priorities like “P0”.
🧪 Practice Questions
Question 1. Traces show Claude often calls lookup_invoice with the customer’s email instead of the invoice number, gets an error, and tells the user the invoice does not exist. The description says “Looks up an invoice.” Which change most reliably fixes this?
- A. Add a system prompt rule telling Claude to always use identifiers
- B. Rewrite the tool description and schema to define the invoice number format with an example, ask for it when missing, and return a structured error naming the expected format
- C. Force tool_choice to lookup_invoice on every turn
- D. Add a second tool that looks up invoices by email
Show answer
Answer: B. The tool definition is what Claude reads when deciding the arguments, and a structured error lets it recover. The other options are weaker or widen the attack surface.
Question 2. A tool returns the full 8,000-token API response for every call, and long sessions become slow and expensive. What should you change?
- A. Raise max_tokens
- B. Shape the tool result to the minimal fields Claude needs, with readable values
- C. Use a model with a larger context window
- D. Call the tool less often by adding a sleep
Show answer
Answer: B. Tool results stay in the conversation. Returning only actionable fields cuts tokens on every later turn.
Question 3. Which two belong in a good tool error result? (Choose 2.)
- A. A stable error code such as ORDER_NOT_FOUND
- B. The full Python stack trace
- C. A hint about how to recover, such as the expected format
- D. The database connection string
Show answer
Answer: A and C. Codes and hints help Claude choose a recovery. Stack traces and connection strings waste tokens and leak internals.
Question 4. Refunds above $100 must never happen without a supervisor, even if a customer’s message contains convincing instructions. Where should this rule be enforced?
- A. In the system prompt only
- B. In the tool description only
- C. In the code that executes the tool, as a deterministic check
- D. In the user message
Show answer
Answer: C. Prompts can be overridden or misread; a check in code cannot be bypassed by model output.
📝 Assignment
- Task 1: Pick one tool from your own project (or invent
get_test_run(run_id)) and rewrite its description with identifier format, example and missing-input behaviour.
✅ Done when: the description answers “what, when, which format, what if missing”. - Task 2: Write a
shape()function for one of your real API responses and measure the size before and after.
✅ Done when: the shaped result keeps everything needed to answer typical questions. - Stretch: Run your old and new tool definitions on 10 test messages (some without an ID) with your key, and count wrong-argument calls for each.
✅ Done when: you have the two counts side by side.
❓ Frequently Asked Questions
🤔 How do I write a good tool description for Claude?
Say what the tool does, when to use it, the exact meaning and format of each parameter with an example, and what Claude should do if an input is missing.
🤔 What should a tool return to Claude?
The minimal, readable result needed for the next step. Summarise long data, convert codes and timestamps, and leave out internal or personal fields.
🤔 How should a tool report errors?
As a tool_result with is_error: true and a structured body: an error code, a short message and a recovery hint.
🤔 How many tools can I give Claude?
There is no small fixed limit, but every tool adds tokens and choice. Keep tools few and distinct, and use tool search with deferred loading for large catalogues.
🏁 Summary
- Fix wrong-argument bugs in the tool description and schema: format, example, ask-when-missing.
- Return structured errors with codes and hints, flagged with
is_error. - Shape responses to the minimum actionable, readable data.
- Keep private systems on client-side tools and enforce risky-action approvals in code.
- Keep the tool set small, distinct and consistently named.
Next, continue with Built-in Tools vs Custom Tools vs Skills vs MCP for Claude.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.