Skip to main content
Glama
l402-kit-mcp
by ShinyDapps

l402-kit

为任何 API 添加比特币闪电网络按次付费功能。仅需 3 行代码。

License: MIT Live Demo Tests l402-kit MCP server

▶ 观看端到端演示 — 安装 → 402 → 支付 → 200 OK


实时动态

SDK

版本

下载量

📦 TypeScript · npmjs.com/package/l402-kit

npm

npm total

🐍 Python · pypi.org/project/l402kit

pypi

pypi total

🦀 Rust · crates.io/crates/l402kit

crates

crates dls

🔌 VS Code 扩展 · marketplace

vscode ver

marketplace

🦫 Go · pkg.go.dev

go

go report



🇺🇸 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.

📖 官方文档: 🇺🇸 · 🇧🇷 · 🇪🇸 · 🇨🇳 · 🇮🇳 · 🇸🇦 · 🇫🇷 · 🇩🇪 · 🇷🇺 · 🇯🇵 · 🇮🇹


安装

npm install l402-kit        # TypeScript / Node.js / Express
pip install l402kit         # Python / FastAPI / Flask
go get github.com/shinydapps/l402-kit/go@v1.8.2   # Go / net/http / Chi / Gin
cargo add l402kit           # Rust / axum

AI 智能体 / LLM: 请参阅 llms.txt 获取机器可读的说明。 智能体发现: /.well-known/agent.json · /.well-known/l402.json


Related MCP server: Bitcoin-MCP-Server

面向 AI 智能体

l402-kit 是自主智能体的支付层。智能体无需人工干预即可支付 API 费用。

系统提示词片段 — 将其添加到任何智能体以启用 L402 支付:

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.

智能体 SDK 快速入门:

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 服务器(适用于 Claude Desktop、Cursor 以及任何兼容 MCP 的智能体):

{
  "mcpServers": {
    "l402-kit": {
      "command": "npx",
      "args": ["l402-kit-mcp"],
      "env": { "BLINK_API_KEY": "your-key" }
    }
  }
}

兼容: LangChain · OpenAI Agents · CrewAI · Vercel AI SDK · AutoGPT · 任何 MCP 客户端

协议支持: L402(比特币闪电网络) · x402(USDC/Coinbase)兼容

Powered by L402-Kit


工作原理

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% → ShinyDapps

快速入门

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();
}

在线测试

# 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." }

▶ 尝试交互式演示


为什么不用 Stripe?

Stripe

l402-kit

最低费用

$0.30

< 1 sat (~$0.001)

结算时间

2–7 天

< 1 秒

退款 (Chargebacks)

有

不可能 — 加密证明

需要账户

是

否 — 任何闪电钱包即可

AI 智能体支持

否

是 — 4 个 SDK,原生支持

封锁国家

~50

0 — 默认全球可用

可撤销

是

否 — 收到即最终确认

开源

否

是 — MIT


提供商

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");

自带节点 — 仅需 5 行代码实现 LightningProvider 接口:

import type { LightningProvider } from "l402-kit";

class MyNode implements LightningProvider {
  async createInvoice(amountSats: number) { /* return Invoice */ }
  async checkPayment(paymentHash: string) { /* return boolean */ }
}

安全模型

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 hour
  • 不可伪造 — SHA256 是单向函数;无法伪造原像 (preimage)

  • 无退款 — 加密结算,非可逆的银行卡授权

  • 防重放 — MemoryReplayAdapter(开发环境)或 RedisReplayAdapter(生产环境,多实例)

  • 600+ 自动化测试,覆盖 5 种运行时(TS、Python、Go、Rust、Cloudflare Workers)— 为自主智能体工作流提供生产级可靠性

  • 完全可审计 — MIT 协议,每一行代码均开源


VS Code 扩展

无需离开编辑器,实时监控每一笔 sat 支付。

VS Code Marketplace

  • ⚡ 每个端点的实时支付流

  • 📊 条形图 — 1天 / 7天(免费) · 30天 / 1年 / 全部(Pro 版)

  • 🌍 内置 11 种语言

  • 🎨 亮色 / 暗色 / 自动主题

  • 🔧 零配置 — 只需设置您的闪电地址


获取闪电地址(免费)

在 dashboard.blink.sv 注册 — 免费、无需信用卡、即时开通。 您的地址:yourname@yourdomain.com

其他钱包:Wallet of Satoshi · Phoenix · Zeus · Alby


链接


MIT 协议 — 自由使用,自由构建。

比特币无国界。

由 ShinyDapps ⚡ 构建

文档 · 演示 · VS Code · npm

Available Tools

4 tools
l402_balanceCheck Lightning budgetA
Read-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.

Inputs: no named parameters.

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.

Inputs: url (required), method, body, headers.

l402_set_budgetCheck budget statusA
Read-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.

Inputs: no named parameters.

l402_spending_reportLightning spending reportA
Read-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.

Inputs: no named parameters.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.7/5.0

    Scored across 4 tools

    Disambiguation5/5

    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.

    Naming Consistency4/5

    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.

    Tool Count5/5

    With 4 tools, the server is well-scoped for its purpose: managing an L402 payment session. Each tool is essential and none are extraneous.

    Completeness5/5

    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

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      B
      maintenance
      MCP 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.
      17
      9
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Bitcoin-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.
      49
      209 npm
      2
      MIT