DEV Community

Tamiz Uddin
Tamiz Uddin

Posted on Originally published at tamiz.pro

Stop AI Agents Acting on Bluffs: Building a Deterministic Tool-Decider Gate

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

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"
  }
}
Enter fullscreen mode Exit fullscreen mode

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"
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

  1. Type validity — the call matches a declared tool schema.
  2. Contextual validity — the call satisfies constraints derived from the current task, session, and environment.
  3. Authority validity — the call is permitted for this agent, this user, and this step.
  4. 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"]
}
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Create the source layout:

mkdir -p src/tools src/policy src/gate src/audit tests
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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,
  };
}
Enter fullscreen mode Exit fullscreen mode

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 RuleSeverity = "hard" | "soft";

exnexport interface RuleResult {
  ruleId: string;
  status: "pass" | "fail";
  severity: RuleSeverity;
  field?: string;
  message: string;
}

export interface RuleContext extends ExecutionContext {
  facts: Record<string, unknown>;
}

export type Rule = (
  args: Record<string, unknown>,
  ctx: RuleContext,
) => RuleResult | Promise<RuleResult>;

const pass = (ruleId: string, message = "Rule satisfied."): RuleResult => ({
  ruleId,
  status: "pass",
  severity: "hard",
  message,
});

const fail = (
  ruleId: string,
  message: string,
  severity: RuleSeverity = "hard",
  field?: string,
): RuleResult => ({ ruleId, status: "fail", severity, message, ...(field ? { field } : {}) });

const refundAmountWithinOrder: Rule = async (args, ctx) => {
  const orderId = String(args.orderId ?? "");
  const order = (ctx.facts.orders as Record<string, { total: number; currency: string }> | undefined)?.[orderId];

  if (!order) {
    return fail(
      "ORDER_MUST_EXIST",
      `Order ${orderId} was not found in the order system. Call search_orders first and use a verified order ID.`,
      "soft",
      "orderId",
    );
  }

  const amount = Number(args.amount);
  if (amount > order.total) {
    return fail(
      "REFUND_EXCEEDS_ORDER_TOTAL",
      `Refund of ${amount} minor units exceeds the order total of ${order.total} for ${orderId}.`,
      "soft",
      "amount",
    );
  }

  if (args.currency !== order.currency) {
    return fail(
      "CURRENCY_MISMATCH",
      `Order ${orderId} is denominated in ${order.currency}, not ${String(args.currency)}.`,
      "soft",
      "currency",
    );
  }

  return pass("REFUND_WITHIN_ORDER_TOTAL");
};

const refundNotAboveAgentLimit: Rule = (args, ctx) => {
  const limit = Number(ctx.facts.agentRefundLimit ?? 0);
  const amount = Number(args.amount ?? 0);

  if (limit <= 0) {
    return fail("NO_REFUND_AUTHORITY", "This agent role has no refund authority configured.");
  }

  if (amount > limit) {
    return fail(
      "REFUND_EXCEEDS_AGENT_LIMIT",
      `Refund of ${amount} exceeds this agent's limit of ${limit}. Escalate to a human operator.`,
    );
  }

  return pass("REFUND_WITHIN_AGENT_LIMIT");
};

const emailOnlyToCustomer: Rule = async (args, ctx) => {
  const customerEmail = ctx.facts.customerEmail;
  const to = String(args.to ?? "").toLowerCase();

  if (typeof customerEmail !== "string") {
    return fail("CUSTOMER_CONTEXT_MISSING", "No customer context is bound to this session.");
  }

  if (to !== customerEmail.toLowerCase()) {
    return fail(
      "EMAIL_RECIPIENT_NOT_VERIFIED",
      `Recipient ${to} does not match the verified customer address for this session.`,
      "soft",
      "to",
    );
  }

  return pass("EMAIL_RECIPIENT_VERIFIED");
};

const readOnlyToolIsSafe: Rule = (args, ctx) =>
  pass("READ_TOOL_ALLOWED", `Read tool permitted for agent role ${ctx.agentRole}.`);

const rulesByTool: Record<ToolName, Rule[]> = {
  issue_refund: [refundAmountWithinOrder, refundNotAboveAgentLimit],
  search_orders: [readOnlyToolIsSafe],
  send_email: [emailOnlyToCustomer],
};

export async function evaluateRules(
  tool: ToolName,
  args: Record<string, unknown>,
  ctx: RuleContext,
): Promise<RuleResult[]> {
  const rules = rulesByTool[tool] ?? [];
  const results: RuleResult[] = [];

  for (const rule of rules) {
    results.push(await rule(args, ctx));
  }

  return results;
}
Enter fullscreen mode Exit fullscreen mode

A rule has a stable ruleId. That ID is what appears in the audit log, the denial reason, and the dashboard. When a support engineer asks "why was this refund blocked?", the answer is a rule ID, not a stack trace or a paraphrase of a prompt.

Rules also have severity. A soft failure means the agent can plausibly correct itself by gathering more information. A hard failure means escalation is required. Getting this distinction wrong is a common source of agent loops: a hard failure returned as a repair prompt invites the model to retry indefinitely.

8. Integrating the Gate with an Agent Loop

Now wire the gate into an agent loop. The loop asks a planner for a proposed call, then hands that call to the gate. Only an allow decision reaches the executor.

Create src/gate/executor.ts:

import { toolRegistry, type ExecutionContext, type ToolName } from "../tools/registry.js";
import type { Decision } from "./decider.js";

export interface ExecutionResult {
  tool: ToolName;
  output: unknown;
  durationMs: number;
}

/**
 * The executor accepts ONLY gate-approved plans. There is no path from a
 * proposed call to execution that bypasses `decide`.
 */
export async function executeApproved(
  decision: Decision,
  ctx: ExecutionContext,
): Promise<ExecutionResult> {
  if (decision.status !== "allow") {
    throw new Error(
      `Refusing to execute a ${decision.status} decision. Only "allow" decisions may execute.`,
    );
  }

  const tool = toolRegistry[decision.tool];
  const started = Date.now();
  const output = await tool.execute(decision.args as never, ctx);

  return {
    tool: decision.tool,
    output,
    durationMs: Date.now() - started,
  };
}
Enter fullscreen mode Exit fullscreen mode

Now the agent loop. Create src/agent-loop.ts:

import { decide, type Decision, type DeciderDeps, type ProposedCall } from "./gate/decider.js";
import { executeApproved } from "./gate/executor.js";
import { writeAuditRecord } from "./audit/log.js";
import type { ExecutionContext } from "./tools/registry.js";

export interface Planner {
  /** Produces the next proposed tool call, or null when the task is complete. */
  nextProposal: (history: Turn[]) => Promise<ProposedCall | null>;
}

export interface Turn {
  role: "proposal" | "decision" | "result";
  content: string;
}

export interface LoopResult {
  turns: Turn[];
  finalOutput?: string;
  stoppedBecause: "completed" | "max_steps" | "denied";
}

const MAX_STEPS = 8;

export async function runAgent(
  planner: Planner,
  ctx: ExecutionContext,
  deps: DeciderDeps,
): Promise<LoopResult> {
  const history: Turn[] = [];

  for (let step = 0; step < MAX_STEPS; step++) {
    const proposal = await planner.nextProposal(history);

    if (proposal === null) {
      const finalOutput = history.findLast((t) => t.role === "result")?.content ?? "";
      return { turns: history, finalOutput, stoppedBecause: "completed" };
    }

    history.push({
      role: "proposal",
      content: JSON.stringify(proposal),
    });

    const decision = await decide(proposal, ctx, deps);
    history.push({
      role: "decision",
      content: JSON.stringify(decision),
    });

    await writeAuditRecord({
      requestId: ctx.requestId,
      tool: decision.tool,
      decision,
      proposedArgs: proposal.args,
    });

    if (decision.status === "deny") {
      return { turns: history, stoppedBecause: "denied" };
    }

    if (decision.status === "repair") {
      // The agent sees the structured violation and may try again.
      continue;
    }

    const result = await executeApproved(decision, ctx);
    history.push({
      role: "result",
      content: JSON.stringify(result.output),
    });
  }

  return { turns: history, stoppedBecause: "max_steps" };
}
Enter fullscreen mode Exit fullscreen mode

Note that the loop never interprets a denial as success. A denied action ends the run and surfaces an escalation, which is exactly what you want when an agent tries to issue a refund beyond its authority.

9. Handling Denials and Repairs

The difference between a good denial and a bad denial is the information content. A bad denial says "blocked." A good denial says what failed, why, and what to do next.

Create src/gate/repair-prompt.ts:

import type { Decision } from "./decider.js";

/**
 * Convert a repair decision into a compact, structured instruction for the planner.
 * The planner sees facts and constraints, not prose negotiation.
 */
export function buildRepairInstruction(decision: Decision): string {
  if (decision.status !== "repair") {
    throw new Error("buildRepairInstruction expects a repair decision.");
  }

  const lines = [
    `The proposed call to \`${decision.tool}\` was rejected by policy.`,
    `Reason code: ${decision.reasonCode}`,
    "",
    "Violations:",
  ];

  for (const v of decision.violations) {
    const field = v.field ? ` [field: ${v.field}]` : "";
    lines.push(`- ${v.ruleId}${field}: ${v.message}`);
  }

  lines.push(
    "",
    "Do not repeat the same call. Either gather the missing information with an allowed read tool, correct the flagged field, or escalate to a human operator.",
  );

  return lines.join("\n");
}
Enter fullscreen mode Exit fullscreen mode

Two safeguards belong here.

Cap repairs per rule. Track how many times each ruleId has produced a repair in a session. After two or three attempts, escalate. Without this, a model can oscillate between two near-identical calls indefinitely.

Never let repair widen authority. A repair instruction must not grant the agent new capabilities. It may only request a different value, a read to obtain a verified value, or escalation.

A denial should also be a first-class outcome in your API, not an exception. Something like:

{
  "status": "denied",
  "reasonCode": "REFUND_EXCEEDS_AGENT_LIMIT",
  "message": "Refund of 50000 exceeds this agent's limit of 20000. Escalate to a human operator.",
  "escalationTicket": "esc_9f2a"
}
Enter fullscreen mode Exit fullscreen mode

Returning a structured denial lets the surrounding application route the case, notify the right team, and keep the customer informed without pretending the task succeeded.

10. Auditing Every Decision

Auditability requires more than logging that something happened. It requires reconstructing why a decision was made, with the exact inputs, the exact rule outcomes, and a tamper-evident record.

Create src/audit/log.ts:

import { createHash } from "node:crypto";
import type { Decision } from "../gate/decider.js";

export interface AuditRecord {
  requestId: string;
  tool: string;
  decision: Decision;
  proposedArgs: unknown;
  timestamp: string;
  /** Hash of the previous record, forming a tamper-evident chain. */
  prevHash: string;
  /** Hash of this record's canonical contents. */
  hash: string;
}

const records: AuditRecord[] = [];

function canonicalize(value: unknown): string {
  if (value === null || typeof value !== "object") {
    return JSON.stringify(value) ?? "null";
  }
  if (Array.isArray(value)) {
    return `[${value.map(canonicalize).join(",")}]`;
  }
  const entries = Object.entries(value as Record<string, unknown>)
    .filter(([, v]) => v !== undefined)
    .sort(([a], [b]) => a.localeCompare(b));
  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalize(v)}`).join(",")}}`;
}

export async function writeAuditRecord(input: {
  requestId: string;
  tool: string;
  decision: Decision;
  proposedArgs: unknown;
}): Promise<AuditRecord> {
  const prevHash = records.at(-1)?.hash ?? "GENESIS";
  const timestamp = new Date().toISOString();

  const body = {
    requestId: input.requestId,
    tool: input.tool,
    decision: input.decision,
    proposedArgs: input.proposedArgs,
    timestamp,
    prevHash,
  };

  const hash = createHash("sha256").update(canonicalize(body)).digest("hex");
  const record: AuditRecord = { ...body, hash };

  records.push(record);

  // In production: append to an append-only store (Postgres, S3 Object Lock,
  // or a dedicated ledger service) and ship to your SIEM.
  console.log(`[audit] ${record.requestId} ${record.tool} ${input.decision.status} ${hash.slice(0, 12)}`);

  return record;
}

export function getAuditRecords(): readonly AuditRecord[] {
  return records;
}
Enter fullscreen mode Exit fullscreen mode

The hash chain gives you a property that plain logs do not: you can detect modification or deletion of historical records. Recompute the chain over the stored records and compare. If a hash does not match, the log has been altered.

For production, ship audit records to append-only storage and keep the decision record separate from the full tool arguments if arguments contain PII. Store a redacted or hashed representation of sensitive fields, plus a pointer to the encrypted original under your retention policy.

A useful audit query surface:

Field Purpose
requestId Trace one end-to-end agent run
tool Identify which tool was targeted
decision.status allow / repair / deny
decision.reasonCode Which rule fired
violations[].ruleId Every rule that failed, not just the first
satisfiedBy Which rules explicitly permitted the action
prevHash / hash Tamper-evidence chain

11. Testing the Gate

A policy engine without tests is a liability. Because the gate is deterministic, tests are fast and exhaustive. You do not need to mock a model to test whether a refund of $500 is blocked.

Create tests/decider.test.ts:

import { describe, expect, it } from "vitest";
import { decide, type DeciderDeps } from "../src/gate/decider.js";
import type { ExecutionContext } from "../src/tools/registry.js";

const deps: DeciderDeps = {
  async lookupFacts() {
    return {
      orders: {
        "A-1042": { total: 4900, currency: "USD" },
        "B-2001": { total: 12000, currency: "EUR" },
      },
    };
  },
  async verifyApproval() {
    return true;
  },
};

function ctx(overrides: Partial<ExecutionContext> = {}): ExecutionContext {
  return {
    requestId: "req_001",
    actorId: "user_77",
    agentRole: "support_l1",
    facts: {
      customerEmail: "buyer@example.com",
      agentRefundLimit: 20000,
    },
    now: new Date("2025-01-01T00:00:00Z"),
    ...overrides,
  };
}

describe("tool-decider gate", () => {
  it("denies an unknown tool", async () => {
    const decision = await decide({ tool: "drop_database", args: {} }, ctx(), deps);
    expect(decision.status).toBe("deny");
    expect(decision.reasonCode).toBe("UNKNOWN_TOOL");
  });

  it("repairs a schema violation with a non-integer amount", async () => {
    const decision = await decide(
      {
        tool: "issue_refund",
        args: {
          orderId: "A-1042",
          amount: 49.5,
          currency: "USD",
          reason: "customer_request",
          idempotencyKey: "idem-key-1234",
        },
      },
      ctx({ approvalToken: "tok_abc" }),
      deps,
    );
    expect(decision.status).toBe("repair");
    expect(decision.reasonCode).toBe("SCHEMA_VIOLATION");
  });

  it("blocks a refund above the order total", async () => {
    const decision = await decide(
      {
        tool: "issue_refund",
        args: {
          orderId: "A-1042",
          amount: 9900,
          currency: "USD",
          reason: "customer_request",
          idempotencyKey: "idem-key-1234",
        },
      },
      ctx({ approvalToken: "tok_abc" }),
      deps,
    );
    expect(decision.status).toBe("repair");
    expect(decision.reasonCode).toBe("REFUND_EXCEEDS_ORDER_TOTAL");
  });

  it("blocks a refund above the agent's authority limit", async () => {
    const decision = await decide(
      {
        tool: "issue_refund",
        args: {
          orderId: "B-2001",
          amount: 12000,
          currency: "EUR",
          reason: "customer_request",
          idempotencyKey: "idem-key-1234",
        },
      },
      ctx({ agentRole: "support_l1", approvalToken: "tok_abc" }),
      deps,
    );
    expect(decision.status).toBe("deny");
    expect(decision.reasonCode).toBe("REFUND_EXCEEDS_AGENT_LIMIT");
  });

  it("denies a write tool with no approval token", async () => {
    const decision = await decide(
      {
        tool: "issue_refund",
        args: {
          orderId: "A-1042",
          amount: 4900,
          currency: "USD",
          reason: "customer_request",
          idempotencyKey: "idem-key-1234",
        },
      },
      ctx(),
      deps,
    );
    expect(decision.status).toBe("deny");
    expect(decision.reasonCode).toBe("HUMAN_APPROVAL_REQUIRED");
  });

  it("allows a valid, approved refund", async () => {
    const decision = await decide(
      {
        tool: "issue_refund",
        args: {
          orderId: "A-1042",
          amount: 4900,
          currency: "USD",
          reason: "customer_request",
          idempotencyKey: "idem-key-1234",
        },
      },
      ctx({ approvalToken: "tok_abc" }),
      deps,
    );
    expect(decision.status).toBe("allow");
    if (decision.status === "allow") {
      expect(decision.args.amount).toBe(4900);
    }
  });

  it("blocks emailing an unverified recipient", async () => {
    const decision = await decide(
      {
        tool: "send_email",
        args: {
          to: "attacker@evil.test",
          subject: "Your refund",
          body: "Click here",
        },
      },
      ctx(),
      deps,
    );
    expect(decision.status).toBe("repair");
    expect(decision.reasonCode).toBe("EMAIL_RECIPIENT_NOT_VERIFIED");
  });
});
Enter fullscreen mode Exit fullscreen mode

Run the suite:

npm test
Enter fullscreen mode Exit fullscreen mode

Now add a test that proves the gate is immune to a class of prompt-injection bluffs. The critical property is that the model's own claims cannot become facts. Create tests/injection.test.ts:

import { describe, expect, it } from "vitest";
import { decide, type DeciderDeps } from "../src/gate/decider.js";
import type { ExecutionContext } from "../src/tools/registry.js";

const deps: DeciderDeps = {
  // The trusted system knows nothing about this order.
  async lookupFacts() {
    return { orders: {} };
  },
  async verifyApproval() {
    return true;
  },
};

describe("model claims cannot become facts", () => {
  it("ignores a model-supplied orderTotal claim", async () => {
    const ctx: ExecutionContext = {
      requestId: "req_inj",
      actorId: "user_1",
      agentRole: "support_l1",
      facts: { agentRefundLimit: 100_000 },
      now: new Date(),
    };

    const decision = await decide(
      {
        tool: "issue_refund",
        args: {
          orderId: "A-1042",
          amount: 999_99,
          currency: "USD",
          reason: "customer_request",
          idempotencyKey: "idem-key-1234",
          // The model claims the order total is huge. The gate ignores it.
          orderTotal: 999_999_99,
          verified: true,
        },
      },
      ctx,
      deps,
    );

    expect(decision.status).toBe("repair");
    expect(decision.reasonCode).toBe("ORDER_MUST_EXIST");
  });
});
Enter fullscreen mode Exit fullscreen mode

This test is the heart of the technique. The model can assert anything in its arguments, but the gate only consults facts it gathered itself. Extra fields are also stripped by Zod's default object parsing, so unverified claims never reach the executor.

12. Production Hardening

The gate works in the tutorial. Production requires more.

Make the gate the only path to side effects

Wrap tool invocation in a single exported function that requires a valid allow decision. Do not export raw tool executors to agent code. If you use an MCP server or a plugin system, enforce the same gate server-side, because a client-side gate protects only against honest clients.

Bind approval tokens to the exact action

An approval token must be scoped to a hash of the tool, arguments, actor, and expiry. Approving "issue a refund for order A-1042" must not authorize a different amount. Verify the token signature, expiry, and subject on every use, and burn it after use so it cannot be replayed.

Use idempotency keys as a real invariant

The schema requires an idempotencyKey. Enforce it at the executor and at the downstream API: a duplicate key with different arguments is a conflict and must fail loudly, not silently reuse the first result.

Separate policy from code

As rule count grows, move rules into a declarative format (Rego, Cedar, OPA, or a JSON/YAML rule file) and keep the gate's evaluation order fixed. The gate stays deterministic; only the rule definitions become configurable.

Version every decision

Record the policy version and tool schema version in each audit entry. Without them, you cannot explain why a call allowed in March was denied in June after a rule change.

Add adversarial and regression suites

Maintain a corpus of real agent failures. Each becomes a test asserting the gate blocks it. This turns production incidents into permanent regression protection, and it is the single highest-leverage practice in this whole architecture.

Watch for performance

The gate adds latency to every tool call. Keep it fast: cache facts with short TTLs, avoid network calls inside individual rules, and batch lookups before rule evaluation. If a fact lookup is slow, the model will route around the gate by trying more calls, which is worse than the latency you were trying to avoid.

Do not let the model write policy

Rules that an LLM generates at runtime are not deterministic and not auditable in the sense you need. If you want model-assisted policy authoring, generate a proposal that a human reviews and promotes into a versioned rule file.

Where this fits in the wider stack

A tool-decider gate is one component of a broader control plane. For more on structuring agent systems and the tooling around them, see Tamiz's Insights. For practical API integration patterns, tamiz.pro is a useful reference.

13. Frequently Asked Questions

Should the tool-decider gate be a model or a rules engine?

A rules engine. The entire point is that the decision does not depend on a stochastic model. If you use an LLM to evaluate policy, you have moved the bluff rather than removed it. Models may assist in authoring rules, but the runtime path must be deterministic.

How do I handle tools with many valid argument shapes?

Use discriminated unions in the schema and branch the rules on the discriminator. Keep each branch's rules small and independently testable. If a tool has more than a handful of materially different modes, split it into multiple tools; smaller tools produce smaller policy surfaces.

Does this replace prompt engineering and output-format constraints?

No. Structured output and clear tool descriptions still matter, because they reduce the number of invalid proposals the model generates. But they are efficiency measures. The gate is the correctness boundary. Even a perfectly formatted call can be semantically wrong, and only the gate catches that.

How do I avoid the agent getting stuck in repair loops?

Track repair attempts per ruleId within a session, cap them at two or three, and escalate to a human on exhaustion. Also make repair messages actionable: name the field, state the constraint, and suggest the next allowed action. A repair that only says "invalid" gives the model nothing to converge on.

What is the minimum viable version of this pattern?

Three pieces: a strict schema per tool, one rule that checks arguments against trusted facts, and an executor that refuses anything without an allow decision. That alone eliminates the most common class of agent bluffs. Add approval tokens and audit chaining next, then expand the rule set as you observe real failures.

Top comments (0)