A human-in-the-loop agent stops before a risky tool call, shows a person exactly what it is about to do, and only runs the call after that person says yes. To build one, decide which tools are risky, pause the run and save its state instead of blocking a process, tie each approval to the exact arguments that were shown, and resume. Three major agent SDKs have it built in: needs_approval in the OpenAI Agents SDK, interrupt() in LangGraph, and canUseTool in the Claude Agent SDK. This post covers the design and then each SDK. The plain Python, OpenAI and LangGraph examples were run against current package versions.
Why risky calls need a person
OWASP's Top 10 for LLM applications lists this as LLM06, Excessive Agency: the vulnerability "that enables damaging actions to be performed in response to unexpected, ambiguous or manipulated outputs from an LLM." It names three root causes: excessive functionality, excessive permissions and excessive autonomy. One of its mitigations is to "require a human to approve high-impact actions before they are taken."
The Model Context Protocol says the same from the tool side. The tools specification says that for trust and safety, there should always be a human in the loop with the ability to deny tool invocations, and that clients should show tool inputs to the user before calling the server, to avoid malicious or accidental data exfiltration.
Approval is one control, not the whole fix. OWASP also lists "complete mediation": implement authorization in downstream systems "rather than relying on an LLM to decide if an action is allowed or not." Keep the refund API's own limits and permissions in place. The approval step sits in front of them.
Step 1: Sort tools by risk
Asking about every call trains people to click yes without reading. Ask only where a mistake is expensive. A simple split works for most agents:
- Read: searches and lookups. No approval.
- Reversible write: a draft, a note, a label. Usually no approval, but log it.
- Irreversible or external: money, deletions, messages to other people, anything outside your system. Approval.
Make the rule a function, not a list in the prompt, and make it fail closed:
RISK = {
"search_orders": "read",
"add_order_note": "write",
"issue_refund": "irreversible",
"delete_account": "irreversible",
}
def needs_approval(tool: str, args: dict) -> bool:
"""Unknown tools count as irreversible, so a new tool can't slip through."""
level = RISK.get(tool, "irreversible")
if tool == "issue_refund":
return args.get("amount_cents", 0) > 5_000
return level == "irreversible"
needs_approval("issue_refund", {"amount_cents": 12000}) returns True, a search returns False, and a tool nobody added to the table returns True. Note the refund rule looks at the arguments: a $30 refund runs on its own, a $120 one waits.
If your tools come from MCP servers, their annotations can help you fill the table. The MCP Python SDK's ToolAnnotations has read_only_hint, destructive_hint, idempotent_hint and open_world_hint, and its docstring says these are hints that clients should never base tool use decisions on when they come from untrusted servers. The specification says the same. Use them as a starting point for servers you run yourself. Build an MCP server in Python shows how to set them.
Step 2: Pause, save, resume
A person might answer in ten seconds or ten hours. Don't hold a process open waiting. Save the run's state, end the request, and resume when the decision comes in.
Two details make this safe. First, bind the approval to the exact call: hash the tool name and arguments when you ask, and refuse to run anything with a different hash. Second, approve a call once. Mark it executed before running it, and pass a stable idempotency key to the downstream API so a retry can't charge twice.
import hashlib
import json
import uuid
from dataclasses import dataclass, field
def fingerprint(tool: str, args: dict) -> str:
"""Hash of the exact call, so an approval can't be reused for other arguments."""
blob = json.dumps({"tool": tool, "args": args}, sort_keys=True)
return hashlib.sha256(blob.encode()).hexdigest()
@dataclass
class PendingCall:
tool: str
args: dict
fingerprint: str
id: str = field(default_factory=lambda: uuid.uuid4().hex)
status: str = "pending" # pending, approved, rejected, executed
class ApprovalGate:
def __init__(self) -> None:
self.pending: dict[str, PendingCall] = {} # use a database in production
def request(self, tool: str, args: dict) -> PendingCall:
call = PendingCall(tool, args, fingerprint(tool, args))
self.pending[call.id] = call
return call
def decide(self, call_id: str, approved: bool) -> PendingCall:
call = self.pending[call_id]
if call.status != "pending":
raise ValueError(f"Call {call_id} was already {call.status}")
call.status = "approved" if approved else "rejected"
return call
def execute(self, call_id: str, tool: str, args: dict, run) -> str:
call = self.pending[call_id]
if call.status != "approved":
raise PermissionError(f"Call {call_id} is {call.status}, not approved")
if fingerprint(tool, args) != call.fingerprint:
raise PermissionError("Arguments changed after approval")
call.status = "executed" # mark first, so a retry can't run it twice
return run(**args, idempotency_key=call.id)
After approving a $120 refund, calling execute with the amount changed to $990 raises Arguments changed after approval. The original call runs once, and a second execute raises is executed, not approved. In production, the status change must be atomic in your database, so two requests can't both see approved.
You rarely need to write this from scratch. The SDKs below handle the pause and resume. Keep the fingerprint and idempotency ideas, because they still apply.
OpenAI Agents SDK: needs_approval
In the OpenAI Agents SDK, function_tool takes needs_approval, either True or an async function that receives the run context, the parsed arguments and the call ID and returns a bool. When a call needs approval, the run stops and result.interruptions lists the pending items. Convert the result to a RunState, approve or reject each item, and run again with the state. This was run with openai-agents 0.24.0:
from agents import Agent, Runner, RunState, function_tool
REFUND_LIMIT_CENTS = 5_000
async def refund_needs_review(_ctx, params, _call_id) -> bool:
"""Small refunds run on their own; anything larger waits for a person."""
return params.get("amount_cents", 0) > REFUND_LIMIT_CENTS
@function_tool(needs_approval=refund_needs_review)
def issue_refund(order_id: str, amount_cents: int) -> str:
"""Refund part or all of an order, in cents."""
return f"Refunded {amount_cents} cents on {order_id}"
agent = Agent(name="Support", instructions="Help with orders.", tools=[issue_refund])
async def handle(user_input: str) -> str:
result = await Runner.run(agent, user_input)
while result.interruptions:
state = result.to_state()
saved = state.to_string() # store this while the person decides
state = await RunState.from_string(agent, saved)
for item in state.get_interruptions():
if await ask_reviewer(item.tool_name, item.arguments): # your UI
state.approve(item)
else:
state.reject(
item,
rejection_message="Refunds over $50 need a manager. Offer store credit.",
)
result = await Runner.run(agent, state)
return result.final_output
With a $120 request, the run paused with issue_refund {"order_id": "A-1001", "amount_cents": 12000}. After a rejection, the tool's output in the history was the rejection message, which is what the model reads next. A $30 request ran without pausing.
The SDK docs add points worth knowing:
- If the arguments can't be parsed safely, such as malformed JSON, your function isn't called and the call requires manual approval.
approve(item, always_approve=True)makes the decision sticky for later calls to the same tool. For shell and apply_patch tools, sticky decisions match by tool type and name, so they can carry across a handoff to another agent. Use per-call decisions there.RunState.from_stringrestores state but does not authenticate it. Load only snapshots your server stored.
LangGraph: interrupt() and Command(resume=...)
In LangGraph, a node calls interrupt() with a JSON-serializable payload, and the graph pauses. You need a checkpointer and a thread_id in the config. Resume by invoking the graph again with Command(resume=value) on the same thread; that value becomes the return value of interrupt(). This ran with langgraph 1.2.22:
from typing import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt
class State(TypedDict):
order_id: str
amount_cents: int
result: str
def refund(state: State) -> dict:
# Everything above interrupt() runs again on resume, so keep it side-effect free.
decision = interrupt({
"action": "issue_refund",
"order_id": state["order_id"],
"amount_cents": state["amount_cents"],
})
if decision.get("approved"):
# Call the refund API here, after the person said yes.
return {"result": f"Refunded {state['amount_cents']} cents"}
return {"result": f"Rejected: {decision.get('reason', 'no reason given')}"}
builder = StateGraph(State)
builder.add_node("refund", refund)
builder.add_edge(START, "refund")
builder.add_edge("refund", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "refund-A-1001"}}
first = graph.invoke({"order_id": "A-1001", "amount_cents": 12000}, config)
print(first["__interrupt__"][0].value)
final = graph.invoke(Command(resume={"approved": False, "reason": "over limit"}), config)
print(final["result"]) # Rejected: over limit
The comment in the node is the rule that catches people. LangGraph's docs say the node restarts from the beginning on resume, so code before interrupt() runs twice. Put side effects after it, make them idempotent, or move them to their own node. The docs also warn against wrapping interrupt() in a bare try/except, because the pause works by raising a special exception. The docs say to use a durable checkpointer in production; InMemorySaver keeps checkpoints only in process memory.
Claude Agent SDK: canUseTool and hooks
The Claude Agent SDK checks every tool request in a fixed order: hooks, deny rules, ask rules, the permission mode, allow rules, and finally your canUseTool callback (can_use_tool in Python). The callback gets the tool name and its input and returns allow or deny:
from claude_agent_sdk.types import PermissionResultAllow, PermissionResultDeny
RISKY = {"Bash", "Write", "Edit"}
async def can_use_tool(tool_name, input_data, context):
if tool_name not in RISKY:
return PermissionResultAllow(updated_input=input_data)
if await ask_reviewer(tool_name, input_data): # your UI
return PermissionResultAllow(updated_input=input_data)
return PermissionResultDeny(message="The user declined this action.")
Pass it as ClaudeAgentOptions(can_use_tool=can_use_tool). The docs' Python example streams the prompt and registers a no-op PreToolUse hook, described as a required workaround that keeps the stream open for the callback. Claude sees the deny message and may adjust its approach.
The trap is the order. The docs warn that auto-approved tools never reach canUseTool: a call approved by an allow rule, by acceptEdits or by bypassPermissions skips your callback, so checks you put there are silently bypassed. They also note that allowed_tools does not constrain bypassPermissions. For a check that must run on every call, use a PreToolUse hook, which runs first and whose deny applies even in bypassPermissions mode. The same kind of hook works in Claude Code itself; Claude Code hooks: block risky commands has a tested example. The callback can also stay pending indefinitely. If a person may take longer than your process can wait, the docs suggest a PreToolUse hook that returns a defer decision, so the process can exit and resume later from the saved session.
Make the approval screen honest
An approval is only as good as what the reviewer saw. The OpenAI Agents SDK docs list server-side rules that apply to any framework:
- Authenticate the reviewer. Don't trust an identity in the request body.
- Check that the reviewer may decide on that run and those calls.
- Validate decisions against the pending items your server stored, not tool calls or arguments the client sends back.
- Consume each decision atomically, so one request can't resume the same snapshot twice.
- Treat tool names and arguments as untrusted when you render them, and escape them in HTML.
Show the full arguments, not the model's summary of them. A model that was manipulated, for example by a prompt injection hidden in a page it read, can describe a call one way and make it another. The fingerprint check in Step 2 is the code version of the same rule.
When the answer is no
A rejection should tell the model what to do instead, or the agent may retry the same call with small changes. "Refunds over $50 need a manager. Offer store credit." gives it a next step. Count rejections per run as well, and stop after a few: debugging agent loops covers repeat detection, and a model that keeps proposing a rejected call often has an unclear tool, which why your agent calls the wrong tool covers.
Finally, measure it. Track how often each tool is sent for approval and how often people reject it. A tool that is approved every time may not need the step; one that is often rejected needs a better description or a narrower scope. Add rejected cases to your agent evals.
Checklist
- List every tool with a risk level; unknown tools need approval.
- Base the rule on arguments too, such as an amount limit.
- Pause and save state; never hold a process open for a person.
- Show the reviewer the exact tool name and arguments, escaped.
- Bind each approval to a hash of the call and use it once.
- Send an idempotency key to any API that moves money or sends messages.
- In LangGraph, keep side effects after
interrupt(). - In the Claude Agent SDK, put must-run checks in a
PreToolUsehook. - Write rejection messages that give the model a next step.
- Keep authorization in the downstream system as well.
FAQ
What is a human-in-the-loop agent?
It is an agent that pauses before certain actions and waits for a person to approve, reject or change them. OWASP recommends this for high-impact actions as a mitigation for excessive agency.
Which tool calls should need approval?
Calls that are hard to undo or reach outside your system: payments, deletions, messages to other people and changes to permissions. Reads and reversible drafts usually don't need it.
How does the OpenAI Agents SDK handle tool approval?
Set needs_approval on a function tool. The run returns interruptions; call to_state(), then approve() or reject() on each item, and pass the state back to Runner.run.
Why does my LangGraph node run twice after an interrupt?
On resume, LangGraph restarts the node from the beginning, so code before interrupt() runs again. Move side effects after the interrupt or into a separate node.
Can MCP tool annotations decide what needs approval?
Not on their own. The MCP specification says clients must treat annotations as untrusted unless they come from trusted servers. Use them as hints for servers you control.
Sources
- OWASP, LLM06:2025 Excessive Agency (OWASP Top 10 for LLM Applications)
- Model Context Protocol, Tools (specification, revision 2026-07-28)
- OpenAI Agents SDK, Human-in-the-loop (SDK documentation)
- LangChain, Interrupts (LangGraph documentation)
- Anthropic, Configure permissions (Claude Agent SDK documentation)
- Anthropic, Handle approvals and user input (Claude Agent SDK documentation)
- openai-agents on PyPI (package, version 0.24.0)
- langgraph on PyPI (package, version 1.2.22)
- mcp on PyPI (package,
ToolAnnotationsinmcp.types)