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 Extension · 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초

차지백(환불)

가능

불가능 — 암호학적 증명

계정 필요

예

아니요 — 모든 라이트닝 지갑

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은 단방향 함수이므로 프리이미지를 위조할 수 없습니다.

  • 차지백 없음 — 암호학적 정산 방식이며, 카드 인증처럼 취소할 수 없습니다.

  • 재전송 방지 — 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