Every call to your MCP server costs you something. Maybe it's an LLM call, a GPU minute, a scraping proxy, or a paid API you're reselling. When the caller was a human clicking a button, that was fine. Now the caller is an agent in a loop, and it can call your tool 400 times before lunch.
At some point you have to charge for it. This post walks through the three ways to do that today, with the code and the failure modes for each:
- Build it yourself — API keys and a balance in your own database.
- x402 — the agent pays per request, on-chain.
- A clearinghouse — a gateway handles keys, wallets, and billing, and you verify signed requests.
I'll be upfront: I co-built a clearinghouse, Nexus402, so option 3 is the one I know best. But I'll give you everything you need to do option 1 properly, because for some tools it's the right answer.
What "charge per tool call" actually requires
Before picking an approach, here's the checklist. Every option has to answer all of these somehow:
- Who is calling? You need a stable identity per paying customer.
- What does this call cost? A price per tool, known before the call runs.
- Can they pay? Check the balance before doing the expensive work, not after.
- Charge exactly once. Agents retry. Networks drop responses. A retry must never become a second charge.
- What if you fail? If your server times out or throws, should the caller still pay?
- Stop runaway spend. A buggy agent loop shouldn't empty someone's wallet in ten minutes.
- Get paid. Money has to actually reach your bank account.
The trap most people fall into is post-paid metering: log usage, invoice at the end of the month. It's easy to build and it's the wrong default for agents. You do the expensive work first and find out weeks later whether the card works. Prepaid balances flip that around: no balance, no call.
Option 1: Build it yourself
You issue API keys, keep a prepaid balance per customer, and debit it on every call. The core of it is one atomic database statement.
The schema
CREATE TABLE accounts ( id BIGSERIAL PRIMARY KEY, api_key_hash BYTEA NOT NULL UNIQUE, -- store a hash, never the key balance_micro BIGINT NOT NULL CHECK (balance_micro >= 0) ); CREATE TABLE charges ( account_id BIGINT NOT NULL REFERENCES accounts (id), idempotency_key TEXT NOT NULL, tool TEXT NOT NULL, amount_micro BIGINT NOT NULL CHECK (amount_micro > 0), status TEXT NOT NULL DEFAULT 'charged', -- charged | refunded created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (account_id, idempotency_key) ); Two decisions are doing the work here:
- Money is an integer count of micro-dollars (
BIGINT), never a float.$0.02is20000. Floats will eventually turn0.1 + 0.2into a billing dispute. -
CHECK (balance_micro >= 0)makes overdraft impossible at the database level, even if your application code has a bug.
Debit atomically, exactly once
The debit and the charge record happen in one transaction. The idempotency key is the primary key of charges, so a retry can't insert a second row:
var ErrInsufficientFunds = errors.New("insufficient funds") // Debit charges an account once per idempotency key. A retry with the same // key is a no-op that reports success without charging again. func Debit(ctx context.Context, db *sql.DB, accountID int64, key, tool string, price int64) error { tx, err := db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() res, err := tx.ExecContext(ctx, ` INSERT INTO charges (account_id, idempotency_key, tool, amount_micro) VALUES ($1, $2, $3, $4) ON CONFLICT (account_id, idempotency_key) DO NOTHING`, accountID, key, tool, price) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { return tx.Commit() // already charged for this key: replay, don't double-charge } res, err = tx.ExecContext(ctx, ` UPDATE accounts SET balance_micro = balance_micro - $2 WHERE id = $1 AND balance_micro >= $2`, accountID, price) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { return ErrInsufficientFunds // rollback undoes the charge row too } return tx.Commit() } The WHERE balance_micro >= $2 guard means two concurrent calls can't both spend the last dollar: Postgres row-locks the account, and the second UPDATE sees the reduced balance and affects zero rows.
One subtlety: a retry with the same key isn't charged again, but in the handler below it does run the tool again — for free. If your tool is expensive, store the result against the idempotency key and return the stored result on a replay instead.
Wrap the tool call
Now the MCP handler debits first, runs the tool, and refunds if your side fails:
func handleToolCall(w http.ResponseWriter, r *http.Request) { acct, ok := authenticate(r) // look up sha256(api key) in accounts if !ok { http.Error(w, "unauthorized", http.StatusUnauthorized) return } var req struct { Params struct { Name string `json:"name"` Arguments json.RawMessage `json:"arguments"` } `json:"params"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "bad request", http.StatusBadRequest) return } price, known := prices[req.Params.Name] // e.g. "word_count": 20000 if !known { http.Error(w, "unknown tool", http.StatusNotFound) return } key := r.Header.Get("Idempotency-Key") if key == "" { http.Error(w, "Idempotency-Key header required", http.StatusBadRequest) return } switch err := Debit(r.Context(), db, acct.ID, key, req.Params.Name, price); { case errors.Is(err, ErrInsufficientFunds): w.WriteHeader(http.StatusPaymentRequired) // 402: top up and try again return case err != nil: http.Error(w, "unavailable", http.StatusServiceUnavailable) // fail closed: no debit, no work return } result, err := runTool(r.Context(), req.Params.Name, req.Params.Arguments) if err != nil { refund(r.Context(), acct.ID, key) // your failure, their money back http.Error(w, "tool failed", http.StatusBadGateway) return } json.NewEncoder(w).Encode(result) } Notice the default when the database is unreachable: refuse the call. If you can't record the charge, don't do the work. An outage should cost you availability, never money.
What you still have to build
That's the core, and it's maybe 20% of the job. You still need:
- Top-ups: a Stripe Checkout flow, a webhook that credits balances, and webhook idempotency (Stripe retries too).
- Key management: issuing, rotating, revoking, and hashing keys.
- Spend caps: a per-key daily limit, so a looping agent stops at $5 instead of $500.
- Refund and dispute handling, taxes, receipts, and a dashboard so customers can see where their money went.
- Reconciliation: a job that proves balances equal the sum of the ledger.
And every developer who wants your tool has to sign up with you, keep a balance with you, and manage a key for you — times every other paid tool their agent uses.
Choose this when: you have one or two big customers, you already run accounts and billing, or your pricing is too custom for a per-call price.
Option 2: x402 — pay per request on-chain
x402, from Coinbase, puts the payment in the HTTP exchange itself. The server answers an unpaid request with 402 Payment Required and a description of what it accepts. The agent signs a stablecoin payment (typically USDC), retries the request with the payment attached, and a facilitator service verifies and settles it before the server does the work.
What's good: no accounts and no API keys. Any agent with a funded wallet can pay any server on first contact, which is genuinely agent-native.
What's hard:
- Both sides need crypto wallets, and the agent's wallet has to be funded and secured.
- Many businesses — especially the enterprises most likely to pay for agent tooling — won't hold or move crypto yet, and it widens your compliance surface.
- On-chain settlement per call adds fees and latency that matter when calls cost fractions of a cent.
Choose this when: your users are already crypto-native, or you want permissionless, account-free access more than mainstream adoption.
Option 3: A clearinghouse
A clearinghouse sits between agents and tools. Developers prepay one wallet and get one key that works across every tool on the network. You publish a price; the gateway authenticates callers, checks balances and caps, answers 402 when a wallet is empty, and only forwards calls that are paid for. You verify that each request really came from the gateway, do the work, and get paid out.
This is what Pradip Dhungana and I built Nexus402 to be. I wrote a deep dive on its internals — the atomic Redis Lua deduction, failing closed, and the append-only ledger — in Billing AI agents per tool call without losing a cent. Here I'll focus on what it looks like from your side as a tool creator.
Nexus402 opens to the public soon, so the details below describe how it works at launch.
What you set up
- Sign in and claim a handle — 3 to 39 characters of
a-z,0-9, and-. You get a creator key (nx_crt_…), shown once. - Stand up an HTTPS endpoint that meets the gateway's requirements (below).
- Publish a version with a price. The first time you publish on a host, you prove you control it by serving a challenge file under
/.well-known/nexus402-challenge/. - Connect Stripe when you want to withdraw. Earnings accrue before that.
Your tools get names like acme/text/word_count, and every version is permanent: its price, endpoint, and description never change. To change the price, you publish @v2. That sounds strict, but it's what lets an agent know exactly what a call costs before it makes it.
Endpoint requirements
- HTTPS on port 443, resolving only to public IPs. Redirects are never followed.
- POST only. The gateway answers
initialize,ping, andtools/listitself from your published schema, so your endpoint only ever receivestools/call. - Timeouts: response headers within 5 seconds, no gap longer than 5 seconds while streaming, and the whole call within 120 seconds.
- Size: responses up to 10 MiB.
If you already run an MCP server built with an SDK, you don't need to rewrite it: the open-source verify-proxy sits in front of it and handles everything in the next section for you. Read on if you want to understand what it does, or implement it yourself.
Verifying a signed request
Every forwarded call carries these headers:
| Header | Value |
|---|---|
X-Nexus-Signature | ed25519: followed by a base64 64-byte signature |
X-Nexus-Timestamp | Unix time in seconds |
X-Correlation-ID | An opaque ID for this call |
X-Nexus-Creator-Key | Your nx_crt_… key (absent on the publish-time "hello") |
The signature covers six fields joined with single \n characters, with no trailing newline:
POST tools.example.com /mcp?region=eu 1767225600 3f6c2a1e-… 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 That's the method, your registered host, the path and query exactly as sent, the timestamp, the correlation ID, and the lowercase hex SHA-256 of the raw request body.
Three rules matter more than they look:
- Use your registered host from config, never the inbound
Hostheader. The host is part of what's signed, so a request meant for another creator's server can't be replayed against yours — but only if you check it against the host you registered. - Reject timestamps more than 60 seconds away from now, in either direction. That bounds how long a captured request can be replayed.
- Accept any key from the published key set. The gateway publishes its public keys (newest first) so it can rotate them without breaking you. Re-read the set periodically.
Prove you received it
The other half is the proof header. On every response — including errors — you echo back X-Nexus-Proof:
"sha256:" + base64url_no_padding( sha256("nexus-endpoint-proof-v1\n" + correlationId + "\n" + timestamp + "\n" + signatureHeader)) where signatureHeader is the full X-Nexus-Signature value, including the ed25519: prefix.
Why does this exist? Because "the endpoint returned 200" isn't evidence that your server handled the call: a misconfigured load balancer or a cached error page can return 200 too. The proof shows that something holding the request actually parsed it. A 2xx without a valid proof is never billed — the developer isn't charged and you aren't paid.
In Go
package main import ( "crypto/ed25519" "crypto/sha256" "crypto/subtle" "encoding/base64" "encoding/hex" "encoding/json" "io" "net/http" "os" "strconv" "strings" "time" ) var ( registeredHost = os.Getenv("NEXUS_REGISTERED_HOST") // e.g. tools.example.com creatorKey = os.Getenv("NEXUS_CREATOR_KEY") // your nx_crt_… key publicKeys = parseKeys(os.Getenv("NEXUS_PUBLIC_KEY")) ) func parseKeys(csv string) []ed25519.PublicKey { var keys []ed25519.PublicKey for _, s := range strings.Split(csv, ",") { raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(s)) if err == nil && len(raw) == ed25519.PublicKeySize { keys = append(keys, ed25519.PublicKey(raw)) } } return keys } func isDigits(s string) bool { return s != "" && strings.Trim(s, "0123456789") == "" } // verify checks a gateway-signed request and returns the proof to send back. func verify(r *http.Request, body []byte) (string, bool) { sigHeader := r.Header.Get("X-Nexus-Signature") ts := r.Header.Get("X-Nexus-Timestamp") corr := r.Header.Get("X-Correlation-ID") // The publish-time hello has an empty body and no creator key. if len(body) > 0 { got := sha256.Sum256([]byte(r.Header.Get("X-Nexus-Creator-Key"))) want := sha256.Sum256([]byte(creatorKey)) if subtle.ConstantTimeCompare(got[:], want[:]) != 1 { return "", false } } if !isDigits(ts) { return "", false } sec, _ := strconv.ParseInt(ts, 10, 64) if skew := time.Now().Unix() - sec; skew > 60 || skew < -60 { return "", false } encoded, hasPrefix := strings.CutPrefix(sigHeader, "ed25519:") sig, err := base64.StdEncoding.DecodeString(encoded) if !hasPrefix || err != nil || len(sig) != ed25519.SignatureSize { return "", false } bodyHash := sha256.Sum256(body) canonical := strings.Join([]string{ r.Method, registeredHost, r.RequestURI, ts, corr, hex.EncodeToString(bodyHash[:]), }, "\n") for _, key := range publicKeys { if ed25519.Verify(key, []byte(canonical), sig) { proof := sha256.Sum256([]byte("nexus-endpoint-proof-v1\n" + corr + "\n" + ts + "\n" + sigHeader)) return "sha256:" + base64.RawURLEncoding.EncodeToString(proof[:]), true } } return "", false } func main() { http.HandleFunc("/mcp", func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) if err != nil { http.Error(w, "body too large", http.StatusRequestEntityTooLarge) return } proof, ok := verify(r, body) if !ok { http.Error(w, "unauthorized", http.StatusUnauthorized) return } w.Header().Set("X-Nexus-Proof", proof) // on every response, before WriteHeader if len(body) == 0 { // publish-time hello: just prove you're alive w.WriteHeader(http.StatusOK) return } var req struct { Params struct { Name string `json:"name"` Arguments json.RawMessage `json:"arguments"` } `json:"params"` } if err := json.Unmarshal(body, &req); err != nil { http.Error(w, "bad request", http.StatusBadRequest) // proved 4xx: refunded, not your fault return } // params.name is "handle/server/tool"; dispatch on the last segment. switch req.Params.Name[strings.LastIndex(req.Params.Name, "/")+1:] { case "word_count": var args struct { Text string `json:"text"` } json.Unmarshal(req.Params.Arguments, &args) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]any{ "content": []map[string]any{{"type": "text", "text": strconv.Itoa(len(strings.Fields(args.Text)))}}, }) default: http.Error(w, "unknown tool", http.StatusNotFound) } }) Source:https://dev.to/nischaldhakal/your-mcp-server-costs-money-to-run-heres-how-to-charge-for-it-2pg