Skip to main content

Building Lightning-paid MCP servers

A developer's guide to building Lightning-paid MCP servers: charge AI agents per tool call in Bitcoin sats over Lightning using L402, with code and tests.

Most MCP servers are free. They expose tools, an AI agent calls them, and nobody pays anyone. That works until the tool costs you something to run, a database query, a compute job, a proprietary dataset, an inference call. At that point you need a way to charge for each invocation. A Lightning-paid MCP server is an MCP server that charges a small Bitcoin payment over the Lightning Network for each tool call, so an autonomous agent can pay per request without a credit card, a subscription, or a human in the loop.

This guide walks through what a Lightning-paid MCP server is, why sat-denominated micropayments fit agent traffic so well, and how to build one, either from scratch with the L402 protocol or by gating your tools behind an existing Lightning payment layer. It is written for developers who already know how to ship an MCP server and want to make it earn.

What is a Lightning-paid MCP server?

A Lightning-paid MCP server is an ordinary Model Context Protocol server whose tools require a Lightning Network payment before they return a result. The agent discovers the tool, sees the price, pays a Lightning invoice, and receives the output. The payment doubles as the access credential, so there is no separate login step.

To unpack that, it helps to separate the two halves of the term.

MCP in one paragraph

MCP, the Model Context Protocol, is an open standard for giving AI models access to external tools. Instead of hardcoding API calls into a prompt, you expose capabilities as tools with typed schemas, and the model invokes them when it decides they are useful. An MCP server is just a process that advertises those tools over the protocol. Clients like Claude Code, Cursor, and a growing set of agent frameworks speak MCP natively, so any server you build is immediately reachable by all of them.

What "Lightning-paid" adds

The Lightning Network is Bitcoin's payment layer for fast, cheap, sub-cent transfers. Pairing it with MCP means each tool call can carry a price, denominated in satoshis (the smallest Bitcoin unit, where 100 million sats equal one bitcoin). A "Lightning-paid" tool is one that responds to an unpaid call with a payment challenge instead of data. Pay the invoice, prove it, and the tool runs. The mechanism that wires this together cleanly is L402, which we will get to shortly.

Why charge for an MCP server in sats?

Traditional monetization assumes a human signs up, enters a card, and agrees to a plan. Agents break every one of those assumptions. They cannot complete a checkout form, they cannot read a verification email reliably, and you do not want to issue API keys to millions of short-lived agent sessions. Lightning micropayments solve this in three ways.

First, the price can match the value of a single call. Most agent requests are worth a fraction of a cent: a price quote, a lookup, a summary. Lightning lets you charge 10 sats here, 200 sats there, and never deal with the overhead of a subscription for a caller that might never return.

Second, there is no account to create. The payment is the authentication. An agent that can pay can use the tool, and one that cannot simply does not get a result. That removes the entire signup, billing, and key-rotation surface.

Third, settlement is instant and final. Lightning payments clear in well under a second, so the agent's reasoning loop is not blocked, and you are not carrying invoice-and-collect risk the way you would with monthly billing.

The honest caveat: this model shines for true micropayments, roughly 1 to 1000 sats per call. Price too high and a card or invoice would serve you better. Price too low and routing fees start to matter. Within that band, sat-denominated pricing is hard to beat for machine-to-machine traffic.

The architecture: MCP tools plus L402 gating

L402 (Lightning HTTP 402) is the protocol that makes "pay before you call" work over plain HTTP. It combines the long-dormant HTTP 402 "Payment Required" status code with a Lightning invoice and a Macaroon, a bearer token that can carry caveats such as an expiry or a service scope. For a Lightning-paid MCP server, L402 is the gate that sits between a tool request and the tool's output.

The request, payment, retry flow

The flow has the same shape whether the caller is a browser, a CLI, or an MCP client:

  1. The agent calls a paid tool with no payment attached.
  2. Your server responds with a 402 challenge containing a Lightning invoice and a Macaroon.
  3. The agent pays the invoice and obtains the preimage, a 32-byte cryptographic proof of payment.
  4. The agent retries the call, presenting the Macaroon and the preimage.
  5. Your server verifies that the preimage hashes to the payment hash embedded in the Macaroon, checks the caveats, and runs the tool.

No accounts, no OAuth dance, no webhook reconciliation. One challenge, one payment, one authenticated call.

Where the Lightning node fits

To issue and verify invoices you need access to a Lightning node, or a service that fronts one for you. The node creates the BOLT-11 invoice in step 2 and confirms settlement before you trust the preimage in step 5. You can run your own node (LND, Core Lightning, and others expose the needed APIs), or you can lean on a hosted payment layer so you never touch channel management. The choice is an operational tradeoff, not a protocol one; the L402 flow is identical either way.

Building it step by step

Here is the shape of a Lightning-paid MCP server. The code is illustrative pseudocode, not tied to one SDK, so you can map it onto whatever MCP and Lightning libraries you use.

1. Define your tools

Start with a normal MCP tool definition. Nothing about the schema changes, paid tools look exactly like free ones to the model.

server.tool("summarize_url", {
  description: "Fetch a URL and return a concise summary.",
  inputSchema: { url: { type: "string" } },
}, handleSummarize);

2. Price each tool

Attach a price to the tools that cost you something to run. A small map keeps pricing explicit and auditable.

const PRICES_SATS = {
  summarize_url: 50,
  sentiment: 20,
  price_quote: 10,
};

3. Add the 402 challenge

Wrap your handler so an unpaid call returns a Lightning invoice instead of running. This is the L402 gate.

async function gate(toolName, args, auth) {
  if (!auth) {
    const price = PRICES_SATS[toolName];
    const invoice = await lightning.createInvoice(price, toolName);
    const macaroon = mintMacaroon({ paymentHash: invoice.paymentHash });
    return challenge402(macaroon, invoice.bolt11, price);
  }
  // fall through to verification
}

4. Verify payment and return results

On the retry, confirm the preimage matches the invoice and the Macaroon caveats hold, then run the real handler.

  const { macaroon, preimage } = parseAuth(auth);
  if (!verifyMacaroon(macaroon)) return error("invalid token");
  if (sha256(preimage) !== macaroon.paymentHash) return error("unpaid");
  if (!await lightning.isSettled(macaroon.paymentHash)) return error("unsettled");
  return runTool(toolName, args);

That is the entire server-side contract. Everything else is your normal business logic.

5. Give agents a wallet so they can actually pay

A paid server is only useful if callers can pay it. On the agent side, the cleanest path is to give the agent a Lightning wallet exposed as MCP tools, so paying an invoice is just another tool call in its reasoning loop. The lightning-wallet-mcp package does this:

npm install -g lightning-wallet-mcp

Configured as an MCP server, it hands the agent tools like check_balance, pay_invoice, pay_l402_api, and create_invoice. When your server returns a 402, the agent's wallet detects it, pays from a funded balance, and retries with the proof, all without the agent needing to understand Lightning at all. If you are building both sides, this is the fastest way to a working end-to-end demo.

Using the Lightning Faucet L402 gateway as a shortcut

If you would rather not run a node or hand-roll Macaroon verification, you can put your tools behind an existing Lightning payment layer. Lightning Faucet runs an L402 gateway with dozens of live endpoints in production, and the same gateway can gate your own MCP tools. You paste a URL, set a per-call price, and the gateway handles invoice creation, Macaroon minting, payment verification, and payouts.

A few resources make this concrete. The builder tools area is the starting point for listing a service and wiring up payouts. The public L402 registry lists every live endpoint with its price and capabilities, which is a useful reference for how to describe and price your own tools. And the agent-facing wallet docs show how a caller funds an account and pays automatically.

Because the agents using that gateway already carry funded wallets, listing there means your tool is reachable by callers who can pay it on the first try, which is the part that is hardest to bootstrap on your own.

Pricing and design tips

A few patterns separate servers that earn from servers that frustrate callers.

Price per call, not per token or per minute. Agents reason about discrete tool calls, and a flat per-call price is the easiest thing for them to budget against. Keep prices inside the micropayment band and revisit them as your costs change.

Make price discovery cheap or free. A 402 challenge is itself a free way to learn the price, so let agents probe before committing. Some servers expose a free describe or list tool and charge only for the heavy operations.

Scope your Macaroons. Use caveats to set a sensible expiry and bind a token to the specific tool it paid for. This prevents a paid token from being replayed against a different, more expensive endpoint.

Return structured output. Agents parse JSON far more reliably than prose. Design tool results to be machine-first, with any human-readable text as a secondary field.

Fail loudly and cheaply. If a tool errors after payment, decide your refund policy up front and document it. Silent failures on a paid call erode trust faster than a slightly higher price ever would.

Testing your Lightning-paid MCP server

You do not need an agent to test the payment flow. Any HTTP client will trigger the 402 challenge. Hit an unpaid endpoint and inspect the response:

curl -i https://lightningfaucet.com/api/l402/ping

You will get back a 402 with a WWW-Authenticate: L402 header carrying a Macaroon and a BOLT-11 invoice, plus the price in the JSON body. Pay the invoice with any Lightning wallet, grab the preimage, and replay the request with an Authorization: L402 <macaroon>:<preimage> header. A successful replay returns the tool output. Once that round-trip works by hand, point an MCP client with a funded wallet at the same endpoint and confirm the agent completes the loop without intervention.

For local development, run your Lightning node in regtest or testnet mode so you can mint and settle invoices freely, then switch the node connection to mainnet when you are ready to charge real sats.

Common pitfalls

Trusting the preimage without checking settlement. A preimage proves a payment was made, but always confirm the invoice is actually settled on your node before releasing the result. Verify the hash and the settlement state.

Pricing below the routing-fee floor. If a call costs fewer sats than the network charges to route the payment, you lose money on every success. Keep a sensible minimum.

Charging for failures. If your tool can fail for reasons inside your control, build in a refund or a free retry. Agents that get charged for a 500 will route around you.

Forgetting idempotency. Agents retry. Make sure a retried-but-already-paid call returns the same result rather than demanding a second payment.

Where this fits in the broader agent economy

A Lightning-paid MCP server is one building block in a larger shift: machines transacting with machines, in real time, for tiny amounts. The same rails that let an agent pay 50 sats for a summary also let it stake sats in a prediction market, sit down at a table of sat-denominated multiplayer poker, or claim small rewards from earn surfaces. Lightning Faucet is a Bitcoin and Lightning faucet with games, earn surfaces, prediction markets, and builder tools, and the payment layer underneath all of it is the same one your MCP server would tap into.

For a developer, that means the wallet, the gateway, and the payout machinery already exist. You bring the tool and the price; the sats move themselves.

Frequently asked questions

What is a Lightning-paid MCP server?

It is a Model Context Protocol server whose tools require a small Bitcoin payment over the Lightning Network before they return a result. The agent discovers the tool, sees the price, pays a Lightning invoice, and gets the output, with the payment serving as the access credential so no separate account is needed.

Do I need to run my own Lightning node to build one?

No. You can run your own node (LND, Core Lightning, and others expose invoice and settlement APIs), or you can put your tools behind a hosted L402 gateway that creates invoices, verifies payments, and handles payouts for you. The L402 payment flow is identical either way; running your own node is an operational choice, not a protocol requirement.

How is this different from charging with an API key or subscription?

API keys and subscriptions assume a human signs up, enters a card, and commits to a plan. Agents cannot do that reliably, and you do not want to manage keys for millions of short-lived sessions. With Lightning, the payment is the authentication: an agent that can pay the per-call invoice gets the result, with no signup, billing integration, or key rotation.

What should I charge per tool call?

Price in the micropayment band, roughly 1 to 1000 sats per call, and match the price to the value of a single invocation. Below the routing-fee floor you lose money on each call; far above the band, a traditional invoice or card might serve better. Charge per discrete call rather than per token or per minute, since that is easiest for agents to budget.

How do agents actually pay my server?

The cleanest path is to give the agent a Lightning wallet exposed as MCP tools, such as the lightning-wallet-mcp package. When your server returns a 402 challenge, the agent's wallet detects it, pays the invoice from a funded balance, and retries with the proof of payment, all inside the agent's normal tool-use loop.

How do I test the payment flow without an agent?

Use any HTTP client. Call an unpaid endpoint to receive the 402 challenge, pay the returned BOLT-11 invoice with a Lightning wallet, then replay the request with an Authorization: L402 <macaroon>:<preimage> header. Once that round-trip works by hand, point an MCP client with a funded wallet at the same endpoint and confirm it completes the loop automatically.

Is L402 the only option for paid HTTP and MCP?

No. L402 settles in Bitcoin over Lightning and excels at sub-cent micropayments with instant settlement. Other 402-based approaches settle in stablecoins on other chains and suit larger, dollar-denominated payments. Some platforms support more than one rail and let the caller choose; the protocols are complementary rather than competing.

By the Lightning Faucet team.

Frequently asked questions

What is a Lightning-paid MCP server?

It is a Model Context Protocol server whose tools require a small Bitcoin payment over the Lightning Network before returning a result. The agent discovers the tool, sees the price, pays a Lightning invoice, and gets the output, with the payment serving as the access credential so no separate account is needed.

Do I need to run my own Lightning node to build one?

No. You can run your own node such as LND or Core Lightning, or put your tools behind a hosted L402 gateway that creates invoices, verifies payments, and handles payouts. The L402 flow is identical either way; running your own node is an operational choice, not a protocol requirement.

How is this different from charging with an API key or subscription?

API keys and subscriptions assume a human signs up and enters a card. Agents cannot do that reliably, and you do not want to manage keys for millions of short-lived sessions. With Lightning, the payment is the authentication: an agent that can pay the per-call invoice gets the result, with no signup or billing integration.

What should I charge per tool call?

Price in the micropayment band, roughly 1 to 1000 sats per call, and match the price to the value of a single invocation. Below the routing-fee floor you lose money on each call; far above the band a traditional invoice may serve better. Charge per discrete call rather than per token or per minute.

How do agents actually pay my server?

Give the agent a Lightning wallet exposed as MCP tools, such as the lightning-wallet-mcp package. When your server returns a 402 challenge, the agent's wallet detects it, pays the invoice from a funded balance, and retries with the proof of payment, all inside the agent's normal tool-use loop.

How do I test the payment flow without an agent?

Use any HTTP client. Call an unpaid endpoint to receive the 402 challenge, pay the returned BOLT-11 invoice with a Lightning wallet, then replay the request with an Authorization: L402 macaroon:preimage header. Once that round-trip works by hand, point an MCP client with a funded wallet at the same endpoint.