Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free 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

Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop

Part 2 of the refund app build-along: four files, each from a requirement. An MCP server keeps the orders, two tools refund or hand off, a hook holds the $500 limit, and one loop routes every tool_use.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Serve order data from a small MCP server with one tool and an error result
  • Write Messages API tools whose descriptions say when to use them
  • Enforce a refund limit with a PreToolUse hook that denies with a reason
  • Join the server, the tools and the hook in one tool_use loop

Before you start

  • From requirement to design (part 1)
  • Claude tool use: tool_use and tool_result
  • Python async basics

In part 1 we turned "answer refund questions and refund small orders" into eight requirements and five design elements. Now the design has to run.

The key moment in this app: a model call can stop with stop_reason: "tool_use". That means Claude is asking for something. Our code decides where the ask goes, and in one case, whether it is allowed at all.

Where each file sits

The refund app as one picture Customer app.py (the loop) Claude tool_use orders_server.py MCP: get_order hooks.py refund over $500? deny tools.py issue_refund, hand_to_human
The model asks. The loop routes the ask to the server or a tool, and a refund meets the hook first.

Four files, each with a reason from part 1:

FileMeetsJob
orders_server.pyF1, I1MCP server: look up an order, keep the data with us
tools.pyF3, F4Refund a small order, hand a big one to a human
hooks.pyI3The refund limit holds every time
app.pyF2The loop that answers the customer in plain words

Picture a clerk at a shop counter. The stockroom window hands over one record when asked (the MCP server). The till does an action when told to (our tools). The manager's key is needed for big sums, and it works the same every time (the hook). The clerk who talks to the customer and uses all three is app.py.

orders_server.py: the data behind one door

"""F1 and I1: order data lives behind an MCP server."""
import json
import pathlib
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

mcp = MCPServer("orders")
DATA = pathlib.Path(__file__).with_name("orders.json")


@mcp.tool()
def get_order(order_id: str) -> str:
    """Look up one order by its id.

    Returns its status and total as JSON. Use it
    before any refund. An unknown id is an error.
    """
    orders = json.loads(DATA.read_text())
    if order_id not in orders:
        raise ToolError(f"no order {order_id}")
    return json.dumps(orders[order_id])


if __name__ == "__main__":
    mcp.run(transport="stdio")

One decorator turns get_order into a tool. The docstring becomes the tool description, which is what Claude reads to decide when to call it (more on that in how Claude picks a tool). A missing id raises ToolError, so it comes back as an error result, not a crash. For the full server API see building an MCP server.

tools.py: our own tools, in Messages API shape

"""F3 and F4: our own tools for the Messages API."""
REFUND_TOOLS = [
    {"name": "issue_refund",
     "description": ("Refund an order in full. Use it "
                     "only after get_order has "
                     "confirmed the order exists."),
     "input_schema": {
         "type": "object",
         "properties": {"order_id": {"type": "string"},
                        "amount": {"type": "number"}},
         "required": ["order_id", "amount"]}},
    {"name": "hand_to_human",
     "description": ("Send the case to a person. Use it "
                     "when a refund is not allowed "
                     "for the assistant to make."),
     "input_schema": {
         "type": "object",
         "properties": {"order_id": {"type": "string"},
                        "reason": {"type": "string"}},
         "required": ["order_id", "reason"]}},
]


def run_tool(name, args):
    if name == "issue_refund":
        return f"refund sent: ${args['amount']}"
    return "queued for a human"

Each description says when to use the tool. hand_to_human is the way out for a refund the assistant must not make. Keep an eye on "amount": {"type": "number"}; in a later lab we plant a bug right there.

hooks.py: the limit, kept in code

"""I3: the refund limit holds every time."""
from claude_agent_sdk import ClaudeAgentOptions
from claude_agent_sdk import HookMatcher

LIMIT = 500
REASON = f"Refunds over ${LIMIT} need a human."


async def refund_gate(input_data, tool_use_id, context):
    amount = input_data["tool_input"].get("amount", 0)
    if amount <= LIMIT:
        return {}
    return {"hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "deny",
        "permissionDecisionReason": REASON}}


# How the Agent SDK registers the same callback.
TOOL = "mcp__refunds__issue_refund"
options = ClaudeAgentOptions(hooks={"PreToolUse": [
    HookMatcher(matcher=TOOL, hooks=[refund_gate])]})

The callback reads the amount from the tool input. An empty dict means allow. Over the limit, it denies with a reason Claude can read. The matcher names the tool with its server in front (mcp__<server>__<tool>), which is how the Agent SDK registers it. The Agent SDK would run a registered hook for you; our plain loop calls the same callback itself.

app.py: one loop joins everything

"""D1, D2, D8: the model, MCP server, tools and hook."""
from mcp import Client
from stand_in import MODEL, make_client
from orders_server import mcp
from tools import REFUND_TOOLS, run_tool
from hooks import refund_gate


def as_claude_tool(t):
    return {"name": t.name, "description": t.description,
            "input_schema": t.input_schema}


async def answer(question, claude, orders):
    listed = await orders.list_tools()
    tools = [as_claude_tool(t) for t in listed.tools]
    tools += REFUND_TOOLS
    messages = [{"role": "user", "content": question}]
    steps = []
    while True:
        r = claude.messages.create(
            model=MODEL, max_tokens=300,
            tools=tools, messages=messages)
        if r.stop_reason != "tool_use":
            return r.content[0].text, steps
        messages.append({"role": "assistant",
                         "content": r.content})
        results = []
        for block in r.content:
            if block.type != "tool_use":
                continue
            got = await dispatch(block, orders)
            out, bad, note = got
            oid = block.input["order_id"]
            steps.append(f"{block.name} {oid} -> {note}")
            results.append({"type": "tool_result",
                            "tool_use_id": block.id,
                            "content": out,
                            "is_error": bad})
        messages.append({"role": "user",
                         "content": results})


async def dispatch(block, orders):
    name, args = block.name, block.input
    gate = {}
    if name == "issue_refund":
        gate = await refund_gate({"tool_input": args},
                                 block.id, None)
    if gate:
        why = gate["hookSpecificOutput"]
        reason = why["permissionDecisionReason"]
        return "blocked: " + reason, True, "hook denies"
    if name == "get_order":
        res = await orders.call_tool(name, args)
        text = res.content[0].text
        return text, res.is_error, "mcp: " + text
    text = run_tool(name, args)
    return text, False, text

The loop lists the server's tools, adds ours, and sends one list to Claude. If the stop reason is anything but tool_use, the answer is ready. Otherwise every tool_use block is dispatched: a refund meets the hook first, get_order goes to the MCP server, anything else runs locally. Every call gets a tool_result back with an is_error flag, and the loop goes round again.

Four customers, one app

The run uses a stand-in for Claude: the real Anthropic SDK talks to an httpx.MockTransport that answers like the Messages API with scripted replies, so no key is needed. The lines marked "test model reply" are scripted, not real Claude output. The MCP server, tools and hook are real code.

R-1: Where is order A-101?
  get_order A-101 -> mcp: {"status": "shipped", "total": 45}
  test model reply: order A-101 is shipped.
R-2: Please refund order A-102.
  get_order A-102 -> mcp: {"status": "delivered", "total": 120}
  issue_refund A-102 -> refund sent: $120
  test model reply: your refund for A-102 is on its way.
R-3: Please refund order A-103.
  get_order A-103 -> mcp: {"status": "delivered", "total": 640}
  issue_refund A-103 -> hook denies
  hand_to_human A-103 -> queued for a human
  test model reply: a person will contact you about A-103.
R-4: Where is order A-999?
  get_order A-999 -> mcp: Error executing tool get_order: no order A-999
  test model reply: I cannot find order A-999.

Follow R-3. The server says the total is 640. Claude asks to refund 640. The hook sees more than 500 and denies. The loop sends that back as an error tool_result, Claude reads the reason and asks for hand_to_human, then replies with a normal end_turn. The limit held, and the customer still got an answer.

Where a hard rule belongs

Suppose the rule is "a refund limit must hold every time". The tempting options all fail:

  • Put the limit in the system prompt. A prompt can be argued with.
  • Trust the model to stop itself. Nothing enforces trust.
  • Block every refund call. Small refunds stop too.

The answer is a hook that checks the amount: code that runs before the tool, the same rule every time.

Recap

PieceWhat it does
MCP serverKeeps the order data behind one door, unknown id is an error result
ToolsDescriptions say when to use them; hand_to_human is the way out
HookDenies a refund over $500 with a reason Claude can act on
Looptool_use, tool_result, repeat until end_turn

Previous: part 1, requirements to design. Next: part 3, ship it, where four gates decide whether this app may go out.

Keep going in Claude · 56 of 66

Previous
From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
Next post
Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
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)

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

  • Where each file sits
  • orders_server.py: the data behind one door
  • tools.py: our own tools, in Messages API shape
  • hooks.py: the limit, kept in code
  • app.py: one loop joins everything
  • Four customers, one app
  • Where a hard rule belongs
  • Recap
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.