How to Add Per-Route Spending Budgets and Human Approvals to Express AI Agents Without Redis
Embed agent-gateway-sdk as Express TypeScript middleware: fail-closed JSON payload rules, hard-block spending budgets, zero-tunnel Slack/Telegram approvals and a SQLite WAL hash-chained audit log, with zero external infrastructure.
Once an LLM agent can call POST /api/refunds, the interesting question is no longer can it. It is how much, how often, and who signs off on the big ones. The usual answer is an afternoon of glue: a Redis counter for the budget, a queue for held requests, a webhook for Slack, and a log table nobody trusts.
This guide does it with one dependency and no infrastructure. agent-gateway-sdk runs as Express middleware in front of your routes and keeps budgets, held approvals and the audit log in an embedded SQLite database (WAL mode). The complete, runnable app is in examples/express-stripe-refund-cap. Every output below comes from running it.
The policy we want
For an agent that handles support refunds:
| Request | Decision |
|---|---|
| refund ≤ $50 | run immediately |
| refund > $50 | hold until a human approves (phone or dashboard) |
| refund > $500 | refuse, even if someone would approve it |
| more than $200/hour of automatic refunds | refuse further automatic refunds |
| a second refund on the same charge within 24 h | refuse |
amount sent as "40" (a string), or missing |
never automatic |
POST /api/transfers, or any route not listed |
refuse |
The last two rows are the ones hand-rolled middleware usually gets wrong. Number("40") is 40, so a string slips under a <= 50 check. undefined <= 50 is false, so a missing amount falls through to whatever your else branch does. Fail-closed means the default path is the safe path.
Wire it into Express
npm install agent-gateway-sdk express stripeimport express from "express";
import { createAgentGateway } from "agent-gateway-sdk";
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const PORT = 4242;
const gateway = createAgentGateway({
port: PORT, // approved requests are replayed to http://127.0.0.1:4242
rulesPath: ".mont-data/rules.json",
configPath: ".mont-data/config.json",
dbPath: ".mont-data/logs.db", // SQLite (WAL): budgets, approvals, audit chain
adminToken: process.env.ADMIN_TOKEN,
});
await gateway.ready; // database opened and migrated
const app = express();
app.use(gateway.discoveryRouter); // GET /.well-known/agent.json
app.use(gateway.approvalCallbackRouter); // signed Approve / Reject links
app.use("/api/agent-admin", gateway.adminRouter); // admin API: mount BEFORE the firewall
app.use("/api", gateway.agentGateway); // the firewall: default deny for /api/*
app.post("/api/refunds", express.json(), async (req, res) => {
// Only reached when Mont allowed the call, or a human approved it.
const refund = await stripe.refunds.create({ charge: req.body.charge, amount: Math.round(req.body.amount * 100) });
res.status(201).json(refund);
});
app.listen(PORT);The order matters. The admin router must be mounted before the firewall, or the firewall would refuse admin calls as unknown routes. Your handlers come after it, so they run only for requests that passed. From v2.2.1 the package ships its own TypeScript declarations, so createAgentGateway and the Rules type are fully typed.
The rules
{
"GET /api/refunds": { "mode": "ALLOW", "description": "List refunds", "rateLimit": 60 },
"POST /api/refunds": {
"mode": "REQUIRE_APPROVAL",
"description": "Refunds",
"rateLimit": 20,
"policies": [
{ "name": "never above $500", "when": [{ "field": "body.amount", "op": ">", "value": 500 }], "mode": "BLOCK" },
{ "name": "auto-refund up to $50", "when": [{ "field": "body.amount", "op": "<=", "value": 50 }], "mode": "ALLOW" }
],
"budget": { "field": "body.amount", "max": 200, "windowMinutes": 60, "per": "global", "onExceed": "BLOCK" },
"dedupe": { "fields": ["body.charge"], "windowMinutes": 1440, "onDuplicate": "BLOCK" }
},
"POST /api/transfers": { "mode": "BLOCK", "description": "Agents never move money out" }
}How Mont evaluates it:
- Rule lookup is by method and path: exact keys first, then wildcards (
"POST /api/*refund*"), most specific first. No match means 403. - Policy tiers run top to bottom and the first match wins, which is why the
BLOCKceiling sits above theALLOWtier. If no tier matches, the rule's ownmode(REQUIRE_APPROVAL) applies. That is the fail-closed default. - Numeric operators never coerce.
"40"is not a number, so neither tier matches and the request is held for a human. A missingamountbehaves the same way. - The budget adds up
body.amountacross requests that would otherwise be allowed, in a rolling 60-minute window. WithonExceed: "BLOCK"it is a hard ceiling. Use"REQUIRE_APPROVAL"if you would rather escalate.per: "caller"gives each agent key its own budget. - Dedupe refuses a second action with the same
body.chargewhile the first is allowed, pending or done. A rejected attempt does not count, so a legitimate retry still works.
Policies read the parsed body, so routes with policies accept JSON only. A text/plain body with an amount inside it is refused rather than skipped.
What the agent sees
npm run smoke in the example fires the table above at the running app:
201 $30 refund (auto-allowed) re_bbd23904bbe5
403 same charge again (duplicate) Refused: this looks like a duplicate of an action already sent...
202 $120 refund (needs a human) approvalId=1
403 $900 refund (over the $500 ceiling) This request to /api/refunds is blocked by a gateway payload policy.
202 "amount": "40" as text (fail-closed) approvalId=2
403 transfer out (blocked route) Access to /api/transfers is blocked by gateway rules.
403 unknown route (default deny) Access to /api/customers/delete is blocked by gateway rules.
201 $45 refund #1 (budget: $200/hour) re_059d3b0ef1a3
201 $45 refund #2 (budget: $200/hour) re_8b76af14b755
201 $45 refund #3 (budget: $200/hour) re_32217a523839
403 $45 refund #4 (budget: $200/hour) Refused: the spending budget for this action has been reached.$30 + 3 × $45 = $165. The fourth $45 would take the hour to $210, so it is refused. Each individual refund passed the ≤ $50 tier. Only the cumulative budget catches the pattern, and that is exactly what a looping or prompt-injected agent produces.
Refusals are JSON with a human-readable message, so a tool-calling agent can read why and tell the user, instead of retrying blindly.
Approving the held ones
A held request returns 202 with an approvalId. Its original body is stored encrypted (AES-256-GCM) in SQLite and survives restarts. Decide it from the admin API:
curl -s -X POST localhost:4242/api/agent-admin/approvals/1/decide \
-H "x-admin-token: $ADMIN_TOKEN" -H "content-type: application/json" -d '{"decision":"APPROVE"}'{ "success": true, "id": 1, "status": "APPROVED", "replayStatus": 201,
"response_preview": "201 {\"id\":\"re_f153ebc99c26\",\"charge\":\"ch_mx950fgub\",\"amount\":120,...}" }In middleware mode the approved request is replayed into your own app on 127.0.0.1:<port> with a secret header the firewall recognises. That is why port must be the port your app listens on. Your handler runs once, with the original body, and the response is captured into the audit row. Each approval can be decided exactly once: a second decision, or two phones tapping at the same moment, gets "Action already taken". Pending items expire after 24 hours.
Approving from your phone, with no tunnel
Most approval flows need Slack or Telegram to call into your server, which means a public URL. Mont reverses the direction. It long-polls Telegram's Bot API, or holds a Slack Socket Mode WebSocket open, both outbound. Approve / Reject buttons work from an app on a laptop, a VPC with no ingress, or a container behind NAT.
curl -s -X POST localhost:4242/api/agent-admin/setup -H "x-admin-token: $ADMIN_TOKEN" \
-H "content-type: application/json" \
-d '{"notifications":{"telegram":{"enabled":true,"mode":"polling","botToken":"123456789:AA…","chatId":"123456789"}}}'
curl -s -X POST localhost:4242/api/agent-admin/setup/test-notification -H "x-admin-token: $ADMIN_TOKEN"The alert shows the route, the redacted body, the caller and the agent's stated justification (the x-mont-justification header). On Pro, Edit & Approve lets you lower 120 to 60 in the chat before approving. The edit is checked against the rules again, and it can't push spend past an onExceed: "BLOCK" budget. The Slack and Telegram details are in the MCP approvals guide, and they work the same for REST routes.
Why SQLite instead of Redis
| Concern | Redis + queue + webhook | Mont (embedded SQLite WAL) |
|---|---|---|
| Extra services | Redis, often a worker, a public webhook URL | none |
| Budget correctness under bursts | needs Lua or MULTI to avoid check-then-act races |
race-free under concurrent bursts, enforced inside SQLite |
| Held requests survive a restart | only if you persist the queue | yes, encrypted at rest |
| Audit evidence | whatever you log | every row SHA-256 chained to the previous one, written before forwarding |
| Multiple processes on one host | yes | yes: several gateway processes can share one database file |
| Multiple hosts | yes | not one SQLite file over NFS. Run Mont as one standalone proxy in front of the fleet (npx agent-gateway-sdk start --target …), or accept per-host budgets |
The honest limit is the last row. SQLite WAL needs a local filesystem. If your API runs on many hosts and needs one global budget, put a single Mont proxy in front of them rather than embedding it in each replica. Embedding gives you middleware with zero network hops. The standalone proxy gives you one choke point. The rules file is the same either way.
The audit trail
Every decision becomes a row: allowed, held, approved (with approved_by), rejected, budget-refused, duplicate-refused, and the replay's response. Each row's hash covers the previous row's hash, so an edit, deletion, insertion or truncation is detectable. Request and response bodies are redacted (card numbers, tokens, API keys, plus your own audit.redactKeys) before they are written. Export it as CSV for chargeback disputes with GET /api/agent-admin/logs/export.csv.
Production checklist
- Keep
ADMIN_TOKENin your secret store, and mount the admin router where only operators can reach it. - Give each agent an
agk_…key (x-agent-keyheader). Thenper: "caller"budgets, blocklists and audit rows are per agent. - Introduce new rules as
SHADOW_BLOCK/SHADOW_APPROVALfirst. They log what they would have done against live traffic without enforcing it. - Edit
rules.jsonin place. It is re-read when it changes, with no restart. - If agents reach you through MCP rather than REST, the same rules apply to tool calls. The MCP Firewall Config Generator builds that config.
Clone the starter, run npm run dev and npm run smoke, and change the numbers to your own limits. It takes about ten minutes, and it replaces the Redis counter and approval queue you were about to write.