Inspiration
I love letting AI agents handle tedious tasks, right up until the moment they need to pay for something.
If you want a shopping agent to actually check out today, you have two bad options: either hand it your raw payment credentials and pray it doesn't hallucinate or hit a prompt-injection trap, or make it ping you for every $12 purchase, which defeats the whole point of having an agent.
I started thinking about how companies solve this for human new hires. You don't hand an intern the company bank login, and the CEO doesn't approve every coffee run. You give them a corporate card with a strict limit, a list of approved vendors, a manager who only steps in when a receipt looks weird, and an audit trail at the end of the month.
What it does
That is why I built agent-spend-guard: a financial safety layer that sits between an AI agent and PayPal. The agent never sees a PayPal credential, an access token, or a vault token. It can only ask, through an MCP tool (request_purchase), and it gets back a status and an id.
Every request goes through the same pipeline:
- Deterministic rules set by the owner on a dashboard: a per-purchase cap and a hard maximum, a monthly budget in the owner's calendar month and timezone, a merchant allowlist (or a hold on the first purchase at any new merchant), a category allowlist, and buying hours.
- An AI risk reviewer that looks at what rules cannot: does the agent's reason fit the item, is the price out of line with what this item cost before, and is the agent being manipulated by the page it read. The guard fetches the product page itself, hidden text included. The reviewer answers with a risk level and flags from a fixed vocabulary, and it can only tighten a decision:
lowleaves the rules' verdict alone,mediumholds the request for the owner,highblocks it. A reviewer failure or timeout means held, never paid. - A decision:
AUTO_APPROVED,HELDorBLOCKED. Held requests wait for the owner, on a dashboard that fits a phone, with the reasons and the reviewer's explanation. - PayPal execution on the owner's one-time mandate, and an audit log of every step with every PayPal id.
The demo plays four scenarios with synthetic merchants and products:
- a 12.00 USD notebook at an approved merchant: inside the rules, paid with the buyer absent, capture id on the dashboard;
- a 45.00 USD microscope at a merchant the owner never allowed: held by the rules, approved on the phone, then charged;
- a bargain page whose hidden text tells the agent to buy ten units and claim the owner approved: the naive agent obeys, the reviewer sees the injection, the false approval claim and the odd quantity, and blocks it with no PayPal call and without bothering the owner;
- the same notebook relisted at 2.4× the price: every rule passes, the reviewer flags
PRICE_ANOMALYagainst the purchase history, the owner denies.
Then both captures are refunded from the same dashboard.
How PayPal is used
- Payment Method Tokens v3 for the mandate: the guard creates a setup token, the owner approves once on PayPal's own page with a sandbox personal account, and the guard exchanges it for a payment token (vault id) that it keeps server side. The agent never receives it.
- Orders v2 with
payment_source.paypal.vault_idto create and capture each approved order with the buyer absent. - Payments v2 for refunds from the dashboard.
PayPal-Request-Idon every create, so a retried call can never charge twice, and a requiredintent_idonrequest_purchase, so an agent that lost the answer repeats the call and gets the same request back instead of a second charge; OAuth tokens requested fresh (ignoreCache=true) so that app permission changes take effect immediately. A charge PayPal never confirmed, or a refund it leaves pending, stays counted against the budget until the owner settles it from the dashboard.- Sandbox only, by construction: the base URL is hard-coded to the sandbox host, every URL is checked before a call, the process refuses to start with any other
PAYPAL_ENV, and credentials, tokens and basic-auth values are redacted from every error and log line (tested). Every merchant, product and price in the demo is synthetic, and the demo's charges land in the app's own sandbox business account: no merchant receives anything.
How AI is used
- The risk reviewer has a mock provider (deterministic rules, no key, the default so that anyone can run the whole loop) and a Claude provider through the Vercel AI SDK with a JSON schema for the answer, one model call per request. The Claude provider (
claude-opus-5-5) was exercised against the live API on 2026-10-30: the four-scenario sandbox run passed 4/4 with four model calls of about 1.7k input and 100–200 output tokens each, answered in 2–3 s, and the explanations are the ones an owner would want ("about 2.4× the 12.00 USD paid for the same notebook at this merchant recently"). In an attempt eighteen minutes earlier three of the four connections to the API failed; those requests were held or blocked and nothing was paid, which is the fail-closed design working for real. The submitted demo and video run the deterministic mode so that judges need no key. - The shopping agent of the demo is a mock agent that follows what the page says, on purpose: it shows that the guard, not the agent, is the safety layer.
- Claude Code (Anthropic), running the Claude Fable 5.1 model, wrote most of the code, tests and documentation, reviewed and re-run by a human before each merge; every such commit is co-authored as Claude Fable 5.1 in the Git history. OpenAI Codex reviewed the repository twice and contributed one commit of fixes, verified and merged by a human. Gemini TTS reads the narration of the demo video. The runtime reviewer above (
claude-opus-5-5) is a different model from the one that wrote the code.
How I built it
TypeScript on Node 24 (22 supported), a Hono server for the dashboard and the agent API (server-sent events keep the dashboard live), SQLite through node:sqlite with migrations, the MCP SDK for the agent-facing tools (stdio), Vitest for 315 tests across 24 files (policy reason codes, reviewer tightening rules, idempotency, the sandbox-only guard, redaction, the dashboard, the MCP server, the end-to-end run against a fake PayPal). CI runs lint, typecheck, the tests and the offline end-to-end run on Node 22 and 24. gitleaks runs as a pre-commit hook and over the whole history before every push. The project was started from scratch on 2026-10-27, inside the submission period.
Challenges I ran into
- Making the AI part safe to be wrong. The reviewer can only tighten, its flags come from a fixed vocabulary, the mapping from risk to decision lives in code rather than in a prompt, and a failure holds the request. Product pages and merchant text are treated as data, never as instructions.
- Vaulting without a checkout. Getting the one-approval mandate right (setup token → approval → payment token → orders with the vault id, buyer absent) and keeping every id out of the agent's reach.
- Sandbox bookkeeping. A business sandbox account in a non-USD currency refuses refunds with
REFUND_FAILED_INSUFFICIENT_FUNDS; PayPal caches an access token for hours with the permissions the app had when it was minted. Both are now handled and documented. - Surviving adversarial code reviews. I ran two external security reviews on my own repo using OpenAI Codex. It caught subtle edge cases I had missed, like a budget race condition under concurrent requests, unconfirmed PayPal outcomes being booked as failed, pending refunds prematurely freeing up monthly budget, and a retry route that could accidentally trigger a first-time charge. Fixing those and locking them down with tests made the state machine much more resilient.
Accomplishments that I'm proud of
- The whole loop runs on the sandbox with real charges and real refunds, and the same four scenarios run offline against a fake PayPal in a few seconds for anyone without an account.
- The AI reviewer has run against the live Claude API on the same four scenarios and reached the same verdicts as the deterministic mode, with explanations written for the owner; when the API was unreachable, every affected request was held or blocked, never paid.
- Zero credentials on the agent side, zero PayPal calls for a blocked request, every decision explained in two sentences.
- A test suite that asserts the vault id and the secrets appear nowhere visible.
What I learned
Hard rules are great for catching the obvious stuff, but the scariest failure modes live inside the untrusted web pages the agent reads. I quickly realized that no amount of prompt engineering on the shopping agent itself can guarantee safety when money is on the line. Having the guard fetch the raw page independently, and cross-check the price against my own local purchase history, turned out to be way more reliable than trusting the agent's word for it.
What's next for agent-spend-guard
Webhooks for asynchronous capture and refund states, push notifications for held requests, several approvers per agent, per-category budgets, and packaging the guard as a drop-in middleware for the PayPal Agent Toolkit and agent-ready commerce protocols.
Testing instructions
Everything in the demo video was recorded against the real PayPal sandbox: the orders, captures and refunds on screen are real sandbox transactions, and the same end-to-end run (npm run e2e:sandbox) passed 4/4 scenarios with 2/2 refunds on 2026-10-29, and again on 2026-10-30 with the live Claude reviewer.
To repeat it with a free PayPal developer account (real sandbox charges and refunds): follow README sections M0 and M1. In short: create a sandbox REST app on a US business sandbox account with Save payment methods (Vault) enabled, put its client id and secret in .env, run npm run dev, link PayPal once from the dashboard's PayPal page with a sandbox personal account, then npm run e2e:sandbox between 08:00 and 22:00 Asia/Tokyo (the demo policy's buying hours). It charges 57.00 USD in two captures and refunds both. Add LLM_PROVIDER=anthropic and an LLM_API_KEY to .env to make the same run use Claude (one model call per request, four in all, about 0.04 USD).
Without a PayPal account, the same four scenarios run against a fake PayPal that answers in-process (deterministic reviewer, no key, no network):
git clone https://github.com/teifurin/agent-spend-guard.git && cd agent-spend-guard
npm ci
npm test # 24 files, 315 tests
npm run e2e:offline # ends with: VERDICT: 4/4 scenarios as expected, 2/2 refunds completed.
npm run dev # dashboard http://localhost:3000, synthetic shop http://localhost:3001
npm run demo:agent -- --wait 0 # second terminal: the four scenarios through MCP; watch the dashboard
AI tools used
- Claude Code (Anthropic), model Claude Fable 5.1: code, tests and documentation, reviewed and re-run by a human before each merge; each such commit carries a
Co-Authored-By: Claude Fable 5.1trailer. - OpenAI Codex (run by an external reviewer): two read-only security reviews of the repository (2026-10-30 and 2026-11-01) and one commit of fixes (pull request #1), verified and merged by a human.
- Gemini TTS (Google): narration of the demo video.
- Runtime: the AI risk reviewer runs in its deterministic mock mode in the demo and the video; the optional Claude provider (Vercel AI SDK,
claude-opus-5-5) was verified against the live API on 2026-10-30 (sandbox end-to-end run, 4/4).
Built With
- anthropic-claude
- github-actions
- hono
- model-context-protocol
- node.js
- paypal
- paypal-orders-v2
- paypal-payment-method-tokens
- paypal-payments-v2
- sqlite
- typescript
- vercel-ai-sdk
- vitest