SpendGate
SpendGate
SpendGate helps an autonomous agent decide whether to approve a planned spend before it pays.
It returns a score from 0 to 100, a verdict of approve, ask_human, or block, short reasons, a recommended_action, and checked_at. The score is deterministic. Rewording the purpose will not fish for a better verdict.
SpendGate does not send the merchant payment and does not hold a wallet key. Overage fees, when configured, are x402 USDC payments on Base to the PAY_TO address you set.
When an agent should use it
Call score_spend or POST /v1/score before a tool transfers crypto, buys a gift card, starts a subscription, or pays an API or merchant.
Pass the amount in USD, the category, the merchant or endpoint URL, and any daily or monthly budget you still have. If the amount is over a budget you supply, the verdict is
block.approvemeans pay.ask_humanmeans stop and ask a person.blockmeans do not pay.Amounts strictly under the free micro threshold (default $1) return
approve, unless they exceed a budget you passed in.Skip it for pure reads that do not spend. If you do check a health probe, use category
status_check.Keep your own hard cap. SpendGate is a second look, not the only lock.
Do not retry with a softer purpose to change the score. v1 does not store the body, and the math does not depend on prose.
Free spend watches are not in v1.
Related MCP server: Budget Governor
Scoring v1
Start at 100, then subtract. Policy version 1. Full constants: GET /v1/policy.
Input | Effect |
Amount |
|
Merchant | Known host or |
Category | High 30: |
Currency |
|
Risk hints | Raising hints add 6 each, cap 18. Lowering hints subtract 6 each, cap 12. Hints are self-reported. |
Thresholds after penalties: 70 approve, 40 ask a human, below that block.
Hard overrides, applied after the raw score:
Amount greater than
daily_budget_remainingormonthly_budget_remainingforcesblockand caps the published score at 24. Omitted budgets are not checked. Equal to the remaining budget is allowed.Otherwise, amount strictly under the micro threshold forces
approveand raises the published score to at least 80.
agent_id is echoed and not scored.
Free tier and x402
Tier | Cap | How |
Anonymous | 100 scores / UTC day | No key |
Free key | 1,000 scores / UTC day |
|
Toolweather key (hex client) | 1,000 scores / UTC day | Matching |
Toolweather anonymous caller | 100 scores / UTC day | Matching secret plus an |
Overage | $0.001 USDC per score | x402 on Base after the cap |
The Toolweather Worker proxies score_spend, get_quota, and spendgate_get_api_key to this server. When it sends x-tw-bundle-secret equal to this Worker's BUNDLE_PROXY_SECRET, quota is charged to x-tw-bundle-client. A hex client (a Toolweather API key hash, 16–128 hex characters; a longer value uses a stable 128-character prefix) gets the free-key cap of 1,000 scores per UTC day. An anonymous Toolweather caller (anon: plus that hash) gets the same 100 scores per UTC day as a direct anonymous caller, so a rotating egress address does not mint a fresh 1,000-score bucket. get_quota reports subject and tier bundle for both, with daily_limit set to the cap that applies. The raw client id is not stored. A presented sg_live_… key still wins. A missing, unset, or wrong secret keeps the anonymous IP bucket and does not return an error just because the headers are absent. Key minting through the proxy uses the same client id for the daily mint cap.
Network
eip155:8453(Base mainnet).Asset USDC
0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913(EIP-712 nameUSD Coin, version2).Facilitator https://facilitator.payai.network (
POST /verify, thenPOST /settle).Price is 1000 atomic units (6 decimals).
Quota reads, key mints, docs, and MCP discovery are not billed.
Set
PAY_TOto the 0x address that should receive USDC. If it is unset, over-cap scores return402withpayment_not_configured. The server will not invent a wallet.
A paid retry:
POST /v1/scorewith no payment header.Read HTTP 402 and the base64
PAYMENT-REQUIREDheader (the JSON body mirrors it).Sign EIP-3009
TransferWithAuthorizationfor the accepted requirement.Retry with
PAYMENT-SIGNATUREset to the base64 x402 v2 payment payload.The score comes back with
PAYMENT-RESPONSEafter settle. The same nonce returns the original score and does not settle again.
API
curl -s http://127.0.0.1:43123/v1/score \
-H 'content-type: application/json' \
-d '{
"amount": 12,
"currency": "USDC",
"category": "api_call",
"purpose": "embeddings for the planner",
"merchant": "https://api.openai.com/v1",
"agent_id": "agent_planner",
"daily_budget_remaining": 40,
"risk_hints": []
}'curl -s http://127.0.0.1:43123/v1/keys \
-H 'content-type: application/json' \
-d '{"label":"planner"}'
curl -s http://127.0.0.1:43123/v1/quota \
-H "authorization: Bearer sg_live_..."Other routes:
GET /healthGET /v1/policyGET /openapi.jsonGET /llms.txtandGET /llms-full.txtGET /.well-known/mcp(and/.well-known/mcp.json)GET /.well-known/x402POST /mcpstreamable HTTP, protocol2025-06-18(also accepts2025-03-26)
MCP
curl -s http://127.0.0.1:43123/mcp \
-H 'content-type: application/json' \
-H 'accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"example","version":"0"}}}'
curl -s http://127.0.0.1:43123/mcp \
-H 'content-type: application/json' \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"score_spend","arguments":{"amount":0.2,"category":"status_check","merchant":"https://www.cloudflare.com","agent_id":"agent_demo"}}}'Tools: score_spend, get_quota, get_api_key.
After the free cap, tools/call on score_spend returns HTTP 402 with a JSON-RPC error (-32002) and the PAYMENT-REQUIRED header. get_quota and get_api_key stay free.
Run locally
Requires Node 20+.
npm install
npx wrangler d1 migrations apply spendgate --local
npm run devThe site and API listen on http://127.0.0.1:43123.
Optional receiving wallet, in .dev.vars (gitignored, copy from .dev.vars.example):
PAY_TO=0xYourAddressnpm test
npm run typecheckDeploy
Free Cloudflare plan: one Worker, one D1 database, static assets from public/. No paid SaaS and no secrets in the repo.
npx wrangler d1 create spendgate
# Put the returned database_id in wrangler.toml (the committed id is a placeholder).
npx wrangler d1 migrations apply spendgate --remote
npx wrangler secret put PAY_TO
npx wrangler secret put BUNDLE_PROXY_SECRET
npx wrangler deployBUNDLE_PROXY_SECRET must be the same value as on the Toolweather Worker. Set it after merge, then redeploy. Do not commit the value. Until that secret is set, proxied calls without an sg_live_… key keep sharing the anonymous daily bucket.
npm run dry-run bundles the Worker the way a deploy would, without publishing.
To host the HTML on Pages by itself: npx wrangler pages deploy public. The API still needs the Worker. Serving both from the Worker is the setup wrangler.toml uses.
database_id in wrangler.toml is a placeholder UUID. Replace it before a real remote deploy. Do not put a production wallet in [vars].
Available Tools
3 toolsget_api_keyAInspect
Mint a free SpendGate API key. The secret is returned once. Store it and send it as Authorization: Bearer, or as api_key on later score_spend calls. Do not call this on every turn.
| Name | Required | Description | Default |
|---|---|---|---|
| label | No | Optional label stored with the key, up to 80 characters. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden and does most of it: it discloses the one-time secret return ('The secret is returned once'), how to transmit it (Authorization: Bearer or api_key), and a usage-rate caution. It does not state whether a key never expires, whether repeated calls invalidate prior keys, or whether auth is required to mint.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Four short sentences with no filler; purpose and the one-time-secret constraint are front-loaded, and each clause adds operational value (storage, header format, call-frequency warning).
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
With no output schema, the description must cover the return value and it does ('The secret is returned once'), which is the critical unknown for a key-minting tool. Minor gaps remain around key lifetime/expiry and what happens to previously issued keys, but nothing blocks correct invocation.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100% and the single optional `label` parameter is fully documented (80-character limit), so the baseline is 3. The description adds no meaning about the label parameter itself, and the parameter is optional, so nothing here is required to invoke the tool correctly.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
States a specific verb and resource ('Mint a ... SpendGate API key') and resolves the mismatch between the generic name get_api_key and the actual minting behavior. It also names score_spend as the downstream consumer, so an agent can place it among its siblings without opening a schema.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Gives an explicit when-not ('Do not call this on every turn') and implies the consumption workflow via score_spend. It stops short of stating when it should be called (initial setup vs. re-mint after a lost key), so it is clear context without full when/when-not coverage.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_quotaAInspect
Read how many free SpendGate scores remain today for this anonymous caller or API key. Does not consume a score and is not billed.
| Name | Required | Description | Default |
|---|---|---|---|
| api_key | No | Optional sg_live_ key. Omit to read the anonymous quota for this client. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description usefully discloses that calling this tool does not consume a score and is not billed, which is critical behavioral context for a quota-check endpoint. It does not cover error cases or rate-limit specifics, but covers the main non-obvious trait.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two sentences, front-loaded with the core purpose and followed by the key behavioral guarantee. No filler or redundancy.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple one-parameter read tool, the description covers purpose, scope, and non-consumption behavior. It implies the return is a count, but does not describe error handling or response shape, which is a minor gap given no output schema exists.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the api_key parameter is already fully documented. The description reinforces the anonymous-vs-key distinction but adds no syntax or format detail beyond the schema, making the baseline 3 appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
States a specific verb (Read) and resource (free SpendGate scores remaining today), and distinguishes from the score-consuming sibling by noting it does not consume a score. The anonymous caller or API key scope is also explicit.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Usage is implied: check remaining quota without spending a score. The description does not explicitly say when to prefer it over siblings like score_spend or get_api_key, so it falls short of clear routing guidance.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
score_spendAInspect
Score a planned payment before sending it. Call this before any tool that transfers crypto, buys a gift card, starts a subscription, or pays an API or merchant. Pass amount in USD, category, merchant or endpoint URL, and any budget remaining. Returns score 0-100, verdict approve | ask_human | block, reasons, and recommended_action.
| Name | Required | Description | Default |
|---|---|---|---|
| amount | Yes | Planned spend in USD, not in token atomic units. | |
| api_key | No | Optional SpendGate key (sg_live_…). Anonymous callers share a smaller daily cap. | |
| purpose | No | Short human description. Used as the category when category is omitted. | |
| agent_id | No | Your agent or key id. Echoed, not scored in v1. | |
| category | No | One of status_check, api_call, saas, infra, gift_card, crypto_transfer, irreversible. Unknown categories are scored as unknown risk. | |
| currency | No | Payment currency. Defaults to USDC. | |
| endpoint | No | Alias of merchant when the payee is an API URL. | |
| merchant | No | Merchant name or https endpoint URL that will receive the spend. | |
| risk_hints | No | Self-reported hints. Raising: new_payee, new_merchant, first_payment, high_velocity, mismatched_purpose, off_platform, shared_wallet. Lowering: trusted_repeat, within_policy, human_preapproved. known_merchant marks the payee known. | |
| daily_budget_remaining | No | USD still available today. Amount above this is blocked. | |
| monthly_budget_remaining | No | USD still available this month. Amount above this is blocked. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden and does disclose the return contract: a 0-100 score, verdict values approve | ask_human | block, reasons, and recommended_action, plus the hard-blocks above remaining budget. It stays silent on error/failure behavior, latency, and whether the scoring call itself has a cost, so it is strong but not exhaustive.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Three sentences, zero filler: the action, then the precondition that governs invocation, then the return contract. The most decision-relevant information (call before any payment tool) is front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
There is no output schema, so the description compensates by naming the score range, verdict enum, reasons, and recommended_action. Combined with the fully documented input schema and the budget-blocking rule, an agent has everything needed to invoke and interpret this tool.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, and the schema already documents each parameter in detail (categories, risk_hints directionality, budget semantics). The description only restates which fields to pass (amount, category, merchant/endpoint, budget), adding no meaning beyond the schema, so the baseline 3 applies.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
States a specific verb and resource ('score a planned payment') plus the timing constraint ('before sending it'), and the sibling tools (get_api_key, get_quota) are clearly different concerns. An agent can distinguish this as a pre-flight risk check without opening the schema.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly lists the trigger conditions: any tool that transfers crypto, buys a gift card, starts a subscription, or pays an API or merchant. That is a strong when-to-use signal, but there is no when-not-to-use guidance (e.g. whether it is needed for tiny/status-check spends) and no advice on acting on a non-approve verdict.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
v0.1.0- First observed
get_api_key - First observed
get_quota - First observed
score_spend
TDQS
Scored across 3 tools
Each tool has a clearly distinct purpose: score_spend evaluates a payment, get_quota reads remaining free scores, and get_api_key mints a credential. There is no overlap in intent, and the descriptions reinforce the separation.
All three names follow a consistent verb_noun snake_case pattern (score_spend, get_quota, get_api_key) with a predictable 'get_' prefix for read/creation helpers and a distinct verb for the main action.
Three tools is a reasonable, well-scoped set for a focused spend-scoring gate: one action, one quota check, one credential mint. It sits at the low end but every tool earns its place without redundancy.
The core workflow is covered end-to-end: mint a key, check quota, then score a spend before transacting. Minor gaps exist (no score history/audit or key revocation), but the primary agent lifecycle is complete and workable.
Maintenance
Related MCP Connectors
Free spend guardrails for AI agents: approve/deny/ask_user, caps, dupes.
Pre-spend firewall for AI agents. Approves, blocks, flags transactions against policy rules.
Zero-secret MCP gateway for AI agents: risk-scored, audited calls with human-in-the-loop approval.
Meter, cap, and block AI agent spend before the provider is charged.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceHuman-in-the-Loop authorization gateway for AI Agents. Securely pause MCP workflows and route high-risk actions to human approvers via Slack or Email.36 npm1MIT
- AlicenseNot gradedqualityCmaintenanceBudget & cost control for AI agents: hard per-agent spend caps, rate limits, idempotency, and human-in-the-loop approval — enforced before each LLM call, not after the invoice. One hosted MCP endpoint (no proxy or self-hosting), settled via x402 (USDC on Base).MIT
- AlicenseBqualityBmaintenanceAn MCP proxy that enforces declarative YAML spend policies for AI agents using Agentcard, providing attribution and anomaly detection.10MIT
- AlicenseNot gradedqualityCmaintenanceGoverns AI agents' spending by enforcing budgets, approvals, and kill switches before any payment, providing an MCP interface for tool calls with policy checks.Apache 2.0