Originally published on tamiz.pro.
An AI agent can produce a perfectly plausible tool call that your runtime happily executes: a SQL statement against the wrong table, a shell command with an unexpected flag, a payment request for the wrong amount. The model was not "lying" in a moral sense; it was optimizing for a plausible next step, and plausibility is not correctness.
The fix is to move authorization and policy decisions out of the model's discretion and into a deterministic layer that sits between the agent and every side-effecting tool. This layer is often called a tool-decider gate. It parses structured tool calls, evaluates them against explicit, testable rules, and either returns an execution plan, a correction request, or a hard denial.
This tutorial builds that gate for a real agent workflow using TypeScript, Zod, and a small policy engine. The result is not merely a safer agent; it is an auditable one, where every decision has a machine-readable reason code and a replayable evidence trail.
- 1. The Core Problem: Plausible Calls Are Not Valid Calls
- 2. Architecture: Where the Gate Belongs
- 3. Prerequisites
- 4. Project Setup
- 5. Defining a Typed Tool Contract
- 6. Building the Deterministic Decider
- 7. Writing Policy Rules
- 8. Integrating the Gate with an Agent Loop
- 9. Handling Denials and Repairs
- 10. Auditing Every Decision
- 11. Testing the Gate
- 12. Production Hardening
- 13. Frequently Asked Questions
1. The Core Problem: Plausible Calls Are Not Valid Calls
Most agent frameworks assume the model emits a tool call and the runtime executes it. That assumption is fine for read-only tools with no sensitive parameters. It breaks down when a tool can mutate state, spend money, delete data, or reach an internal network.
Consider a customer-support agent asked to "refund order A-1042 for $49.00." A model might emit:
{ "tool": "issue_refund", "args": { "orderId": "A-1042", "amount": 4900, "currency": "USD", "reason": "customer_request" } } That looks correct. Now consider the same agent under a slightly different prompt, where the model confuses cents and dollars:
{ "tool": "issue_refund", "args": { "orderId": "A-1042", "amount": 49, "currency": "USD", "reason": "customer_request" } } The second call is structurally valid, semantically wrong, and will happily refund $0.49 while reporting $49.00 to the customer. No schema validator catches this. No prompt makes it reliably safe.
The general failure mode is that language models are probabilistic generators of text-shaped actions, while production systems require deterministic acceptance criteria over structured actions. The gap between the two is where bluffs become incidents.
A tool-decider gate narrows that gap by enforcing four properties:
- Type validity — the call matches a declared tool schema.
- Contextual validity — the call satisfies constraints derived from the current task, session, and environment.
- Authority validity — the call is permitted for this agent, this user, and this step.
- Evidence validity — the call references facts that the system can independently verify, not facts the model asserted.
The gate must be ordinary code. It must never ask a model whether it thinks the call is safe.
2. Architecture: Where the Gate Belongs
The gate is a chokepoint. Every tool call, whether generated by a model, a planner, a sub-agent, or a human-facing UI, passes through it.
User Request | v [ Agent / Planner (LLM) ] | | proposed tool call (structured) v [ Tool-Decider Gate ] <-- schemas, policy rules, context, allowlists | | | | | | | +--> DENY: hard block, no execution | | +-----> REPAIR: return structured correction request | +--------> ALLOW: emit execution plan v [ Executor / Sandbox ] | v [ Tool (DB, API, shell, browser, payments) ] | v [ Audit Log ] <-- decision, rule IDs, evidence hashes, outcome Two design rules follow immediately.
The gate returns decisions, not just booleans. A boolean false tells the agent nothing useful. A structured denial tells it exactly which field failed, what constraint applies, and what it must do next. That distinction is what turns a gate from a wall into a feedback loop.
The executor trusts only the gate's output. The executor should never re-derive policy, and the model should never be able to construct an execution plan directly. If the agent can bypass the gate, the gate is decoration.
A useful mental model: the LLM is a proposal engine, and the gate is the compiler front end. The model's output is untrusted source code. The gate performs type checking, semantic analysis, and admission control before anything runs.
3. Prerequisites
You will need:
- Node.js 20 or later
- npm 10 or later
- Basic TypeScript familiarity
- A terminal
You do not need an LLM API key to build and test the gate. That is deliberate: policy logic that depends on a network call is not deterministic, and deterministic policy logic should be testable offline.
4. Project Setup
Create the project and install dependencies:
mkdir tool-decider-gate && cd tool-decider-gate npm init -y npm install zod npm install -D typescript tsx @types/node vitest npx tsc --init Configure tsconfig.json:
{ "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "strict": true, "noUncheckedIndexedAccess": true,\n "exactOptionalPropertyTypes": true,\n "outDir": "dist", "rootDir": "src", "declaration": true, "sourceMap": true, "esModuleInterop": true, "skipLibCheck": true }, "include": ["src/**/*.ts", "tests/**/*.ts"] } Set the package to ESM and add scripts:
npm pkg set type=module npm pkg set scripts.build="tsc -p tsconfig.json" npm pkg set scripts.test="vitest run" npm pkg set scripts.dev="tsx src/demo.ts" Create the source layout:
mkdir -p src/tools src/policy src/gate src/audit tests 5. Defining a Typed Tool Contract
Tools are declared once, and that declaration drives three things: validation, the policy gate's type narrowing, and the agent-facing schema. One source of truth prevents the classic failure where the prompt describes a tool differently from the runtime.
Create src/tools/registry.ts:
import { z } from "zod"; /** Amounts are always integer minor units (cents). */ export const refundArgsSchema = z.object({ orderId: z.string().regex(/^[A-Z]{1,3}-\d{4,10}$/, "Invalid order ID format"), amount: z.number().int().positive().max(100_000), currency: z.enum(["USD", "EUR", "GBP"]), reason: z.enum(["customer_request", "damaged_item", "duplicate_charge"]), idempotencyKey: z.string().min(8).max(128), }); export type RefundArgs = z.infer<typeof refundArgsSchema>; export const searchOrdersArgsSchema = z.object({ customerEmail: z.string().email(), limit: z.number().int().min(1).max(50).default(10), }); export type SearchOrdersArgs = z.infer<typeof searchOrdersArgsSchema>; export const sendEmailArgsSchema = z.object({ to: z.string().email(), subject: z.string().min(1).max(200), body: z.string().min(1).max(10_000), }); export type SendEmailArgs = z.infer<typeof sendEmailArgsSchema>; /** * A tool definition carries its schema plus metadata used by the policy layer. * The policy layer reads metadata; it never re-parses raw model output. */ export interface ToolDefinition< Args extends z.ZodTypeAny, Result, > { name: string; description: string; argsSchema: Args; /** Side-effecting tools require an explicit authorization decision. */ effect: "read" | "write" | "destructive"; /** Tools that must never be reachable without a human confirmation token. */ requiresHumanApproval?: boolean; execute: (args: z.infer<Args>, ctx: ExecutionContext) => Promise<Result>; } export interface ExecutionContext { requestId: string; actorId: string; agentRole: string; /** Facts the gate can verify independently of the model. */ facts: Record<string, unknown>; /** A short-lived token proving a human approved this specific action. */ approvalToken?: string; now: Date; } export const issueRefundTool: ToolDefinition<typeof refundArgsSchema, { refundId: string }> = { name: "issue_refund", description: "Issue a refund to a customer for an existing order.", argsSchema: refundArgsSchema, effect: "write", requiresHumanApproval: true, async execute(args, ctx) { // Replace with a real payments API call. return { refundId: `rf_${ctx.requestId}_${args.orderId}` }; }, }; export const searchOrdersTool: ToolDefinition<typeof searchOrdersArgsSchema, { orderIds: string[] }> = { name: "search_orders", description: "Look up a customer's recent orders.", argsSchema: searchOrdersArgsSchema, effect: "read", async execute(args) { // Replace with a real database query. return { orderIds: ["A-1042"] }; }, }; export const sendEmailTool: ToolDefinition<typeof sendEmailArgsSchema, { messageId: string }> = { name: "send_email", description: "Send an email to the customer.", argsSchema: sendEmailArgsSchema, effect: "write", async execute(args) { // Replace with a real email provider call. return { messageId: `msg_${args.to}` }; }, }; export const toolRegistry = { issue_refund: issueRefundTool, search_orders: searchOrdersTool, send_email: sendEmailTool, } as const; export type ToolName = keyof typeof toolRegistry; Note the schema details that do real work. amount is an integer in minor units, so decimal-cent ambiguity disappears at the type level. orderId has a format constraint, which rejects a hallucinated identifier before it reaches the database. limit is capped, which prevents a model from requesting an unbounded scan.
The effect field classifies risk. requiresHumanApproval marks tools where the gate must find a valid approval token. These are not prompts; they are control-flow branches.
6. Building the Deterministic Decider
The decider takes a proposed call plus context and returns a decision. It must be a pure function of its inputs, apart from explicitly injected lookups.
Create src/gate/decider.ts:
import { z } from "zod"; import { toolRegistry, type ExecutionContext, type ToolName } from "../tools/registry.js"; import { evaluateRules, type RuleResult } from "../policy/rules.js"; export type Decision = | { status: "allow"; tool: ToolName; args: Record<string, unknown>; /** Rule IDs that explicitly permitted this action. */ satisfiedBy: string[]; /** Facts the executor may rely on. */ evidence: Record<string, unknown>; } | { status: "repair"; tool: ToolName; reasonCode: string; message: string; /** Machine-readable hints the agent can act on. */ violations: RuleResult[]; } | { status: "deny"; tool: ToolName | "unknown"; reasonCode: string; message: string; violations: RuleResult[]; }; export interface ProposedCall { tool: string; args: unknown; } export interface DeciderDeps { /** Resolves facts independently of the model. */ lookupFacts: (ctx: ExecutionContext) => Promise<Record<string, unknown>>; /** Verifies an approval token. Inject a real verifier in production. */ verifyApproval: (token: string, ctx: ExecutionContext) => Promise<boolean>; } const KNOWN_TOOLS = new Set<string>(Object.keys(toolRegistry)); export async function decide( proposed: ProposedCall, ctx: ExecutionContext, deps: DeciderDeps, ): Promise<Decision> { // Step 1: is this even a tool we know about? if (!KNOWN_TOOLS.has(proposed.tool)) { return { status: "deny", tool: "unknown", reasonCode: "UNKNOWN_TOOL", message: `Tool "${proposed.tool}" is not registered. Available tools: ${[...KNOWN_TOOLS].join(", ")}.`, violations: [], }; } const toolName = proposed.tool as ToolName; const tool = toolRegistry[toolName]; // Step 2: structural validation. Never trust shape from the model. const parsed = tool.argsSchema.safeParse(proposed.args); if (!parsed.success) { const issues = parsed.error.issues.map((i) => ({ ruleId: "SCHEMA_VALIDATION", field: i.path.join(".") || "<root>", message: i.message, })); return { status: "repair", tool: toolName, reasonCode: "SCHEMA_VIOLATION", message: "Tool arguments failed schema validation. Fix the fields listed and retry.", violations: issues, }; } const args = parsed.data as Record<string, unknown>; // Step 3: gather independent facts. The model cannot supply these. const facts = { ...ctx.facts, ...(await deps.lookupFacts(ctx)) }; // Step 4: deterministic policy evaluation. const results = await evaluateRules(toolName, args, { ...ctx, facts }); const failures = results.filter((r) => r.status === "fail"); if (failures.length > 0) { const hard = failures.filter((r) => r.severity === "hard"); const soft = failures.filter((r) => r.severity === "soft"); if (hard.length > 0) { return { status: "deny", tool: toolName, reasonCode: hard[0]!.ruleId, message: hard.map((h) => h.message).join(" "), violations: failures, }; } return { status: "repair", tool: toolName, reasonCode: soft[0]!.ruleId, message: soft.map((s) => s.message).join(" "), violations: failures, }; } // Step 5: approval requirement for high-risk effects. if (tool.requiresHumanApproval) { const token = ctx.approvalToken;\n const approved = token ? await deps.verifyApproval(token, ctx) : false; if (!approved) { return { status: "deny", tool: toolName, reasonCode: "HUMAN_APPROVAL_REQUIRED", message: "This action requires human approval. Present the proposed action to an authorized approver and retry with a valid approval token.", violations: [ { ruleId: "HUMAN_APPROVAL_REQUIRED", status: "fail", severity: "hard", field: "approvalToken", message: "No valid approval token was supplied for this action.", }, ], }; } } return { status: "allow", tool: toolName, args, satisfiedBy: results.filter((r) => r.status === "pass").map((r) => r.ruleId), evidence: facts, }; } Three properties of this design matter more than the code itself.
Ordering is fixed. Unknown tool, then schema, then facts, then policy, then approval. Changing the order changes security semantics, so treat it as part of the contract.
Facts flow one way. The gate collects facts from trusted systems. Model-provided claims can be proposed as facts, but they are never promoted to facts by the gate.
Repair and deny are distinct. A schema error is repairable: the agent can retry with corrected fields. A policy violation like "refund exceeds order total" may also be repairable if the agent can look up the correct amount. But an unknown tool or a missing approval token is a deny. Conflating them causes agents to loop, retrying the same thing against a wall.
7. Writing Policy Rules
Rules are small, named, independently testable predicates. They receive the validated arguments, the execution context, and trusted facts.
Create src/policy/rules.ts:
import type { ExecutionContext, ToolName } from "../tools/registry.js"; export type Source:https://dev.to/tamizuddin/stop-ai-agents-acting-on-bluffs-building-a-deterministic-tool-decider-gate-2i8i