The guard belongs at the one place every tool call passes through before it runs: your agent loop, your MCP client or gateway, or the tool proxy of a code-mode sandbox. Each recipe below is short on purpose; adapt the names to your framework.
Send the intent and the trigger. Most unsafe tool calls are only unsafe relative to what the user asked. Pass the user request as intent, and set trigger: "tool_result" whenever the call may come from a tool output, a web page, an email or a document rather than from the user. This is how prompt injection is caught: left out, trigger means user_request, and an injected call looks like something the user asked for.
02
Fail to a human, not open. When the guard is unreachable, times out or returns an error, every recipe treats the call as ask; a 503 body says so too (fallback_verdict: "ask"). Failed calls are never billed. See timeouts and failover for how long to wait.
03
Keep your deterministic rules. Allow-lists, least-privilege credentials and sandboxes still come first; the guard is one layer and reduces risk, it does not remove it.
Check each tool call the model proposes, then run it on allow, ask the user on ask, and hand the model an error on block so it can re-plan. The same pattern fits any framework with a before-tool callback.
01
Check each call before it runs
TypeScriptts
const GUARD_URL = "https://api.mcp-guard.ai/v1/guard";
type Guard = { verdict: "allow" | "ask" | "block"; p_unsafe: number; reasons: string[] };
export async function guard(check: Record<string, unknown>): Promise<Guard> {
try {
const res = await fetch(GUARD_URL, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.MCP_GUARD_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(check),
// 10 s covers a failover to the backup GPUs, unless one has to cold-start
// (tens of seconds); then this returns "ask" below.
signal: AbortSignal.timeout(10_000),
});
if (res.ok) return await res.json();
// 5xx / 429: nothing was charged, and the error body says fallback_verdict: "ask".
return { verdict: "ask", p_unsafe: 1, reasons: [`guard returned HTTP ${res.status}`] };
} catch {
return { verdict: "ask", p_unsafe: 1, reasons: ["guard unreachable or timed out"] }; // fail to a human
}
}
// In the agent loop, before running the tool calls the model proposed.
// readToolOutput: has the model read any tool output (a web page, an email, a file,
// search results) since the user's last message? Then the call may come from that content.
for (const call of toolCalls) {
const g = await guard({
action: { tool: call.name, args: call.input },
intent: userRequest, // what the user asked for
trigger: readToolOutput ? "tool_result" : "user_request",
context: "Support agent. Environment: production.",
});
if (g.verdict === "block" || (g.verdict === "ask" && !(await askUser(call, g.reasons)))) {
results.push({ id: call.id, error: `Not run (${g.verdict}): ${g.reasons.join(", ")}` });
continue;
}
results.push({ id: call.id, output: await runTool(call) });
}
02
Batch a multi-call plan
A plan with several calls? Send them together to POST /v1/guard/batch (up to 64 checks, one result each, in order) before running any of them.
Claude Code runs a PreToolUse hook before every matching tool call. This script sends the call and your latest message to the guard, then answers deny on block and ask on ask. On allow it says nothing, so your normal permission rules still apply. If the guard cannot answer within 10 seconds, or answers with an error, the hook answers ask so you decide; it never lets the call through silently. Save it as .claude/hooks/mcp_guard.py and set MCP_GUARD_API_KEY in your environment.
01
Save the hook script
The hook marks a call tool_result when Claude has read tool output (files, pages, command output) since your last message. That is deliberately cautious: in a long task most calls are checked as possibly driven by what Claude read, which is where injected instructions come from.
.claude/hooks/mcp_guard.pypython
#!/usr/bin/env python3
"""Claude Code PreToolUse hook: check each tool call with MCP Guard before it runs."""
import json, os, sys, urllib.request
event = json.load(sys.stdin)
key = os.environ.get("MCP_GUARD_API_KEY")
if not key:
sys.exit(0) # not set up: leave Claude Code's normal permission rules in charge
def answer(decision, reason):
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": decision,
"permissionDecisionReason": reason,
}}))
def read_transcript(path):
"""(latest text the user typed, whether Claude read tool output after it), best effort."""
try:
with open(path) as f:
entries = [json.loads(line) for line in f if line.strip()]
except (OSError, ValueError):
return None, True # unknown: assume tool output was involved
read_tool_output = False
for e in reversed(entries):
m = e.get("message") or {}
if e.get("type") != "user" or m.get("role") != "user":
continue
c = m.get("content")
blocks = [{"type": "text", "text": c}] if isinstance(c, str) else [b for b in c or [] if isinstance(b, dict)]
if any(b.get("type") == "tool_result" for b in blocks):
read_tool_output = True
continue
text = "\n".join(b.get("text", "") for b in blocks if b.get("type") == "text")
if text.strip():
return text[-2000:], read_tool_output
return None, read_tool_output
intent, read_tool_output = read_transcript(event.get("transcript_path", ""))
check = {
"action": {"tool": event["tool_name"], "args": event.get("tool_input", {})},
# tool_result: Claude has read tool output (files, pages, command output) since your
# last message, so this call may come from that content rather than from you.
"trigger": "tool_result" if read_tool_output else "user_request",
"context": f"Claude Code coding agent, working directory {event.get('cwd', '?')}",
}
if intent:
check["intent"] = intent
req = urllib.request.Request(
"https://api.mcp-guard.ai/v1/guard",
data=json.dumps(check).encode(),
headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(req, timeout=10) as r: # keep below the hook timeout (15 s)
g = json.load(r)
except Exception as e:
# Unreachable, timed out or an HTTP error (nothing is charged then): fail to you, not open.
answer("ask", f"MCP Guard unavailable ({e}); confirm this call yourself")
sys.exit(0)
decision = {"block": "deny", "ask": "ask"}.get(g["verdict"]) # allow: no opinion
if decision:
reasons = ", ".join(g["reasons"]) or "no specific reason"
answer(decision, f"MCP Guard {g['verdict']} (p_unsafe {g['p_unsafe']}): {reasons}")
In .claude/settings.json (one project) or ~/.claude/settings.json (everywhere). The matcher picks the tools worth checking; read-only tools such as Read and Grep can skip the round trip. Keep the hook timeout (15 s) above the script's own 10 s request timeout, so the script always gets to answer ask before Claude Code gives up on it.
Prefer to let Claude call the guard itself? Connect the MCP server instead; the hook is the stronger option because it runs on every call, whether or not the model remembers to ask.
In code mode the model writes a script that calls your tools, and the script can fire dozens of calls that no human reads. Every one of them goes through the sandbox's tool binding, so wrap that binding once and each call is checked before it runs.
01
Wrap the sandbox's tool binding
guarded-tools.tsts
import { guard } from "./guard"; // the helper from the agent-loop recipe
type Tools = Record<string, (args: unknown) => Promise<unknown>>;
/** Wrap the tools a code-mode sandbox exposes: every call the generated code makes is checked first. */
export function guardedTools<T extends Tools>(
tools: T,
ctx: {
intent: string;
context?: string;
/** "tool_result" if the model wrote the code after reading tool output or a document. */
trigger?: "user_request" | "tool_result";
confirm?: (tool: string, reasons: string[]) => Promise<boolean>;
},
): T {
// Once any call has returned, later calls may act on what it returned (an email,
// a page, a file), so from then on they are checked as tool_result.
let readToolOutput = ctx.trigger === "tool_result";
return new Proxy(tools, {
get(target, name) {
const fn = target[name as keyof T];
if (typeof name !== "string" || typeof fn !== "function") return fn;
return async (args: unknown) => {
const g = await guard({
action: { tool: name, args },
intent: ctx.intent,
context: ctx.context,
trigger: readToolOutput ? "tool_result" : "user_request",
});
const ok = g.verdict === "allow" || (g.verdict === "ask" && (await ctx.confirm?.(name, g.reasons)));
if (!ok) throw new Error(`MCP Guard ${g.verdict}: ${name} not run (${g.reasons.join(", ") || "unsafe"})`);
const out = await fn(args);
readToolOutput = true;
return out;
};
},
});
}
// The model wrote `code`; run it with checked tools. With no confirm(), "ask" fails closed.
await sandbox.run(code, { tools: guardedTools(tools, { intent: userRequest, context: "Environment: production." }) });
02
What the script sees
A blocked call throws inside the script, like any failing tool, so the model sees the reason and can try something else. After the first call returns, the proxy checks the rest as tool_result: from then on the script may be acting on what a tool returned. Latency is roughly 15 ms of model time per check on our GPUs plus your network round trip (about 100 ms from Europe), so a script with many calls may prefer to pre-check its planned calls in one /v1/guard/batch request.