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, 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:
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, 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 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.
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 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:
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<string, string | undefined>,
body: Buffer,
): string | null {
const sigHeader = headers['x-nexus-signature'] ?? ''
const ts = headers['x-nexus-timestamp'] ?? ''
const corr = headers['x-correlation-id'] ?? ''
if (body.length > 0 && !timingSafeEqual(sha256(headers['x-nexus-creator-key'] ?? ''), sha256(CREATOR_KEY))) return null
if (!/^\d+$/.test(ts) || Math.abs(Date.now() / 1000 - Number(ts)) > 60) return null
if (!sigHeader.startsWith('ed25519:')) return null
const sig = Buffer.from(sigHeader.slice('ed25519:'.length), 'base64')
if (sig.length !== 64) return null
const canonical = [method, REGISTERED_HOST, rawTarget, ts, corr, sha256(body).toString('hex')].join('\n')
if (!PUBLIC_KEYS.some((key) => verify(null, Buffer.from(canonical), key, sig))) return null
return 'sha256:' + sha256(`nexus-endpoint-proof-v1\n${corr}\n${ts}\n${sigHeader}`).toString('base64url')
}
Make sure you hash the raw body bytes. If your framework parses JSON before you see it (Express's express.json(), for example), capture the raw buffer first β re-serialising the parsed object will change the bytes and the signature won't match.
The rule is simple and worth designing around: the first byte is the boundary.
isError: true. You did the work.
Prices are integer micro-dollars, sent as strings: "20000" is $0.02. A few practical guidelines:
"20000" you keep 18000.@v2 to change price.@v1 keep the old price; a large increase is held back from unpinned callers for a week, so nobody's agent gets a surprise.
Payouts go through Stripe Connect. New creators have a holding period before withdrawals that shortens as your account builds a clean history, and payouts launch in a limited set of countries first β check the docs for yours.
| Build it yourself | x402 | Clearinghouse | |
|---|---|---|---|
| Caller setup | Account + key per tool | Funded crypto wallet | One key, one wallet for every tool |
| Money | Fiat, your Stripe | Stablecoins | Fiat, prepaid |
| You build | Keys, balances, top-ups, caps, refunds, payouts | Payment verification | Signature verification |
| Fees | Stripe's | Network + facilitator | Platform fee |
| Best for | A few large customers | Crypto-native users | Reaching many agent developers |
If your tool has two enterprise customers, build it yourself β the code above gets you most of the way. If your users already live on-chain, x402 is elegant. If you want any developer's agent to be able to pay you on the first call without signing up for anything, that's the problem a clearinghouse solves.
Nexus402 opens to the public soon. If you build MCP tools and want to charge for them, join the launch list β you'll get a single email the day it opens.
I'm Nischal, a software engineer in Kathmandu building backend systems in Go. Questions about any of this? Ask in the comments β I read all of them.