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

In this topic

Claude
  • Claude.ai Interface Tour: Every Control You Need on One Screen
  • The AI Fluency Model: Delegation, Description, Discernment and Diligence
  • Working With Claude: Pick the Surface, Match the Model, Keep the Context Clear
  • Claude's Four Entry Points: Choose Chat, Projects, Artifacts or Research Before You Type
  • What Claude Can Do: Extended Thinking, Web Search, Artifacts and File Analysis
  • Getting More From a Claude Chat: Steer the Conversation Instead of Starting Over
  • Claude Research Mode End to End: From One Prompt to a Cited Briefing
  • Claude's Capability Layer: When to Use Skills, Code Execution or Memory
  • Code Execution and File Creation in Claude: Calculated Numbers and a Real Excel File
  • Adding and Using Skills in Claude: Let Claude Pick the Skill, Then Teach It Your Format
  • Claude Memory, Curation and Incognito: Keep What Helps, Remove What Has Gone Stale
  • Claude Styles, Preferences and Project Instructions: Three Dials, Three Scopes
  • Claude Projects: Knowledge, Instructions and a Real Workspace You Set Up Once
  • Keeping a Claude Project Current and Connected: Refresh, Prune and Grant the Least
  • Claude Scheduled Tasks: Let Claude Work on a Schedule and Email You the Result
  • Claude Code and Claude for Chrome: What They Are and Who They Are For
  • Anatomy of a Good Prompt: Role, Context, Task, Format and Examples
  • Shaping Claude's Output: Format, Tone and Length in a Few Words
  • Iterating and Refining a Prompt: Read, Diagnose, Adjust, Repeat
  • Five Prompting Patterns for Work: Summarise, Extract, Rewrite, Classify and Draft
  • Why Evaluating AI Output Matters Most: Trust, Then Verify
  • Spotting AI Hallucinations and Fabrications: Four Tells and Where Risk Spikes
  • Fact-Checking Claude's Answers: Four Techniques and a Line-by-Line Claim Log
  • Judging AI Output Quality: Four Questions That Score Any Answer
  • Adapting AI Output for Your Audience: One Answer, Three Readers
  • When a Human Must Review AI Output Before It Ships
  • A Personal Validation Checklist for AI Output: Six Lines, Any Draft
  • Fitting Claude Into Real Work: Where It Helps and Where It Never Should
  • Breaking Big Tasks Into Steps With Claude: Small Asks, Checked Hand-offs
  • Designing a Repeatable Claude Workflow: A Reusable Weekly Report Template
  • Measuring If Claude Is Actually Working: One Number, Before and After
  • Communicating AI Value and Limitations to Stakeholders: The Honest Pitch
  • Data Privacy With Claude: What Never Goes in a Prompt, and How to Redact a Document Before You Paste It
  • Responsible AI Use and Transparency: Helpful, Honest, Harmless, and One Honest Line
  • Troubleshooting a Weak Claude Answer: Name the Cause, Fix One Thing, Then Make It Cheaper
  • 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
  • Claude Code's Built-in Tools: Read, Write, Edit, Bash, Grep and Glob, and When Each One Is the Right Pick
  • The CLAUDE.md Hierarchy: User, Project and Directory Files, How They Stack, and the Team Rule Stuck on One Laptop
  • Split a 600-Line CLAUDE.md: @import Lines, .claude/rules Files and Which One to Pick
  • Path-Specific Rules in Claude Code: paths Globs, When a Rule Loads and the Glob That Matches Nothing
  • Claude Code Slash Commands and Skills: Project vs User Scope, $ARGUMENTS, context: fork and allowed-tools
  • Iterative Refinement with Claude Code: Input/Output Examples, Tests First and the Interview Pattern
  • Claude Code Sessions: Resume by Name, Fork From a Baseline, or Start Fresh With a Summary Card
  • CI Reviews That Don't Repeat Themselves: Prior Findings, Existing Tests and Test Standards in CLAUDE.md
  • 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
  • Validation-Retry Loops for Claude Extraction: Send Back the Exact Errors, and Stop When a Retry Cannot Help
  • Multi-Pass and Multi-Instance Code Review with Claude: A Fresh Reviewer, Per-File Passes and an Integration Pass
  • When a Claude Support Agent Should Escalate: Three Clear Triggers, Not Mood or a Confidence Score
  • Error Propagation Across Subagents: Retry Locally, Then Report the Failure, the Attempts and What You Found
  • Human Review and Confidence Calibration: Check Accuracy by Type and Field Before You Stop Looking
  • Provenance in Multi-Source Research: Keep Every Claim With Its Source and Date, and Show Conflicts Instead of Settling Them
  • Lab: An Extraction Pipeline With a Nullable Schema, Validation-Retry, a 100-Request Batch and Human Review
  • Lab: A Research Pipeline With Parallel Subagents, a Timeout That Keeps Its Partial Results, and a Report With Its Trail
  • Coordinator and Subagents: Decompose, Delegate, Check Coverage, and Call Only the Spokes You Need
  • Passing Context to Subagents: Nothing Is Inherited, So Put Findings, Goal and Criteria in the Prompt
  • Parallel Subagents: Several Task Calls in One Response, Every Result Back in One User Turn
  • Task Decomposition: a Fixed Prompt Chain With an Integration Pass, or a Dynamic Plan That Adapts
  • Prompt Guidance vs Programmatic Gates: Block the Refund Until the Customer Is Verified, Then Hand Off a Card That Stands Alone
  • Scoped Tools per Agent and tool_choice: Three to Five Tools per Role, a Shared One, and auto, any or a Forced Tool
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

Prompt Guidance vs Programmatic Gates: Block the Refund Until the Customer Is Verified, Then Hand Off a Card That Stands Alone

A prompt that says "always verify first" works most of the time. gate.py blocks process_refund until get_customer has returned a verified id, across three call sequences. Then a request with two concerns is split, and "please help" is replaced by a four-field handoff card.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Tell a rule that can live in the prompt from one that needs a programmatic gate
  • Block process_refund until get_customer has returned a verified customer id, and test three call sequences
  • Split a message with two requests into two items that share context and get one reply
  • Write a four-field handoff card a human can act on without the transcript

Before you start

  • Claude tool use: tool_use and tool_result
  • Agent SDK hooks: PreToolUse and PostToolUse

A customer writes: refund order 1042 to me. Sounds easy. But picture the wrong order. The agent calls process_refund first, and the money leaves. To whom? Only then does it call get_customer and check who was asking. Too late.

The safe order is the other way round: get_customer first, then process_refund. Some steps must come first, every single time. There are two ways to enforce a rule like that. We can ask Claude nicely in the prompt, or we can build a gate in code. This article shows the difference, then two more things a support agent needs: splitting a request with two concerns, and handing a case to a person.

A sign asks, a lock decides

Think of a bank teller. On the wall there's a sign: please check ID first. Most days the teller follows it. One busy afternoon the teller forgets, and the drawer opens. Now think of a cash drawer with a lock that won't open until an ID is scanned. No scan, no cash. The teller can't forget, because the drawer doesn't allow it.

In an agent, the sign is a prompt instruction: always verify first. Claude follows it most of the time. Once in a while, one call slips through. The failure rate is small, but it isn't zero. The gate is code standing in front of the tool. It looks at every call, and the wrong one is blocked, with a reason, every time.

A sentence versus a gate Prompt instruction "Always verify first" tool runs one refund call slips through small failure rate, not zero Gate in code process_refund call gate(tool, state) no verified id: BLOCKED runs only if allowed
When a rule must always hold, don't rely on a sentence. Put it in code in front of the tool.

gate.py: a prerequisite gate in 26 lines

This file is a plain Python simulation, with no model and no API key. It prints what a gate placed before each tool call would do. The mock customer and order live in data.json: one customer, C-77 (Maya), and order 1042 for headphones at 49.0.

import json, pathlib

DATA = json.load(open(pathlib.Path(__file__).with_name("data.json")))


def gate(tool, state):
    """the hook: runs before a tool call and may say no"""
    if tool == "process_refund" and not state["verified_id"]:
        return "BLOCKED (call get_customer first)"
    return "ALLOWED"


def run(label, calls):
    state = {"verified_id": None}
    for tool, arg in calls:
        verdict = gate(tool, state)
        print(f"{label}: {tool} {arg} -> {verdict}")
        if verdict != "ALLOWED":
            continue
        if tool == "get_customer" and arg in DATA["customers"]:
            state["verified_id"] = arg


run("A", [("process_refund", "1042")])
run("B", [("get_customer", "C-77"), ("process_refund", "1042")])
run("C", [("get_customer", "C-00"), ("process_refund", "1042")])
  • The verified-id check. If the tool is process_refund and no verified customer id exists yet, the rule fires.
  • The reason. BLOCKED (call get_customer first) is the text that goes back to the model, so it knows what to do next instead of just failing.
  • Every call asks the gate. run calls gate before every tool call. There's no path around it.
  • Only a real customer verifies. verified_id is set only when get_customer runs with an id that exists in the data.

Three call sequences

A: process_refund 1042 -> BLOCKED (call get_customer first)
B: get_customer C-77 -> ALLOWED
B: process_refund 1042 -> ALLOWED
C: get_customer C-00 -> ALLOWED
C: process_refund 1042 -> BLOCKED (call get_customer first)

A asks for the refund straight away: blocked. B calls get_customer for C-77, then asks for the refund: both allowed. C is the interesting one. It looks up C-00, an unknown customer. The lookup itself is allowed, but nobody gets verified, so the refund is still blocked. The gate checks the outcome of the prerequisite. A call with the right name is not enough.

In the Claude Agent SDK, this same rule sits in a PreToolUse hook, which runs before the tool and can deny the call with a reason. How to write one is covered in Agent SDK hooks and hooks that block destructive actions.

Two requests in one message

A different problem. The customer writes: refund order 1042, and also update my email. Don't treat that as one blob. Split it into two items: item 1, refund order 1042; item 2, update the email. Investigate both at the same time with shared context, since both know the customer is C-77 and the order is 1042. Then combine the findings into one unified reply. Split, investigate in parallel, answer once. (The parallel part works the way parallel subagents do: several calls in one turn.)

A handoff card that stands alone

Sometimes the agent must hand the case to a person. By then the chat is long, and the human agent can't read the transcript; they only see what you send. So send a card with four fields: who the customer is, why it happened, how much, and what to do next.

import json, pathlib

DATA = json.load(open(pathlib.Path(__file__).with_name("data.json")))


def build_handoff(order_id, root_cause, action):
    order = DATA["orders"][order_id]
    return {
        "customer_id": order["customer"],
        "root_cause": root_cause,
        "refund_amount": order["amount"],
        "recommended_action": action,
    }


print("weak  : customer is upset, please help")
card = build_handoff("1042", "headphones arrived with a cracked band",
                     "approve the refund, send a return label")
for field, value in card.items():
    print(f"{field}: {value}")
weak  : customer is upset, please help
customer_id: C-77
root_cause: headphones arrived with a cracked band
refund_amount: 49.0
recommended_action: approve the refund, send a return label

The first line is the weak handoff: customer is upset, please help. The human has no customer, no cause and no amount, so they start from zero and ask the customer everything again. The card below it fixes that. customer_id comes from the order, root_cause is what the agent found out, refund_amount is read from the data so nobody has to guess it, and recommended_action is the next move. With those four lines, a person can start in seconds.

Please help versus a four-field card Weak handoff "customer is upset, please help" who? why? how much? Handoff card customer_id: C-77 root_cause: headphones arrived with a cracked band refund_amount: 49.0 recommended_action: approve the refund, send a return label
A handoff has to stand on its own, without the chat.

How this shows up in a question

A scenario says refunds must never go out before the customer is verified, the prompt already says to verify first, and yet a few refunds went out. Writing the rule in capital letters or adding examples is still a prompt, so it can still miss. Asking Claude to double-check after each refund acts after the money has left. The fix is a gate that blocks process_refund until an id is verified. Clue words that point to a gate: must always, never, before, compliance.

Common mistakes

  • Strengthening the prompt for a must-hold rule. A louder sentence is still a sentence.
  • Checking after the action. A post-refund review can't bring the money back. The gate runs before.
  • Gating on the call, not the result. Sequence C shows why: a lookup of an unknown id must not count as verification.
  • Blocking without a reason. Return what to do instead (call get_customer first), so the model can recover.
  • Handing off "please help". Send customer id, root cause, amount and recommended action.

Quick recap

SituationTool for the job
Rules that don't have to hold every single timePrompt guidance (the rest stays in the prompt)
A step that must come first, every timeProgrammatic gate before the tool (a PreToolUse hook in the Agent SDK)
Two requests in one messageSplit, investigate in parallel with shared context, one reply
Escalating to a personFour-field card: customer_id, root_cause, refund_amount, recommended_action

Prompts guide. Gates guarantee. The project files for this lesson are in the community, free to join.

Try it yourself

Add a second rule to gate: block refunds above a limit. You'll need the amount, so look it up from DATA["orders"] with the order id. Add a sequence D that verifies C-77 and then asks for a refund that breaks the limit, and predict the printout before you run it. Then drop refund_amount from the handoff card and ask yourself what the human now has to go and find.

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 · 122 of 123

Previous
Task Decomposition: a Fixed Prompt Chain With an Integration Pass, or a Dynamic Plan That Adapts
Next post
Scoped Tools per Agent and tool_choice: Three to Five Tools per Role, a Shared One, and auto, any or a Forced Tool

Related course on Udemy

Claude Certified Architect - Foundations (CCAR-F) Exam Prep

Agentic loops, tools, MCP, Claude Code, prompts, structured output and context.View on Udemy ↗: Claude Certified Architect - Foundations (CCAR-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 sign asks, a lock decides
  • gate.py: a prerequisite gate in 26 lines
  • Three call sequences
  • Two requests in one message
  • A handoff card that stands alone
  • How this shows up in a question
  • 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 Architect - Foundations (CCAR-F) Exam Prep

Agentic loops, tools, MCP, Claude Code, prompts, structured output and context.View on Udemy ↗: Claude Certified Architect - Foundations (CCAR-F) Exam Prep (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.