AI Agents Should Never Execute Tools Directly: Build an Authorization Gate Before the Side Effect
Once an AI agent can trigger real side effects, tool calls need an authorization boundary. Here is a practical policy gate in TypeScript and Python with default-deny rules and human approval for risky actions.
On this page
Once an agent can call tools, the security problem changes.
When the model only generates text, a bad answer is mostly a content problem. When the same model can issue a refund, update a customer record, send an email, or trigger a deployment, a bad decision becomes a real side effect.
That is the point where I stop treating tool calls as ordinary function calls.
I treat them as requests for permission.
Suppose a support agent decides to refund an order:
{ "tool": "issue_refund", "arguments": { "orderId": "ord_84721", "amountCents": 48000 }}The call may be perfectly valid. The order may exist. The arguments may match the schema.
There is still another question:
Is this agent allowed to refund this order for this amount on behalf of this user?
The model should not answer that question.
Your application should.
Put the check at the tool boundary
The simplest design is to have one place through which every state-changing tool call passes.
The model proposes the action. Your application builds the trusted context around it — current user, tenant, roles, environment — and evaluates policy before the tool runs.
The important distinction is that the model can choose:
issue_refundorderId = ord_84721amount = $480but it cannot choose:
role = finance_admintenant = customer_123refund_limit = $50,000Those values must come from authenticated application state.
Otherwise a prompt-injected model could simply claim the permissions it needs.
For most agent workflows, three decisions are enough: allow, deny, and require_approval.
A small refund may run automatically. A larger refund may need a finance person. Deleting an account may simply be unavailable to the agent.
One policy gate
You do not need a dedicated policy platform to start. For a small application, plain application code is often easier to understand, test, and review.
Here is the same policy in TypeScript and Python:
type ActionContext = { tool: string; args: Record<string, unknown>; principal: { userId: string; tenantId: string; roles: string[]; };};type Decision = | { effect: "allow" } | { effect: "deny"; reason: string } | { effect: "require_approval"; reason: string };function authorize(ctx: ActionContext): Decision { if (ctx.tool === "delete_account") { return { effect: "deny", reason: "Agents cannot delete customer accounts", }; } if (ctx.tool === "issue_refund") { const amount = Number(ctx.args.amountCents); if (!Number.isSafeInteger(amount) || amount <= 0) { return { effect: "deny", reason: "Invalid refund amount", }; } if (amount > 50_000) { return { effect: "require_approval", reason: "Refund exceeds the automatic limit", }; } return { effect: "allow" }; } return { effect: "deny", reason: "No policy permits this action", };}The last branch matters more than it looks.
A tool that nobody has written policy for is denied. That means adding a new tool does not accidentally give every agent a new capability.
The code is deliberately boring. Authorization code should be boring. I would rather debug a deterministic amount > 50_000 rule than ask another model whether a large refund "seems reasonable."
Wrap the tool runner, not every individual tool
The policy only matters if every tool actually goes through it.
If authorization is implemented separately inside every tool, somebody will eventually add a new tool and forget the check. I prefer one execution boundary.
async function runTool( ctx: ActionContext, execute: () => Promise<unknown>,) { let decision: Decision; try { decision = authorize(ctx); } catch { decision = { effect: "deny", reason: "Authorization failed", }; } console.log({ tool: ctx.tool, userId: ctx.principal.userId, decision, }); if (decision.effect === "deny") { return { ok: false, error: "action_not_authorized", reason: decision.reason, }; } if (decision.effect === "require_approval") { return requestApproval(ctx); } return execute();}Two details matter here.
First, an authorization failure does not mean "let the request through." For state-changing actions, the safe default is to fail closed.
Second, a denial does not have to crash the whole agent run. It can be returned as a normal tool result. The agent can explain that approval is required, choose another permitted path, or stop cleanly.
It just cannot bypass the decision.
One place teams get this wrong
The policy context itself has to be trustworthy.
It is dangerous to take identity or permissions from model-generated tool arguments. The model should be able to propose the action, but the application must provide the principal from authenticated state.
The safe pattern looks like this:
const ctx: ActionContext = { tool: modelCall.name, args: modelCall.arguments, principal: session.user,};const decision = authorize(ctx);This is the most important boundary in the design.
The model can say what it wants to do.
It cannot say who it is.
What about human approval?
Approval should sit above the same gate, not replace it.
For example, a $700 refund might return:
{ "effect": "require_approval", "reason": "Refund exceeds the automatic limit"}A finance user can approve that specific request.
I would avoid turning approval into a temporary "admin mode" for the agent. The approval should be tied to the exact order and amount that were reviewed.
If the agent later changes the refund from $700 to $7,000, that is a new action and should require a new decision.
There is also a practical detail worth adding in larger systems: if approval takes twenty minutes, re-check the current state before executing. The order may already have been refunded, cancelled, or modified while the request was waiting.
Authorization is not the same as observability
Logging every tool call is useful.
It is not authorization.
A log can tell you:
02:14 refund issued: $4,000after the money has already moved.
An authorization gate can prevent that operation from happening in the first place.
You still want logs. I would log every authorization decision — allowed ones included — because they become useful when debugging an agent run later.
But logging and authorization solve different problems.
Do not forget duplicate execution
There is another failure mode that authorization does not solve.
Imagine the refund succeeds, but the tool response times out. The agent sees no success response and retries the call. Now the same authorized action may execute twice.
For high-risk writes, pair authorization with an idempotency key:
const idempotencyKey = `${runId}:${toolCallId}`;Store the execution result against that key and return the previous result if the same operation is retried.
Authorization answers may this happen?
Idempotency answers has this already happened?
Both matter once an agent can change state.
When the rules get bigger
For a small agent, keeping policies in application code is completely reasonable.
You get normal pull requests, normal tests, and normal CI.
Eventually the rules may become complicated enough that this stops being pleasant. If several services share the same authorization rules, or different teams need to manage policy independently, that is when systems such as Open Policy Agent or Cedar become worth evaluating.
I would not start there unless the complexity requires it.
The architectural boundary matters more than the policy language:
the agent proposes an action, and trusted code decides whether that action may execute.
What I would test
For the refund example, I care about a small set of invariants: malformed refund amounts are denied, normal refunds are allowed, large refunds require approval, unknown tools are denied, and permissions come from trusted application context rather than tool arguments.
The default-deny test is small:
it("denies unknown tools by default", () => { const decision = authorize({ tool: "production_database_reset", args: {}, principal: { userId: "u_1", tenantId: "t_1", roles: ["support"], }, }); expect(decision.effect).toBe("deny");});That kind of test is more valuable than another paragraph in the system prompt saying:
Be careful before issuing refunds.
The model can still make mistakes.
The authorization layer exists because we assume that eventually it will.
The takeaway
Once agents can change real systems, tool calls need a security boundary of their own.
Do not rely on the model to decide what it is allowed to do.
Let it propose the action. Build the user's identity and permissions from trusted server-side state. Evaluate a deterministic policy before the tool runs. Default to deny when nothing explicitly allows an action. Escalate the smaller set of operations that genuinely need a human.
That is a much safer foundation than hoping the prompt always wins.
References
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article