Originally published on tamiz.pro.
Your AI coding agent just opened a pull request that claims to "fix the flaky test suite." In reality, it deleted the CI configuration, bumped three dependencies to untrusted versions, and force-pushed to a release branch. Nobody noticed until the build broke in production. This is the bluffing problem: autonomous agents don't just make mistakes — they confidently assert work they never did, run commands they were never meant to run, and produce pull requests that look reasonable on the surface while hiding catastrophic changes underneath.
The fix is not to remove the agents. It's to put a tool gate between every agent and every tool it can touch. A tool gate is a policy-enforcing middleware layer that validates, scopes, logs, and sometimes blocks each tool invocation before it reaches the filesystem, the shell, or the remote Git host. This deep-dive explains how to design those gates so they survive adversarial agents, scale across a fleet of bots, and make autonomous pull requests safe to merge.
- 1. The Bluffing Problem: Why Agents Lie
- 2. Anatomy of a Tool Gate
- 3. Building the Gate: A Reference Implementation
- 4. Fleet-Wide Enforcement: Policy as Code
- 5. The Final Gate: Safe Autonomous Pull Requests
- 6. Observability: You Can't Audit What You Don't Log
- 7. Failure Modes and How to Survive Them
- 8. Best Practices Checklist
- Frequently Asked Questions
1. The Bluffing Problem: Why Agents Lie
"Bluffing" in the context of an AI coding agent isn't malicious deception. It's a structural consequence of how large language models interact with tools. An agent is a loop: it reads context, calls a tool, observes the result, and decides the next action. When that loop breaks down, the agent doesn't stop — it confabulates. It fills the gap with a plausible narrative.
1.1 The Three Bluff Patterns
Pattern 1: The Phantom Success. The agent runs a test command, the tool returns an error, but the agent's next message says "all tests pass." The model has seen "tests pass" thousands of times in training data and patterns it into the response. The tool result never made it into the context window, or it was truncated, so the model guessed.
Pattern 2: The Silent Skip. The agent decides to edit src/auth.ts, but the file path is wrong or the write fails silently. The agent proceeds to open a PR that references changes it never made. The diff is empty, yet the PR description claims a fix.
Pattern 3: The Escalation. The agent needs to install a package, so it runs npm install. That triggers a postinstall script. That script runs arbitrary shell code. The agent never intended to execute untrusted code, but the tool chain let it happen. The bluff is in the agent's assumption that npm install is a safe, scoped operation.
1.2 The Threat Model
Before you design a gate, enumerate what you're actually defending against. For a fleet of coding agents, the realistic threats are:
| Threat | Vector | Impact |
|---|---|---|
| Destructive Git commands | git reset --hard, git push --force | Lost work, broken branches, rewritten history |
| Secret exfiltration | Reading .env, id_rsa, cloud credentials | Credential leak, lateral movement |
| Supply-chain injection | npm install <malicious>, go get | Compromised dependencies shipped to prod |
| PR spam / flooding | Unlimited create_pr calls | Review queue collapse, CI resource exhaustion |
| Path traversal | Editing ../../etc/passwd or symlink targets | Host compromise, config tampering |
| Shell injection | run_command with unescaped args | Arbitrary code execution on the runner |
Notice that most of these aren't "AI failures" in the narrow sense — they're tool access failures. The agent was given a hammer and no one told it where the nails were. The gate is the instruction manual.
2. Anatomy of a Tool Gate
A tool gate sits between the agent's reasoning loop and the underlying tool implementations. It is not a prompt, not a system message, and not a "please be careful" instruction. It is a hard boundary enforced by code.
2.1 The Five Layers
A robust gate has five layers, each independently enforceable:
- Identity Layer — Who is calling? Each agent gets a unique ID, a scoped token, and a declared intent. No anonymous calls.
- Policy Layer — What is allowed? An allowlist of tools, a denylist of dangerous patterns, and argument schemas.
- Sandbox Layer — Where can it run? Path confinement, read-only mounts, network egress blocking, CPU/memory limits.
- Human Layer — What needs a human? Destructive or high-blast-radius operations require explicit approval, never auto-retry.
- Audit Layer — What happened? Every call is logged with a trace ID, the full argument set, the decision, and the outcome.
2.2 The Decision Flow
Agent → ToolCall { id, agentId, tool, args, cwd } │ ▼ ┌───────────────┐ │ 1. Identity │ Reject if agentId unknown or token expired └──────┬────────┘ ▼ ┌───────────────┐ │ 2. Policy │ Reject if tool not in allowlist, or └──────┬────────┘ args match denylist regex, or schema fails ▼ ┌───────────────┐ │ 3. Sandbox │ Reject if path escapes cwd, or network └──────┬────────┘ egress not permitted for this tool ▼ ┌───────────────┐ │ 4. Human │ If high-risk, require approval token. └──────┬────────┘ Otherwise auto-approve. ▼ ┌───────────────┐ │ 5. Execute │ Run in sandbox, capture stdout/stderr, └──────┬────────┘ return sanitized result to agent ▼ Audit Log (immutable) The key insight: the gate decides, the agent doesn't. The agent can ask for anything, but the gate is the only thing that can say yes.
3. Building the Gate: A Reference Implementation
Here's a minimal but realistic TypeScript implementation of the Policy and Sandbox layers. It's designed to wrap any tool-calling interface — including MCP (Model Context Protocol) servers, which are the de facto standard for agent tool exposure.
3.1 The Policy Definition
// policy.ts export interface ToolPolicy { name: string; // e.g. "run_command" allowArgs: RegExp[]; // each arg must match at least one denyArgs: RegExp[]; // any match = reject allowCwd: RegExp; // path must be inside this maxConcurrency: number; requiresApproval: boolean; timeoutMs: number; networkEgress: boolean; } const POLICIES: Record<string, ToolPolicy> = { "run_command": { name: "run_command", allowArgs: [/^[a-zA-Z0-9_\-./ ]+$/], // no shell metachars denyArgs: [ /\brm\s+-rf\b/i, // no recursive delete /\bgit\s+push\s+.*--force\b/i, // no force push /\bcurl\s+.*\|\s*(sh|bash)\b/i, // no curl | bash /\b(chmod|chown)\s+777\b/i, /\bsudo\b/i, /\b(nc|netcat|ncat)\b/i, ], allowCwd: /^\/workspace\//, maxConcurrency: 2, requiresApproval: false, timeoutMs: 30_000, networkEgress: false, }, "edit_file": { name: "edit_file", allowArgs: [/^[\w./-]+$/], denyArgs: [/\.\.\//, /\/etc\//, /\.env$/i, /\.ssh\//i], allowCwd: /^\/workspace\//, maxConcurrency: 5, requiresApproval: false, timeoutMs: 10_000, networkEgress: false, }, "create_pr": { name: "create_pr", allowArgs: [/^[\w\-./ ]+$/], denyArgs: [], allowCwd: /^\/workspace\//, maxConcurrency: 1, requiresApproval: true, // humans must approve PR creation timeoutMs: 60_000, networkEgress: true, }, }; 3.2 The Gate Class
// gate.ts import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; import { POLICIES, ToolPolicy } from "./policy"; export interface ToolCall { agentId: string; tool: string; args: string[]; cwd: string; } export interface GateResult { allowed: boolean; reason?: string; policy?: string; traceId: string; } const auditLog: Array<GateResult & { tool: string; agentId: string }> = []; function writeAudit(entry: GateResult & { tool: string; agentId: string }) { // In production, append to an immutable, append-only store (e.g. S3 + WORM) auditLog.push(entry); } export class ToolGate { constructor(private readonly allowedAgents: Set<string>) {} async execute(call: ToolCall): Promise<GateResult> { const traceId = randomUUID(); const policy = POLICIES[call.tool]; // Layer 1: Identity if (!this.allowedAgents.has(call.agentId)) { return this.deny(traceId, call, "unknown agent"); } // Layer 2: Policy existence if (!policy) { return this.deny(traceId, call, "tool not in allowlist"); } // Layer 2: Arg validation for (const arg of call.args) { if (!policy.allowArgs.some((re) => re.test(arg))) { return this.deny(traceId, call, `arg failed allowlist: ${arg}`); } if (policy.denyArgs.some((re) => re.test(arg))) { return this.deny(traceId, call, `arg matched denylist: ${arg}`); } } // Layer 3: Path confinement if (!policy.allowCwd.test(call.cwd)) { return this.deny(traceId, call, `cwd outside workspace: ${call.cwd}`); } // Layer 4: Human approval if (policy.requiresApproval) { const approved = await this.requestHumanApproval(call, traceId); if (!approved) { return this.deny(traceId, call, "human approval denied"); } } // Layer 5: Execute in sandbox try { const output = await this.runInSandbox(call, policy); const result: GateResult = { allowed: true, traceId, policy: policy.name }; writeAudit({ ...result, tool: call.tool, agentId: call.agentId }); return result; } catch (err) { return this.deny(traceId, call, `execution failed: ${(err as Error).message}`); } } private deny(traceId: string, call: ToolCall, reason: string): GateResult { const result: GateResult = { allowed: false, reason, traceId }; writeAudit({ ...result, tool: call.tool, agentId: call.agentId }); return result; } private async requestHumanApproval(call: ToolCall, traceId: string): Promise<boolean> { // In production: post to Slack/Teams, wait for webhook, with a 5-min TTL. // Never auto-approve. Never retry on timeout. console.log(`[HUMAN APPROVAL REQUIRED] ${traceId}: ${call.tool} ${call.args.join(" ")}`); return false; // default deny unless a human explicitly approves } private runInSandbox(call: ToolCall, policy: ToolPolicy): Promise<string> { return new Promise((resolve, reject) => { // Use execFile, not exec — no shell, no interpolation, no injection. const child = spawn(call.args[0], call.args.slice(1), { cwd: call.cwd, timeout: policy.timeoutMs, env: { PATH: "/usr/bin:/bin", HOME: "/tmp" }, stdio: ["ignore", "pipe", "pipe"], }); let stdout = ""; let stderr = ""; child.stdout.on("data", (d) => (stdout += d)); child.stderr.on("data", (d) => (stderr += d)); child.on("error", reject); child.on("close", (code) => { if (code !== 0) reject(new Error(stderr || `exit ${code}`)); else resolve(stdout); }); }); } } What this code does, layer by layer:
-
allowedAgentsenforces that only registered bot identities can even attempt a call. Unregistered agents get a harddeny. - The
POLICIESmap is the allowlist. If a tool isn't in there, it doesn't exist for the agent. No fallback, no "default allow." -
denyArgsare compiled regular expressions that catch the classic destructive patterns:rm -rf,git push --force,curl | bash,chmod 777,sudo,nc. This is defense-in-depth against both hallucinated commands and prompt-injected commands. -
allowCwdconfines every operation to/workspace/. The agent literally cannot touch files outside its sandbox. -
requiresApprovaloncreate_prmeans the agent can do all the work, but a human must click "approve" before a PR is opened. No auto-approval, no TTL-based silent approval. -
runInSandboxusesspawnwithexecFilesemantics — no shell is invoked, so there's no;,&&,|, or backtick injection possible. The environment is stripped to a minimalPATHand a writable/tmp.
3.3 Wrapping an MCP Server
If you're using MCP, you wrap the server's tool handlers so every request flows through the gate:
// mcp-gate.ts import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { ToolGate } from "./gate"; const gate = new ToolGate(new Set(["agent-alpha", "agent-beta"])); const server = new Server( { name: "gated-agent", version: "1.0.0" }, { capabilities: { tools: {} } } ); server.setRequestHandler(ListToolsRequestSchema, async () => { // Only expose tools that pass the allowlist — the agent never even // sees the ones it can't use. return { tools: Object.keys(POLICIES).map((name) => ({ name, description: `Gated tool: ${name}`, inputSchema: { type: "object", properties: { args: { type: "array" } } }, })), }; }); server.setRequestHandler(CallToolRequestSchema, async (req) => { const { name, arguments: args } = req.params; const result = await gate.execute({ agentId: req.session?.agentId ?? "unknown", tool: name, args: (args as string[]) ?? [], cwd: process.env.WORKSPACE ?? "/workspace", }); if (!result.allowed) { return { content: [{ type: "text", text: `BLOCKED: ${result.reason}` }], isError: true }; } // ... execute the real tool here, return sanitized output return { content: [{ type: "text", text: "ok" }] }; }); The agent only sees the tools in the allowlist. It can't even attempt to call a tool that isn't gated, because the tool doesn't appear in its capability list. This is the most effective way to shrink the attack surface: don't advertise what you don't want used.
4. Fleet-Wide Enforcement: Policy as Code
A single gate is easy. The hard part is rolling the same guarantees out to 500 agents across 40 repositories without drift. The answer is policy as code: a versioned, signed, centrally-distributed policy document that every gate pulls and validates before it starts.
4.1 The Policy Document
# agent-policy.yaml version: "2025.01" signature: "ed25519:base64..." agents: - id: agent-alpha repos: ["acme/web", "acme/api"] maxOpenPRs: 2 maxConcurrentCalls: 4 - id: agent-beta repos: ["acme/infra"] maxOpenPRs: 1 maxConcurrentCalls: 2 extraDenyArgs: - /\bterraform\s+apply\b/ - /\bkubectl\s+apply\b/ tools: run_command: allowArgs: [/^[a-zA-Z0-9_\-./ ]+$/] denyArgs: - /\brm\s+-rf\b/ - /\bgit\s+push\s+.*--force\b/ - /\bcurl\s+.*\|\s*(sh|bash)\b/ allowCwd: "/workspace/*" timeoutMs: 30000 networkEgress: false create_pr: requiresApproval: true maxPerHour: 3 denyArgs: - /\b--draft\b/ # agents can't open draft PRs either 4.2 Distribution and Validation
Every gate instance polls a policy registry (Git repo, OCI artifact, or object store) on a short interval. The policy is signed with Ed25519; the gate verifies the signature before applying it. If the signature fails, the gate fails closed — it refuses to execute any tool until a valid policy is loaded.
// policy-loader.ts import { verify } from "node:crypto"; const PUBLIC_KEY = process.env.POLICY_PUBLIC_KEY!; async function loadAndVerifyPolicy(url: string): Promise<AgentPolicy> { const res = await fetch(url); const raw = await res.text(); const doc = parseYaml(raw); const valid = verify( "ed25519", Buffer.from(doc.Source:https://dev.to/tamizuddin/stop-your-ai-agents-bluffing-designing-safe-tool-gates-for-autonomous-pull-requests-and-fleet-wide-2lda