Your MCP server costs money to run. Here's how to charge for it. A developer who co-built the Nexus402 payments clearinghouse published a guide to charging for MCP server tool calls, arguing that post-paid metering is the wrong default for agent-driven workloads and that prepaid balances are safer. The approach uses a single atomic Postgres transaction that inserts a charge row keyed by an idempotency key and debits a BIGINT micro-dollar balance guarded by a CHECK constraint, so retries and concurrent calls cannot double-charge or overspend. 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: I'll be upfront: I co-built a clearinghouse, Nexus402 https://nexus402.dev , 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. Before picking an approach, here's the checklist. Every option has to answer all of these somehow: 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. 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. 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: BIGINT , never a float. $0.02 is 20000 . Floats will eventually turn 0.1 + 0.2 into a billing dispute. CHECK balance micro = 0 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: js 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. 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. That's the core, and it's maybe 20% of the job. You still need: 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. x402 https://www.x402.org/ , 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: Choose this when: your users are already crypto-native, or you want permissionless, account-free access more than mainstream adoption. 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 https://nexus402.dev 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 https://nischaldhakal.com.np/blog/billing-ai-agents-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. a-z , 0-9 , and - . You get a creator key nx crt … , shown once. /.well-known/nexus402-challenge/ . 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. initialize , ping , and tools/list itself from your published schema, so your endpoint only ever receives tools/call . If you already run an MCP server built with an SDK, you don't need to rewrite it: the open-source verify-proxy https://github.com/Nexus-402/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. 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: Host header. 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. 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 } } http.ListenAndServe ":8080", nil // terminate TLS on 443 in front of this } A detail worth copying: r.RequestURI is the request target exactly as it arrived. r.URL.RequestURI looks similar but re-encodes the path, and a single re-encoded character breaks the signature. Node needs Ed25519 public keys in SPKI form, so you prefix the raw 32-byte key with a fixed 12-byte DER header: js import { createHash, createPublicKey, timingSafeEqual, verify, type KeyObject } from 'node:crypto' const SPKI PREFIX = Buffer.from '302a300506032b6570032100', 'hex' const REGISTERED HOST = process.env.NEXUS REGISTERED HOST const CREATOR KEY = process.env.NEXUS CREATOR KEY const PUBLIC KEYS: KeyObject = process.env.NEXUS PUBLIC KEY .split ',' .map k = createPublicKey { key: Buffer.concat SPKI PREFIX, Buffer.from k.trim , 'base64' , format: 'der', type: 'spki' } , const sha256 = data: string | Buffer = createHash 'sha256' .update data .digest / Returns the X-Nexus-Proof value for a genuine request, or null. / export function verifyNexus method: string, rawTarget: string, // path + query exactly as received, e.g. req.originalUrl headers: Record