l402-kit-mcp
The l402-kit-mcp server enables AI agents to autonomously interact with Bitcoin Lightning-paid APIs (L402 protocol), handling the full payment flow without human intervention.
l402_fetch: Fetch any URL, including those protected by L402. Automatically detects HTTP 402 responses, pays the Lightning invoice, and retries the request. Supports all HTTP methods (GET, POST, PUT, DELETE, PATCH), custom headers, and request bodies.l402_balance: Check the remaining Lightning budget (in sats) for the current session.l402_spending_report: Get a detailed breakdown of all payments made in the session — total spent, remaining budget, and per-domain expenditures.l402_set_budget: View the current budget configuration (set at startup via theBUDGET_SATSenvironment variable).
Key features: Integrates with Lightning wallets (e.g., Blink, Alby), enforces a configurable satoshi budget to prevent overspend, and is designed specifically for autonomous AI agent use without human intervention.
l402-kit
Add Bitcoin Lightning pay-per-call to any API. 3 lines of code.
▶ Watch end-to-end demo — install → 402 → pay → 200 OK
Live traction
SDK | Version | Downloads |
📦 TypeScript · npmjs.com/package/l402-kit | ||
🐍 Python · pypi.org/project/l402kit | ||
🦀 Rust · crates.io/crates/l402kit | ||
🔌 VS Code Extension · marketplace | ||
🦫 Go · pkg.go.dev |
🇺🇸 Charge for your API in Bitcoin Lightning. 3 lines of code. 🇧🇷 Monetize sua API com Bitcoin Lightning. 3 linhas de código. 🇪🇸 Monetiza tu API con Bitcoin Lightning. 3 líneas de código. 🇨🇳 用 3 行代码,通过比特币闪电网络收费。 🇮🇳 अपने API को Bitcoin Lightning से 3 लाइनों में मोनेटाइज़ करें। 🇸🇦 اكسب من API الخاص بك عبر Bitcoin Lightning. 3 أسطر فقط. 🇫🇷 Monétisez votre API en Bitcoin Lightning. 3 lignes de code. 🇩🇪 Monetarisiere deine API mit Bitcoin Lightning. 3 Zeilen Code. 🇷🇺 Монетизируй свой API через Bitcoin Lightning. 3 строки кода. 🇯🇵 Bitcoin LightningでAPIを3行で収益化。 🇮🇹 Monetizza la tua API con Bitcoin Lightning. 3 righe di codice.
📖 Official docs: 🇺🇸 · 🇧🇷 · 🇪🇸 · 🇨🇳 · 🇮🇳 · 🇸🇦 · 🇫🇷 · 🇩🇪 · 🇷🇺 · 🇯🇵 · 🇮🇹
Install
npm install l402-kit # TypeScript / Node.js / Express
pip install l402kit # Python / FastAPI / Flask
go get github.com/shinydapps/l402-kit/go@v1.10.0 # Go / net/http / Chi / Gin
cargo add l402kit # Rust / axumAI Agents / LLMs: See
llms.txtfor machine-readable instructions. Agent discovery:/.well-known/agent.json·/.well-known/l402.json
Related MCP server: Bitcoin-MCP-Server
For AI Agents
l402-kit is the payment layer for autonomous agents. Agents can pay for APIs without human intervention.
System prompt snippet — add this to any agent to enable L402 payments:
You have access to paid APIs via the L402 protocol.
When you call an API that returns HTTP 402, use the L402Client from l402-kit
to pay automatically with Bitcoin Lightning.
Budget limit: {BUDGET_SATS} sats per session. Never exceed this limit.Agent SDK quickstart:
import { l402Client, buildWallet } from "l402-kit/agent";
const client = l402Client({
wallet: buildWallet(process.env), // auto-detects BLINK_API_KEY or ALBY_TOKEN
budgetSats: 1000,
});
const data = await client.fetch("https://api.example.com/paid-endpoint");MCP Server (for Claude Desktop, Cursor, and any MCP-compatible agent):
{
"mcpServers": {
"l402-kit": {
"command": "npx",
"args": ["l402-kit-mcp"],
"env": { "BLINK_API_KEY": "your-key" }
}
}
}Compatible with: LangChain · OpenAI Agents · CrewAI · Vercel AI SDK · AutoGPT · Any MCP client
Protocol support: L402 (Bitcoin Lightning) · x402 (USDC/Coinbase) compatible
How it works
1. Client calls your API
↓
2. API returns HTTP 402 + BOLT11 invoice + macaroon
↓
3. Client pays (any Lightning wallet, < 1 second, any country)
↓
4. Client sends Authorization: L402 <macaroon>:<preimage>
↓
5. API verifies SHA256(preimage) == paymentHash ✓
↓
6. HTTP 200 OK + your data
── Fee flow (managed mode) ─────────────────────────────────
Payment → 99.7% → your Lightning Address (instant)
→ 0.3% → ShinyDappsQuickstart
TypeScript
import express from "express";
import { l402, AlbyProvider } from "l402-kit";
const app = express();
const lightning = new AlbyProvider(process.env.ALBY_TOKEN!);
app.get("/premium", l402({ priceSats: 100, lightning }), (_req, res) => {
res.json({ data: "Payment confirmed." });
});
app.listen(3000);Python
from fastapi import FastAPI, Request
from l402kit import l402_required
app = FastAPI()
@app.get("/premium")
@l402_required(price_sats=100, owner_lightning_address="you@yourdomain.com")
async def premium(request: Request):
return {"data": "Payment confirmed."}Go
package main
import (
"fmt"
"net/http"
l402kit "github.com/shinydapps/l402-kit/go"
)
func main() {
http.Handle("/premium", l402kit.Middleware(l402kit.Options{
PriceSats: 100,
OwnerLightningAddress: "you@yourdomain.com",
}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, `{"data": "Payment confirmed."}`)
})))
http.ListenAndServe(":8080", nil)
}Rust
use axum::{middleware, routing::get, Router};
use l402kit::{l402_middleware, Options};
use std::sync::Arc;
#[tokio::main]
async fn main() {
let opts = Arc::new(Options::new(100).with_address("you@yourdomain.com"));
let app = Router::new()
.route("/premium", get(|| async { "Payment confirmed." }))
.route_layer(middleware::from_fn_with_state(opts, l402_middleware));
let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
axum::serve(listener, app).await.unwrap();
}Test it live
# Step 1 — triggers 402 + returns invoice
curl http://localhost:3000/premium
# ← { "error": "Payment Required", "invoice": "lnbc1u...", "macaroon": "eyJ..." }
# Step 2 — pay the invoice with any Lightning wallet, then:
curl http://localhost:3000/premium \
-H "Authorization: L402 <macaroon>:<preimage>"
# ← { "data": "Payment confirmed." }Why not Stripe?
Stripe | l402-kit | |
Minimum fee | $0.30 | < 1 sat (~$0.001) |
Settlement time | 2–7 days | < 1 second |
Chargebacks | Yes | Impossible — cryptographic proof |
Requires account | Yes | No — any Lightning wallet |
AI agent support | No | Yes — 4 SDKs, native |
Countries blocked | ~50 | 0 — global by default |
Reversible | Yes | No — final on receipt |
Open source | No | Yes — MIT |
Providers
import { BlinkProvider, OpenNodeProvider, LNbitsProvider } from "l402-kit";
// Blink (recommended — free, instant setup)
const provider = new BlinkProvider(process.env.BLINK_API_KEY!, process.env.BLINK_WALLET_ID!);
// OpenNode (production, custodial)
const provider = new OpenNodeProvider(process.env.OPENNODE_KEY!);
// LNbits (self-hosted)
const provider = new LNbitsProvider(process.env.LNBITS_KEY!, "https://your.lnbits.host");Bring your own node — implement the LightningProvider interface in 5 lines:
import type { LightningProvider } from "l402-kit";
class MyNode implements LightningProvider {
async createInvoice(amountSats: number) { /* return Invoice */ }
async checkPayment(paymentHash: string) { /* return boolean */ }
}Security model
Invoice creation: paymentHash = SHA256(preimage)
Client payment: Lightning Network releases preimage to payer
API verification: SHA256(preimage) == paymentHash ✓
Replay protection: each preimage is marked used — works exactly once
Token expiry: macaroons expire after 1 hourUnforgeable — SHA256 is a one-way function; you cannot fake a preimage
No chargebacks — cryptographic settlement, not reversible card auth
Replay-safe — MemoryReplayAdapter (dev) or RedisReplayAdapter (production, multi-instance)
600+ automated tests across 5 runtimes (TS, Python, Go, Rust, Cloudflare Workers) — production-grade reliability for autonomous agent workflows
Fully auditable — MIT, every line open source
VS Code Extension
Monitor every sat in real-time without leaving your editor.
⚡ Live payment feed per endpoint
📊 Bar chart — 1D / 7D (free) · 30D / 1Y / ALL (Pro)
🌍 11 languages built-in
🎨 Light / dark / auto theme
🔧 Zero config — just set your Lightning Address
Get a Lightning Address (free)
Sign up at dashboard.blink.sv — free, no credit card, instant.
Your address: yourname@yourdomain.com
Other wallets: Wallet of Satoshi · Phoenix · Zeus · Alby
Links
Resource | URL |
📖 Docs (11 languages) | |
📦 npm | |
🐍 PyPI | |
🦫 Go | |
🦀 Rust | |
🔌 VS Code | |
⚡ Lightning | |
🐙 GitHub |
MIT — use freely, build freely.
Bitcoin has no borders.
Built with ⚡ by ShinyDapps
Docs · Demo · VS Code · npm
Available Tools
4 toolsl402_balanceCheck Lightning budgetARead-onlyIdempotent
Returns the remaining Bitcoin Lightning budget for this MCP session. Use this before calling l402_fetch to confirm you have enough sats — avoids wasted attempts when budget is exhausted. Returns: ' sats remaining of total (spent: sats)'. Read-only — does not trigger any payment or side effect. Budget is set at server startup via BUDGET_SATS (default: 1000 sats ≈ $0.60); to increase it, restart the MCP server.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already provide readOnlyHint and idempotentHint. Description adds that it doesn't trigger payment or side effects, and explains budget is set at startup via BUDGET_SATS (default 1000 sats). Adds useful context beyond annotations.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Three sentences: first states main function, second gives usage guidance, third provides return format and budget details. No wasted words, front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
No output schema but description explicitly shows return format. Covers purpose, usage, behavior, and budget configuration. Complete for a simple, param-less tool.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Input schema has no parameters (100% coverage), so description doesn't need to add param info. Baseline 4 for 0 params; description is adequate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states it returns the remaining Lightning budget for the MCP session, specifying the verb 'returns' and resource 'remaining Bitcoin Lightning budget'. It distinguishes from siblings by mentioning usage before l402_fetch.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly says 'Use this before calling l402_fetch to confirm you have enough sats — avoids wasted attempts when budget is exhausted.' Also notes it's read-only with no side effects.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
l402_fetchFetch L402-protected URLA
Fetch a URL that may require a Bitcoin Lightning payment (L402 protocol). Side effect: deducts sats from the session budget when a payment is required — check l402_balance first if budget is limited. Flow: sends request → if 402 received, pays the Lightning invoice (1 attempt) → retries once with payment proof → returns response body as text. Fails with error if: budget is exhausted, URL is unreachable, or the Lightning payment fails. Do NOT use for regular (non-L402) URLs — use a standard fetch tool instead. Do NOT use if l402_balance shows 0 sats remaining.
| Name | Required | Description | Default |
|---|---|---|---|
| url | Yes | The URL to fetch (http or https) | |
| method | No | HTTP method — GET, POST, PUT, DELETE, PATCH. Default: GET | |
| body | No | Request body as string (for POST/PUT requests) | |
| headers | No | Additional HTTP request headers as key-value pairs |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Discloses side effects (deducts sats), detailed flow (request, 402 handling, payment, retry), and failure modes (budget exhaustion, unreachable, payment failure). Annotations only provide readOnlyHint=false, so description fully covers behavioral traits.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Front-loaded with key side effect, concise sentences, well-organized flow and exclusions. No redundant information.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Covers all necessary context: purpose, side effect, prerequisite checks, step-by-step flow, error conditions, and exclusions. Without an output schema, it states the return type ('response body as text'). Complete for an AI agent.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100% with descriptions for all parameters. The description adds no extra parameter-level detail; it focuses on overall behavior. Baseline 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool fetches an L402-protected URL with payment side effects. It distinguishes from siblings by mentioning l402_balance and explicitly says not to use for non-L402 URLs, advising a standard fetch tool instead.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Provides explicit guidance: check l402_balance first if budget limited, do not use if balance is 0, and use standard fetch for regular URLs. Describes the flow and failure conditions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
l402_set_budgetCheck budget statusARead-onlyIdempotent
Returns the session budget cap configured at startup (via BUDGET_SATS env var). Use this to confirm what hard spending limit is in effect — useful at the start of a session before making any API calls. Read-only: this tool CANNOT set or change the budget at runtime. To raise or lower the cap, stop and restart the MCP server with a different BUDGET_SATS value. For remaining balance during a session, use l402_balance instead.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already provide readOnlyHint and idempotentHint. Description adds that it's read-only, cannot set budget, and details the source env var BUDGET_SATS and immutability during runtime. This adds valuable context beyond annotations.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Description is four sentences, front-loaded with main purpose. Each sentence adds value: purpose, when-to-use, limitation, and sibling reference. No wasted words.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given no parameters, clear annotations, and explicit description of what it returns and limitations, the tool is well-described for an agent. Lacks output format but it's a simple read-only query; still complete enough.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Input schema has no parameters, so schema description coverage is 100% vacuously. Baseline for 0 parameters is 4. Description does not need to add parameter info.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool 'returns the session budget cap configured at startup', uses specific verb 'Returns' and resource 'session budget cap'. It distinguishes from sibling l402_balance which tracks remaining balance.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly says when to use: 'useful at the start of a session before making any API calls'. It also says what not to use for: 'CANNOT set or change the budget', and provides alternative (restart server). Distinguishes from l402_balance for remaining balance.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
l402_spending_reportLightning spending reportARead-onlyIdempotent
Returns a full audit of all Bitcoin Lightning payments made in this MCP session. Includes: total sats spent, remaining budget, sats spent per domain, and chronological transaction list (timestamp + sats + URL). Use this instead of l402_balance when you need to know which APIs were called and how much each cost, not just the remaining balance. Read-only — does not trigger any payment or side effect. Returns '(none yet)' for domains and transactions if no payments have been made this session.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already declare readOnlyHint and idempotentHint true; description reinforces no side effects and adds details about return format for no payments.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Single, well-structured sentence with bullet-like details; front-loaded with purpose.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given zero parameters and no output schema, description fully explains what it returns, when to use, and read-only nature.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
No parameters in schema; baseline 4 per rules. Description adds no parameter info needed.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool returns a full audit of Lightning payments, listing specific fields and distinguishing it from sibling l402_balance.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly tells when to use this tool instead of l402_balance ('when you need to know which APIs were called and how much each cost'), and declares it read-only.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
TDQS
Each tool has a clearly distinct purpose: checking remaining budget, fetching with optional payment, viewing the budget cap, and obtaining a spending audit. There is no overlap in functionality.
All tools share the consistent 'l402_' prefix and use snake_case, but the naming pattern varies between noun (balance, spending_report) and verb (fetch, set_budget). This minor inconsistency prevents a perfect score.
With 4 tools, the server is well-scoped for its purpose: managing an L402 payment session. Each tool is essential and none are extraneous.
The tool set covers all core operations for an L402 session: checking budget, fetching with automatic payment, viewing the budget cap, and auditing spending. There are no obvious gaps.
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Pay-per-action access to APIs and MCP tools over Lightning L402 and Base USDC x402.
L402 MCP: 5 paid BTC/Lightning tools + fiat credits, 10-25 sats/call.
MCP server for Boson Protocol — on-chain agentic commerce for physical & digital goods.
Monetize any MCP server: x402 paywall, pay-per-call billing in USDC on Base, agent marketplace.
Related MCP Servers
AlicenseBqualityDmaintenanceConnects a Bitcoin Lightning wallet to your LLM using Nostr Wallet Connect, enabling payments and interactions with Lightning Network features.113067TypeScriptApache 2.0- AlicenseAqualityCmaintenanceThe first MCP Server dedicated to Bitcoin ecosystem236MIT
- AlicenseAqualityBmaintenanceMCP server that enables AI agents to make autonomous Bitcoin Lightning Network payments using the L402 protocol. Agents can pay for API access, purchase resources, and complete transactions without human intervention — invoice comes in, sats go out, done.179MIT
- AlicenseAqualityCmaintenanceBitcoin-powered AI tools via Lightning Network micropayments (L402). Image generation, text generation, video, music, speech, 3D models, file conversion, and SMS — no signup or API keys required.49801MIT
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/ShinyDapps/l402-kit'
If you have feedback or need assistance with the MCP directory API, please join our Discord server