{"slug": "your-mcp-server-costs-money-to-run-here-s-how-to-charge-for-it", "title": "Your MCP server costs money to run. Here's how to charge for it.", "summary": "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.", "body_md": "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.\n\nAt 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:\n\nI'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.\n\nBefore picking an approach, here's the checklist. Every option has to answer all of these somehow:\n\nThe 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.\n\nYou issue API keys, keep a prepaid balance per customer, and debit it on every call. The core of it is one atomic database statement.\n\n```\nCREATE TABLE accounts (\n  id            BIGSERIAL PRIMARY KEY,\n  api_key_hash  BYTEA  NOT NULL UNIQUE,              -- store a hash, never the key\n  balance_micro BIGINT NOT NULL CHECK (balance_micro >= 0)\n);\n\nCREATE TABLE charges (\n  account_id      BIGINT NOT NULL REFERENCES accounts (id),\n  idempotency_key TEXT   NOT NULL,\n  tool            TEXT   NOT NULL,\n  amount_micro    BIGINT NOT NULL CHECK (amount_micro > 0),\n  status          TEXT   NOT NULL DEFAULT 'charged',  -- charged | refunded\n  created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),\n  PRIMARY KEY (account_id, idempotency_key)\n);\n```\n\nTwo decisions are doing the work here:\n\n`BIGINT`), never a float. `$0.02` is `20000`. Floats will eventually turn `0.1 + 0.2` into a billing dispute.`CHECK (balance_micro >= 0)`\nThe 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:\n\n``` js\nvar ErrInsufficientFunds = errors.New(\"insufficient funds\")\n\n// Debit charges an account once per idempotency key. A retry with the same\n// key is a no-op that reports success without charging again.\nfunc Debit(ctx context.Context, db *sql.DB, accountID int64, key, tool string, price int64) error {\n    tx, err := db.BeginTx(ctx, nil)\n    if err != nil {\n        return err\n    }\n    defer tx.Rollback()\n\n    res, err := tx.ExecContext(ctx, `\n        INSERT INTO charges (account_id, idempotency_key, tool, amount_micro)\n        VALUES ($1, $2, $3, $4)\n        ON CONFLICT (account_id, idempotency_key) DO NOTHING`,\n        accountID, key, tool, price)\n    if err != nil {\n        return err\n    }\n    if n, _ := res.RowsAffected(); n == 0 {\n        return tx.Commit() // already charged for this key: replay, don't double-charge\n    }\n\n    res, err = tx.ExecContext(ctx, `\n        UPDATE accounts SET balance_micro = balance_micro - $2\n        WHERE id = $1 AND balance_micro >= $2`,\n        accountID, price)\n    if err != nil {\n        return err\n    }\n    if n, _ := res.RowsAffected(); n == 0 {\n        return ErrInsufficientFunds // rollback undoes the charge row too\n    }\n    return tx.Commit()\n}\n```\n\nThe `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.\n\nOne 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.\n\nNow the MCP handler debits first, runs the tool, and refunds if *your* side fails:\n\n```\nfunc handleToolCall(w http.ResponseWriter, r *http.Request) {\n    acct, ok := authenticate(r) // look up sha256(api key) in accounts\n    if !ok {\n        http.Error(w, \"unauthorized\", http.StatusUnauthorized)\n        return\n    }\n\n    var req struct {\n        Params struct {\n            Name      string          `json:\"name\"`\n            Arguments json.RawMessage `json:\"arguments\"`\n        } `json:\"params\"`\n    }\n    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n        http.Error(w, \"bad request\", http.StatusBadRequest)\n        return\n    }\n\n    price, known := prices[req.Params.Name] // e.g. \"word_count\": 20000\n    if !known {\n        http.Error(w, \"unknown tool\", http.StatusNotFound)\n        return\n    }\n\n    key := r.Header.Get(\"Idempotency-Key\")\n    if key == \"\" {\n        http.Error(w, \"Idempotency-Key header required\", http.StatusBadRequest)\n        return\n    }\n\n    switch err := Debit(r.Context(), db, acct.ID, key, req.Params.Name, price); {\n    case errors.Is(err, ErrInsufficientFunds):\n        w.WriteHeader(http.StatusPaymentRequired) // 402: top up and try again\n        return\n    case err != nil:\n        http.Error(w, \"unavailable\", http.StatusServiceUnavailable) // fail closed: no debit, no work\n        return\n    }\n\n    result, err := runTool(r.Context(), req.Params.Name, req.Params.Arguments)\n    if err != nil {\n        refund(r.Context(), acct.ID, key) // your failure, their money back\n        http.Error(w, \"tool failed\", http.StatusBadGateway)\n        return\n    }\n    json.NewEncoder(w).Encode(result)\n}\n```\n\nNotice 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.\n\nThat's the core, and it's maybe 20% of the job. You still need:\n\nAnd 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.\n\n**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.\n\n[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.\n\n**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.\n\n**What's hard:**\n\n**Choose this when:** your users are already crypto-native, or you want permissionless, account-free access more than mainstream adoption.\n\nA 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.\n\nThis 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.\n\nNexus402 opens to the public soon, so the details below describe how it works at launch.\n\n`a-z`, `0-9`, and `-`. You get a creator key (` nx_crt_…`), shown once.`/.well-known/nexus402-challenge/`.\nYour 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.\n\n`initialize`, `ping`, and `tools/list` itself from your published schema, so your endpoint only ever receives `tools/call`.\nIf 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.\n\nEvery forwarded call carries these headers:\n\n| Header | Value | \n|---|---|\n| `X-Nexus-Signature` | `ed25519:` followed by a base64 64-byte signature | \n| `X-Nexus-Timestamp` | Unix time in seconds | \n| `X-Correlation-ID` | An opaque ID for this call | \n| `X-Nexus-Creator-Key` | Your `nx_crt_…` key (absent on the publish-time \"hello\") | \n\nThe signature covers six fields joined with single `\\n` characters, with no trailing newline:\n\n```\nPOST\ntools.example.com\n/mcp?region=eu\n1767225600\n3f6c2a1e-…\n9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\n```\n\nThat'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.\n\nThree rules matter more than they look:\n\n`Host` header.\nThe other half is the **proof header**. On *every* response — including errors — you echo back `X-Nexus-Proof`:\n\n```\n\"sha256:\" + base64url_no_padding(\n  sha256(\"nexus-endpoint-proof-v1\\n\" + correlationId + \"\\n\" + timestamp + \"\\n\" + signatureHeader))\n```\n\nwhere `signatureHeader` is the full `X-Nexus-Signature` value, including the `ed25519:` prefix.\n\nWhy 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.\n\n```\npackage main\n\nimport (\n    \"crypto/ed25519\"\n    \"crypto/sha256\"\n    \"crypto/subtle\"\n    \"encoding/base64\"\n    \"encoding/hex\"\n    \"encoding/json\"\n    \"io\"\n    \"net/http\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nvar (\n    registeredHost = os.Getenv(\"NEXUS_REGISTERED_HOST\") // e.g. tools.example.com\n    creatorKey     = os.Getenv(\"NEXUS_CREATOR_KEY\")     // your nx_crt_… key\n    publicKeys     = parseKeys(os.Getenv(\"NEXUS_PUBLIC_KEY\"))\n)\n\nfunc parseKeys(csv string) []ed25519.PublicKey {\n    var keys []ed25519.PublicKey\n    for _, s := range strings.Split(csv, \",\") {\n        raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(s))\n        if err == nil && len(raw) == ed25519.PublicKeySize {\n            keys = append(keys, ed25519.PublicKey(raw))\n        }\n    }\n    return keys\n}\n\nfunc isDigits(s string) bool { return s != \"\" && strings.Trim(s, \"0123456789\") == \"\" }\n\n// verify checks a gateway-signed request and returns the proof to send back.\nfunc verify(r *http.Request, body []byte) (string, bool) {\n    sigHeader := r.Header.Get(\"X-Nexus-Signature\")\n    ts := r.Header.Get(\"X-Nexus-Timestamp\")\n    corr := r.Header.Get(\"X-Correlation-ID\")\n\n    // The publish-time hello has an empty body and no creator key.\n    if len(body) > 0 {\n        got := sha256.Sum256([]byte(r.Header.Get(\"X-Nexus-Creator-Key\")))\n        want := sha256.Sum256([]byte(creatorKey))\n        if subtle.ConstantTimeCompare(got[:], want[:]) != 1 {\n            return \"\", false\n        }\n    }\n\n    if !isDigits(ts) {\n        return \"\", false\n    }\n    sec, _ := strconv.ParseInt(ts, 10, 64)\n    if skew := time.Now().Unix() - sec; skew > 60 || skew < -60 {\n        return \"\", false\n    }\n\n    encoded, hasPrefix := strings.CutPrefix(sigHeader, \"ed25519:\")\n    sig, err := base64.StdEncoding.DecodeString(encoded)\n    if !hasPrefix || err != nil || len(sig) != ed25519.SignatureSize {\n        return \"\", false\n    }\n\n    bodyHash := sha256.Sum256(body)\n    canonical := strings.Join([]string{\n        r.Method, registeredHost, r.RequestURI, ts, corr, hex.EncodeToString(bodyHash[:]),\n    }, \"\\n\")\n\n    for _, key := range publicKeys {\n        if ed25519.Verify(key, []byte(canonical), sig) {\n            proof := sha256.Sum256([]byte(\"nexus-endpoint-proof-v1\\n\" + corr + \"\\n\" + ts + \"\\n\" + sigHeader))\n            return \"sha256:\" + base64.RawURLEncoding.EncodeToString(proof[:]), true\n        }\n    }\n    return \"\", false\n}\n\nfunc main() {\n    http.HandleFunc(\"/mcp\", func(w http.ResponseWriter, r *http.Request) {\n        body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))\n        if err != nil {\n            http.Error(w, \"body too large\", http.StatusRequestEntityTooLarge)\n            return\n        }\n\n        proof, ok := verify(r, body)\n        if !ok {\n            http.Error(w, \"unauthorized\", http.StatusUnauthorized)\n            return\n        }\n        w.Header().Set(\"X-Nexus-Proof\", proof) // on every response, before WriteHeader\n\n        if len(body) == 0 { // publish-time hello: just prove you're alive\n            w.WriteHeader(http.StatusOK)\n            return\n        }\n\n        var req struct {\n            Params struct {\n                Name      string          `json:\"name\"`\n                Arguments json.RawMessage `json:\"arguments\"`\n            } `json:\"params\"`\n        }\n        if err := json.Unmarshal(body, &req); err != nil {\n            http.Error(w, \"bad request\", http.StatusBadRequest) // proved 4xx: refunded, not your fault\n            return\n        }\n\n        // params.name is \"handle/server/tool\"; dispatch on the last segment.\n        switch req.Params.Name[strings.LastIndex(req.Params.Name, \"/\")+1:] {\n        case \"word_count\":\n            var args struct {\n                Text string `json:\"text\"`\n            }\n            json.Unmarshal(req.Params.Arguments, &args)\n            w.Header().Set(\"Content-Type\", \"application/json\")\n            json.NewEncoder(w).Encode(map[string]any{\n                \"content\": []map[string]any{{\"type\": \"text\", \"text\": strconv.Itoa(len(strings.Fields(args.Text)))}},\n            })\n        default:\n            http.Error(w, \"unknown tool\", http.StatusNotFound)\n        }\n    })\n    http.ListenAndServe(\":8080\", nil) // terminate TLS on 443 in front of this\n}\n```\n\nA 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.\n\nNode needs Ed25519 public keys in SPKI form, so you prefix the raw 32-byte key with a fixed 12-byte DER header:\n\n``` js\nimport { createHash, createPublicKey, timingSafeEqual, verify, type KeyObject } from 'node:crypto'\n\nconst SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex')\nconst REGISTERED_HOST = process.env.NEXUS_REGISTERED_HOST!\nconst CREATOR_KEY = process.env.NEXUS_CREATOR_KEY!\nconst PUBLIC_KEYS: KeyObject[] = process.env.NEXUS_PUBLIC_KEY!.split(',').map((k) =>\n  createPublicKey({ key: Buffer.concat([SPKI_PREFIX, Buffer.from(k.trim(), 'base64')]), format: 'der', type: 'spki' }),\n)\n\nconst sha256 = (data: string | Buffer) => createHash('sha256').update(data).digest()\n\n/** Returns the X-Nexus-Proof value for a genuine request, or null. */\nexport function verifyNexus(\n  method: string,\n  rawTarget: string, // path + query exactly as received, e.g. req.originalUrl\n  headers: Record<string, string | undefined>,\n  body: Buffer,\n): string | null {\n  const sigHeader = headers['x-nexus-signature'] ?? ''\n  const ts = headers['x-nexus-timestamp'] ?? ''\n  const corr = headers['x-correlation-id'] ?? ''\n\n  if (body.length > 0 && !timingSafeEqual(sha256(headers['x-nexus-creator-key'] ?? ''), sha256(CREATOR_KEY))) return null\n  if (!/^\\d+$/.test(ts) || Math.abs(Date.now() / 1000 - Number(ts)) > 60) return null\n  if (!sigHeader.startsWith('ed25519:')) return null\n\n  const sig = Buffer.from(sigHeader.slice('ed25519:'.length), 'base64')\n  if (sig.length !== 64) return null\n\n  const canonical = [method, REGISTERED_HOST, rawTarget, ts, corr, sha256(body).toString('hex')].join('\\n')\n  if (!PUBLIC_KEYS.some((key) => verify(null, Buffer.from(canonical), key, sig))) return null\n\n  return 'sha256:' + sha256(`nexus-endpoint-proof-v1\\n${corr}\\n${ts}\\n${sigHeader}`).toString('base64url')\n}\n```\n\nMake 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.\n\nThe rule is simple and worth designing around: **the first byte is the boundary.**\n\n`isError: true`. You did the work.\nPrices are integer micro-dollars, sent as strings: `\"20000\"` is $0.02. A few practical guidelines:\n\n`\"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.\nPayouts 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.\n\n|  | Build it yourself | x402 | Clearinghouse | \n|---|---|---|---|\n| Caller setup | Account + key per tool | Funded crypto wallet | One key, one wallet for every tool | \n| Money | Fiat, your Stripe | Stablecoins | Fiat, prepaid | \n| You build | Keys, balances, top-ups, caps, refunds, payouts | Payment verification | Signature verification | \n| Fees | Stripe's | Network + facilitator | Platform fee | \n| Best for | A few large customers | Crypto-native users | Reaching many agent developers | \n\nIf 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.\n\n**Nexus402 opens to the public soon.** If you build MCP tools and want to charge for them, [join the launch list](https://app.nexus402.dev/?utm_source=devto&utm_medium=referral&utm_campaign=nexus402_launch&utm_content=mcp_charge_post) — you'll get a single email the day it opens.\n\nI'm [Nischal](https://nischaldhakal.com.np), a software engineer in Kathmandu building backend systems in Go. Questions about any of this? Ask in the comments — I read all of them.", "url": "https://wpnews.pro/news/your-mcp-server-costs-money-to-run-here-s-how-to-charge-for-it", "canonical_source": "https://dev.to/nischaldhakal/your-mcp-server-costs-money-to-run-heres-how-to-charge-for-it-2pg", "published_at": "2026-11-22 04:07:59+00:00", "updated_at": "2026-11-22 04:12:16.585266+00:00", "lang": "en", "topics": ["ai-agents", "agent-protocols", "ai-tools", "developer-tools"], "entities": ["Nexus402", "MCP", "Postgres"], "also_reported_by": [], "takeaway": "Debit prepaid balances inside one Postgres transaction using an idempotency key as the charges primary key and a CHECK (balance_micro >= 0) guard, so retries and concurrent calls can't double-charge or spend the last dollar.", "recommendation": {"advice": "Charge MCP tool calls against a prepaid balance in a single atomic transaction keyed by idempotency key, and cache results per key so replays don't rerun expensive tools for free.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/your-mcp-server-costs-money-to-run-here-s-how-to-charge-for-it", "markdown": "https://wpnews.pro/news/your-mcp-server-costs-money-to-run-here-s-how-to-charge-for-it.md", "text": "https://wpnews.pro/news/your-mcp-server-costs-money-to-run-here-s-how-to-charge-for-it.txt", "jsonld": "https://wpnews.pro/news/your-mcp-server-costs-money-to-run-here-s-how-to-charge-for-it.jsonld"}}