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

Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First

Your own tools run in your code and every tool_use needs a tool_result. Server tools like web search run at Anthropic and come back already answered. A refund harness shows both, plus an approval gate that asks a person first and still answers a decline.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Tell a client tool (tool_use, you run it) from a server tool (server_tool_use, Anthropic runs it)
  • Handle the three server-tool response shapes: end_turn, pause_turn and a mixed turn
  • Put an approval gate in front of a risky tool and still answer a declined call
  • Describe the order in which the Agent SDK decides whether a tool call may run

Before you start

  • Claude tool use: tool_use and tool_result
  • Basic Python

A customer writes: please refund order 1042. Before anything happens, two questions come up. Who runs the tool? And who says yes first?

This article answers both with a small refund harness: a client tool, a server tool, and an approval gate in front of the risky one.

A workshop, a supplier and the manager's key

  • Your own workshop. You do the work yourself, see every step and hand back the finished job. That is a client tool.
  • A supplier. They work in their own factory and send the product back done. You only read what arrives. That is a server tool.
  • The manager's key. A small sale goes through. A big refund waits until the manager says yes. That is an approval gate.

Two kinds of tools

Client tools and server tools Client tools: you run them your own tools, plus Anthropic-schema tools like bash and text_editor 1. stop_reason: tool_use 2. your code runs it 3. you send a tool_result Server tools: Anthropic runs them web_search, web_fetch, code_execution, tool_search 1. response has server_tool_use 2. result block, same reply 3. you send nothing back
The tool_use block is yours to answer. The server_tool_use block is already answered. (Source: Claude docs, Tool use overview; Server tools.)

One detail catches people: Anthropic's schema tools, such as bash, text editor, memory and computer use, are still client tools. Anthropic defines the schema; your code runs them. The client loop itself is in Claude tool use: tool_use and tool_result.

tools.py: mark each tool auto or ask

"""Client tools run here. Server tools run at Anthropic."""


def lookup_order(args):
    return {"order_id": args["order_id"], "paid": True}


def issue_refund(args):
    return {"refund_id": "R-7001", "amount": args["amount"]}


CLIENT_TOOLS = {
    "lookup_order": {"run": lookup_order, "approval": "auto"},
    "issue_refund": {"run": issue_refund, "approval": "ask"},
}

SERVER_TOOLS = [
    {"type": "web_search_20250305", "name": "web_search"},
]

lookup_order only reads, so it runs at once. issue_refund moves money, so it waits for a person. web_search is only declared; we never run it.

harness.py: dispatch every block

"""The harness: dispatches every block of a Claude response."""
import json
from approval import ask_person
from tools import CLIENT_TOOLS


def tool_result(uid, data, error=False):
    block = {"type": "tool_result", "tool_use_id": uid,
             "content": json.dumps(data)}
    if error:
        block["is_error"] = True
    return block


def dispatch(response, answers):
    results = []
    for block in response["content"]:
        if block["type"] == "server_tool_use":
            print(f'  SERVER  {block["name"]} runs at Anthropic')
        if block["type"] != "tool_use":
            continue
        uid = block["id"]
        tool = CLIENT_TOOLS[block["name"]]
        ask = tool["approval"] == "ask"
        if ask and not ask_person(block, answers):
            note = {"message": "The user declined this call"}
            results.append(tool_result(uid, note, error=True))
            continue
        print(f'  CLIENT  {block["name"]} runs here')
        output = tool["run"](block["input"])
        results.append(tool_result(uid, output))
    return results

A server_tool_use block is only noted. For a client tool marked ask, the person is asked first. If they say no, the harness still adds a tool_result, with is_error set and a short message.

The gate itself, in approval.py, shows the person exactly what will run and returns true only for yes:

def describe(block):
    name, args = block["name"], block["input"]
    return f"{name}({args})"


def ask_person(block, answers):
    answer = answers.pop(0)
    print(f"  ASK     {describe(block)} -> {answer}")
    return answer == "yes"

Run it: five scripted turns

agent_run.py uses a stand-in model that sends five scripted turns, and scripted answers from the person (yes, then no), so no API key is needed:

turn 1  stop_reason: tool_use
  CLIENT  lookup_order runs here
  SEND    1 tool_result back, 0 is_error
turn 2  stop_reason: tool_use
  ASK     issue_refund({'order_id': '1042', 'amount': 49.9}) -> yes
  CLIENT  issue_refund runs here
  SEND    1 tool_result back, 0 is_error
turn 3  stop_reason: tool_use
  ASK     issue_refund({'order_id': '1042', 'amount': 400.0}) -> no
  SEND    1 tool_result back, 1 is_error
turn 4  stop_reason: pause_turn
  SEND    the paused response back as it is
turn 5  stop_reason: end_turn
  SERVER  web_search runs at Anthropic
  DONE    end_turn: nothing to send
  • Turn 1: the lookup is auto, so it runs without a question.
  • Turn 2: a refund of 49.90. The person says yes, then it runs.
  • Turn 3: a refund of 400. The person says no, and a tool_result is still sent, with is_error.
  • Turns 4 and 5: a paused server turn, then a finished web search. Nothing for us to run.

Server tools come back in three shapes

Shapestop_reasonWhat is in the replyYour job
Server tool onlyend_turnserver_tool_use, its result block, the textRead the text
Pausedpause_turnserver_tool_use, no result block yetSend the reply back as it is, with the same tools
Mixed turntool_useserver_tool_use plus your own tool_useRun yours and send only the tool_result blocks; the server tool runs on the next request

The quick check: a server_tool_use block with no result block means that call is not finished.

Approval in the Agent SDK

If you build on the Claude Agent SDK, the gate is built in. The SDK decides a tool call in this order (Source: Claude Agent SDK docs, Configure permissions):

  1. Hooks can deny the call or pass it on.
  2. Deny rules: a match is denied, even in bypass mode.
  3. Ask rules send the call to the canUseTool callback.
  4. The permission mode, the global setting: default, dontAsk, acceptEdits, plan, bypassPermissions or auto.
  5. Allow rules: a match is approved and the callback is skipped.
  6. canUseTool: a person decides at runtime.

The warning is in that order. A call approved early, by an allow rule, acceptEdits or bypass, never reaches canUseTool. To check calls that an allow rule approves, put the check in a PreToolUse hook, which runs first.

Break it: skip the declined call

The bug: the person says no, and the harness just skips the call, sending no reply for that tool_use block. The next request fails, because the API finds tool_use ids without tool_result blocks. One decline, and the whole turn fails with no answer for the customer.

The fix is what harness.py already does: answer the decline with is_error: true. Claude reads it and explains to the customer. The gate says no to the action. It never says no to the tool_result.

Quick recap

KindBlockYou do
Client tooltool_useRun it, send a tool_result
Server toolserver_tool_useRead the answer; send no tool_result; continue a pause_turn as it is
Risky client tooltool_use behind a gateAsk first; answer a decline with is_error

For wider checks on what an agent may do, see guardrails for an LLM agent.

Try it yourself

Change the gate so refunds of 50.00 or less run without asking and larger ones still ask. Where does that rule belong: in tools.py, in approval.py, or in harness.py?

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 · 38 of 66

Previous
Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
Next post
Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits

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

  • A workshop, a supplier and the manager's key
  • Two kinds of tools
  • tools.py: mark each tool auto or ask
  • harness.py: dispatch every block
  • Run it: five scripted turns
  • Server tools come back in three shapes
  • Approval in the Agent SDK
  • Break it: skip the declined call
  • 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.