
402 Mcp
dev.forgesworn由 forgesworn.dev 發布v3.15.2更新於 Oct 24, 2026
AI agents discover, pay for, and consume any Lightning-gated API autonomously
概覽
L402 用戶端 MCP,讓 AI 代理探索需以閃電網路付費的 API,在限額內自動付款並取得資料。
- 可以做什麼
- 探索與檢視付費 API:在 Nostr 中繼上搜尋 L402 服務,探測端點並預覽價格而不付款
- 付款並取回資料:發出 HTTP 請求,透過 NWC 閃電錢包、Cashu 電子現金、LNURLcash 票據或人工掃碼完成 402 支付
- 管理付款:依付款雜湊支付指定挑戰、核對結果不明的付款、購買 toll-booth 額度方案、兌換 Cashu 代幣
- 檢視狀態:顯示已設定的錢包與限額,列出已儲存憑證與快取餘額
- 互動元件:在支援 MCP Apps 的用戶端中瀏覽服務目錄與錢包面板
- 適用情境
- 適合讓代理呼叫按次計費、以閃電網路或電子現金結算的 API,不需人工註冊或 API 金鑰,同時希望自動支出受單筆與滾動總額上限約束的情境。
- 執行需求
- 透過 npx 在本機執行,需要 Node.js 22.4 或更新版本。自動閃電付款需要把 NWC 錢包 URI 放進權限 0600 的私有檔案,並以 NWC_URI_FILE 指向它;Cashu 與 LNURLcash 儲存為選用。需要連線至 Nostr 中繼、錢包的中繼或鑄幣廠,以及所呼叫的付費 API。
安裝
在 SourceWeft 中
- 開啟 儀表板中的 402 Mcp,將其新增到工作區。
- 為需要使用其工具的對話啟用該服務。
Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。
其他 MCP 客戶端
參照 儲存庫 中的啟動說明。
README
402-mcp
Nostr: npub1mgvlrnf5hm9yf0n5mf9nqmvarhvxkc6remu5ec3vf8r0txqkuk7su0e7q2
[MIT licence] [TypeScript] [Node] [Statement coverage 90%, measured with npm run test:coverage] [Nostr] [GitHub Sponsors]
L402 client MCP that gives AI agents economic agency. Discover, pay for, and consume Lightning and ecash payment-gated APIs within limits you set: no human registration, no API keys, no middlemen.
- Discover paid APIs on Nostr, no URLs needed upfront
- Auto-pay with Lightning (NWC), Cashu ecash, LNURLcash bearer notes, or human QR fallback
- Credentials cached and encrypted at rest (AES-256-GCM)
- Works with any L402 server: toll-booth, Aperture, or any future implementation
Quick start
There is no install step: npx fetches 402-mcp when your MCP client first starts it. Running npx 402-mcp by hand only starts a stdio server that waits for a client on standard input (stop it with Ctrl+C), so do that to check it launches, not to use it.
1. Connect it to your MCP client
Claude Code:
Claude Desktop or Cursor, in the MCP configuration file:
2. Try it
Ask Claude: "Search for paid joke APIs using l402-search", no wallet needed, just discovery.
3. Pay for calls (optional): connect an NWC wallet
402-mcp reads the Nostr Wallet Connect URI from a private file, never from an environment variable or a command line. Create the file with owner-only permissions first, then paste the URI into it with an editor so it stays out of your shell history:
The URI comes from your wallet service and looks like this, with your own values in place of the placeholders:
It needs a 64-character hex wallet pubkey, one to eight relay values, one 64-character hex secret, and may carry lud16; any other parameter is rejected. The file must be a regular, non-empty file under 8 KiB, and on macOS and Linux it is refused unless group and other have no permissions (chmod 600). Create the connection with pay_invoice permission and a spending budget (lookup_invoice as well lets l402-reconcile ask the wallet about unknown outcomes). The wallet must support NIP-44 v2 encryption.
Then register 402-mcp with the absolute path ($HOME expands in your shell when you run the command):
For Claude Desktop or Cursor, add an env block to the same server entry. JSON does not expand ~ or $HOME, so write out the absolute path of the file you created:
A raw NWC_URI variable is refused at startup. For Cashu, LNURLcash or no wallet at all, and a first paid call, see the full quickstart guide.
Requires Node.js 22.4 or newer.
How it works
Example session:
Step 5 needs no autoPay: step 4 stored a credential for that server and l402-fetch sends it. Without a stored credential, l402-fetch pays nothing unless autoPay: true is set; it returns the price and a paymentHash instead (see Spending limits).
For detailed architecture and payment flow diagrams, see docs/architecture.md.
Configuration
NWC_URI and HTTP_AUTH_TOKEN are refused at startup: both secrets are read only from their *_FILE variables. The spend caps, MAX_AUTO_PAY_SATS and FETCH_MAX_RETRIES must be non-negative whole numbers; the timeouts, the size limit and the poll interval at least 1; PORT 1 to 65535.
Transport selection and fallback
When a kind 31402 event advertises multiple URLs (one per transport), 402-mcp selects the best one based on your configuration:
- Preference first: URLs are tried in
TRANSPORT_PREFERENCEorder,onion,hns,https,httpby default. Useonion,hns,httpsandhttpas the values; there is no value for anything else. A URL counts ashnswhen its TLD is.hns. One whose TLD is merely unfamiliar (.pub,.fyi) is more likely an ICANN name, so it has no value of its own: it counts as a guessedhnsname and is tried just after whichever ofhnsandhttpscomes later in your order, which is just afterhttpsby default. If you leavehnsout ofTRANSPORT_PREFERENCE, such URLs go last. - Capability filter:
.onionURLs are skipped unlessTOR_PROXYorSOCKS_PROXYis set, so without a proxy the default order starts at HNS and clearnet. - Availability fallback: if a transport is unreachable (connection refused, timeout), the next URL is tried.
Services can announce multiple endpoints for the same service (same pricing, same macaroon key) on different transports. This is purely for censorship resistance; you do not need to re-authenticate when switching transports. .onion endpoints need TOR_PROXY or SOCKS_PROXY. Handshake endpoints need no configuration, because HNS_GATEWAY_URL has a default, except under SOCKS_PROXY, which switches Handshake lookups off (see Tor and SOCKS5).
Credentials across transports. When l402-fetch is given a service's pubkey (from l402-search), it stores and looks up the credential under that pubkey, so one purchase serves every transport URL passed in urls. Without a pubkey the credential is keyed by the request's origin. Either way the credential records the origins it was bought through and is sent only to those, whatever pubkey a later request names. A macaroon bought through a Tor hidden service therefore works on the clearnet URL when both were in urls at purchase, and is never sent to any other host.
Tor and SOCKS5
TOR_PROXYsends.onionrequests through the proxy. Everything else connects directly.SOCKS_PROXYsends every request to a paid API through the proxy, including redirects. Host names are resolved by the proxy, never by this machine, so a Tor proxy hides both your IP and the names you look up. The SSRF guard still refuses private IP literals and local names such aslocalhost; it cannot see what a name resolves to on the far side, which Tor exits refuse for private ranges anyway.
Neither setting covers wallet or discovery traffic: NWC relays, Cashu and LNURLcash mints, and the Nostr relays l402-search queries still connect directly. Handshake lookups are switched off under SOCKS_PROXY, because the DNS-over-HTTPS query would go around the proxy.
SOCKS5 support comes from undici's Socks5ProxyAgent, which Node marks experimental; expect one ExperimentalWarning on stderr when a proxy is configured.
Tools
Core L402 (any server)
Widgets (MCP Apps hosts)
l402-fetch-preview also has a payment confirmation widget.
toll-booth extensions
Arguments and results
* marks a required argument. Every tool replies with JSON text; failures set the MCP isError flag.
Payment methods
Two separate choices decide how a 402 gets paid: which challenge the server sent, and, for a Lightning invoice, which payer pays it.
Payer for a Lightning invoice. An L402 or IETF Payment challenge, l402-pay and l402-buy-credits pay an invoice with the first available payer in this order:
- NWC (Nostr Wallet Connect): fully autonomous; pays from your connected wallet. Available when
NWC_URI_FILEis set. - Cashu: fully autonomous; melts ecash tokens to pay the invoice. Available when the
CASHU_TOKENSstore holds a balance. - LNURLcash: fully autonomous; melts LUD-25 bearer notes to pay the invoice. Available when the
LNURLCASH_NOTESstore holds a balance. - Human-in-the-loop: used only when none of the above is available, or when
method: "human"is passed tol402-payorl402-buy-credits.l402-fetchdoes not wait: it returns the toll-booth payment page URL, or a QR code and invoice, at once. You pay from your own wallet, then the agent callsl402-pay, which polls the toll-booth payment page for up to 120 seconds (or, with no payment page, the server's/invoice-status/<hash>endpoint forHUMAN_PAY_TIMEOUT_Sseconds). Settlement can only be confirmed where the server reports it, which toll-booth does; other L402 servers do not. Whenever the price is aboveMAX_AUTO_PAY_SATSthe human payer does not take over either: the challenge goes back to the agent unpaid.
One payer is chosen per payment and there is no fallback: if it fails, the failure is reported and the next payer is not tried. To use a different payer, pass method (nwc, cashu, lnurlcash or human) to l402-pay, or (nwc, cashu or human) to l402-buy-credits. l402-fetch has no payment-method argument. You can also configure only the methods you want.
Challenge the server sent. l402-fetch handles four HTTP 402 challenge variants, plus an experimental x402 format. When a response carries more than one, it checks them in the order below and uses the first it can act on. Every rail still needs autoPay: true and a price within the limits.
LNURLcash is checked first because a bearer note is already money in hand, so paying one costs no Lightning hop and no swap at the mint: the note goes straight into the retry header and the server settles it. When the price does not match a note exactly, one is split at the mint and the change stays in the store. If no note covers it, or no note store is configured, the remaining challenges in the same response are tried as usual. The LNURLcash payer in the list above is a different path: it melts notes to pay a Lightning invoice.
l402-fetch-preview reports the challenge it finds without paying, and it also names the wallet that would pay (paymentMethod). It checks the challenge types in a different order from l402-fetch (IETF Payment, L402, LNURLcash, xCashu, x402), so for a server that sends several at once the preview may name a different rail from the one l402-fetch uses.
Spending limits
402-mcp checks every automatic payment against these, and the agent can read them with l402-config:
MAX_AUTO_PAY_SATScaps each payment. A dearer challenge is returned to the agent unpaid.0disables auto-pay: every priced challenge goes back to the agent.maxCostSatsonl402-fetchlowers that cap for one call, so the price shown byl402-fetch-previewis binding. It can never raise it.MAX_SPEND_PER_MINUTE_SATSandMAX_SPEND_PER_DAY_SATScap total automatic spend over rolling windows. The daily window is persisted, so restarting the server does not reset it.0in either blocks auto-pay entirely. At the defaults (10,000 per minute, 5,000 per day) the daily cap is the lower one, and spend in any minute also counts towards the day, so the per-minute cap never binds until you lower it or raise the daily cap.- A payment whose outcome is unknown pauses auto-pay to that service until
l402-reconcileresolves it, so the same thing is not bought twice.
The real hard limit is the budget on your NWC connection. Everything above is enforced in software by this process, on the machine it runs on. Most NWC wallets let you set a spending budget when you create the connection; set one, because that is the limit a bug or a misbehaving agent cannot raise. For Cashu and LNURLcash, the hard limit is what you put in the token or note store.
Privacy
402-mcp stores credentials locally on your machine only (~/.402-mcp/credentials.json, encrypted at rest with AES-256-GCM). The encryption key lives in the OS keychain when one is available (the macOS Keychain through the security tool; elsewhere the optional keytar module, which often fails to load on current Node). Otherwise it falls back to a file, ~/.402-mcp/encryption.key, created with 0600 permissions, and 402-mcp warns on startup that the keychain was unavailable; anyone who can read that file can decrypt the store. There are no accounts, no tracking and no analytics, and 402-mcp has no server of its own. It does talk to parties other than the APIs you call:
- Nostr relays.
l402-searchsubscribes to public relays (by default relay.damus.io, relay.primal.net and nos.lol) for service announcements, sending only the topic filter you give it. The payment-method filter and the query text are matched locally, so relays never see them. - A Handshake resolver. When ordinary DNS cannot find a host name, it is looked up at
HNS_GATEWAY_URL(https://query.hdns.io/by default), which therefore sees that name. This is off underSOCKS_PROXY. - Your wallet's services. NWC relays, Cashu mints and LNURLcash mints see the payments you make through them.
Payments use Lightning or ecash, which are pseudonymous rather than anonymous.
Using the modules in code
The package exposes nine subpath imports. Each maps to build/<path>.js with its declaration file beside it, so TypeScript finds the types without a types field:
These are the server's own modules, exposed as they are; read src/ for their signatures. Do not import the package root (402-mcp) from library code: main and the . export both point at the server entry, build/index.js, which loads configuration from the environment and connects a transport as soon as it is imported.
Storage service announcements (Wildbloom)
l402-search also returns storage services announced with the forgesworn-storage-service-v1 profile (kind 31402, validated by 402-announce/storage 2.3.0). Wildbloom is one such service: it offers paid storage, and a free tier called free shelter, which keeps copies pushed by authorised mirrors on a best-effort basis, may evict them, and does not take direct uploads from unknown users.
These results are descriptive only. A paid storage result carries storage.paymentFlow: "wildbloom-checkout-v1" and autoPaySupported: false, and 402-mcp cannot buy it. Do not hand that flow to l402-fetch or l402-pay: both refuse it, and l402-fetch also refuses any /checkout/v1 path, before any network, credential or wallet access. To buy, read the operator's current terms (its /services/v1 listing) and use Wildbloom's own checkout, which asks for a private quote signed with NIP-98 (Nostr HTTP authentication) and an explicit payment from you. Mirroring to free shelter is not something these tools do either. The terms in an announcement are the operator's own claims, not a recommendation or proof of uptime, and a valid signature shows only who published it; it never authorises a purchase.
How results are chosen: search contacts only the relays you name (or the defaults), never a storage node or a wallet. The newest valid signed announcement for each service (same publisher and d tag; on equal timestamps the lowest event ID) is selected before expiry, withdrawal and query filters apply. So that a relay replaying an older copy cannot revive a withdrawn or expired offer, the newest record seen for each service is kept in memory as a watermark: up to 2,000 per search handler, kept across calls until the server restarts, and a search that would exceed that fails with an error rather than dropping any. A fresh server has no watermarks, so it cannot know about a record a relay leaves out. Full or paused listings that are still current remain in the results; expired and withdrawn ones stay as watermarks but are not returned. Discovery stores nothing on disk and opens no browser.
Ecosystem
Browse live L402 services at 402.pub, the decentralised marketplace for payment-gated APIs.
402-mcp is the wallet-provider agnostic alternative to Lightning Labs' lightning-agent-tools: no Lightning node required, multiple wallets, encrypted credentials.
Full comparison
The Lightning Labs spend-safety cell comes from the lnget documentation in lightning-agent-tools: --max-cost sets the most lnget will auto-pay for a single request (docs/l402-and-lnget.md), and that page documents no budget across requests. The other cells in that column are not sourced here.
Use Lightning Labs' tools if you want agents that run their own Lightning node. Use 402-mcp if you want agents that pay from any wallet without infrastructure.
See CONTRIBUTING.md for development setup and guidelines.
Built by @forgesworn.
- Lightning tips:
[email protected] - Nostr:
npub1mgvlrnf5hm9yf0n5mf9nqmvarhvxkc6remu5ec3vf8r0txqkuk7su0e7q2
Part of the ForgeSworn Toolkit
ForgeSworn builds open-source cryptographic identity, payments, and coordination tools for Nostr.
Licence
來源:README.md,提交 fc1f3da
工具
0版本歷史
1- v3.15.2最新Sep 16, 2026
評分
已滿足適用檢查項的 50%
該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。
- 近 30 天內可連通25 分
請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。
- 已宣告認證方式10 分
請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。
- 已列出工具15 分
請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。
- 描述必需15 分
- 圖示10 分
- 文件15 分
- 授權條款10 分