Tollbooth Sample

io.github.lonniev由 GitHub 帳號 lonniev 發布v0.5.0更新於 Nov 4, 2026

Educational Weather Stats MCP Service — Tollbooth DPYC monetization sample

已驗證Streamable HTTP可網頁執行位置與生活金融開發者工具

概覽

AI 產生的概覽

一個範例天氣統計 MCP 服務,包裝 Open-Meteo,並依每次呼叫以比特幣閃電網路點數計費,用來示範 Tollbooth DPYC 變現機制。

可以做什麼
  • 依經緯度查詢目前天氣、多日預報與歷史天氣
  • 查詢點數餘額、透過閃電網路購買點數並查看發票狀態
  • 在花費點數前預覽工具價格與限制規則的影響
  • 申請由 Authority 接納,並取得 DPYC 入門說明、稅率、成員與網路公告資訊
  • 查看服務健康狀態與限制設定
適用情境
適合想端到端體驗具付費機制的 MCP 服務,或把它當成範本,將自家 API 包裝成 Tollbooth DPYC 付費工具。若只是查天氣,免費的 Open-Meteo API 更簡單。
執行需求
透過 streamable HTTP 存取的遠端端點,需要 OAuth 登入。付費工具需要以比特幣閃電網路購買的點數餘額,以及連線可證明持有的 Nostr 金鑰對(npub);在本機 STDIO 模式下付費工具會被拒絕。
安裝前請注意
天氣呼叫會扣除以比特幣閃電網路購買的真實點數,使用工具會產生費用,建議先預覽價格。身分採用 Nostr 金鑰對而非帳號,營運方密鑰如 BTCPay 主機、API 金鑰與商店 ID 透過 Secure Courier 流程處理。它是參考範例,並非正式營運的天氣服務。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Tollbooth Sample,將其新增到工作區。
  2. 連接 所需的 憑證。它們會被私密儲存,絕不會在公開頁面上展示。
  3. 為需要使用其工具的對話啟用該服務。

Web executable,透過 Streamable HTTP。 遠端服務在工作區中設定後即可從網頁執行環境執行。

交給代理程式安裝

把這段提示詞貼上到 Claude Code、Codex、Cursor 等代理程式,或 SourceWeft 對話中。代理程式會讀取該伺服器的安裝指南,先向你展示發布者、端點和登入方式,經你同意後再把它新增到你的客戶端。金鑰不會寫進任何命令。

閱讀 https://sourceweft.com/mcp/io.github.lonniev%2Ftollbooth-sample/install.md,並按其中說明把這個 MCP 伺服器接入我的客戶端。修改任何設定之前,先告訴我它的發布者、端點和登入方式,等我確認。不要把 API 金鑰寫進命令或我會提交的檔案;問我金鑰應從哪裡取得。

檢視代理程式所依據的安裝指南

其他 MCP 客戶端

把它新增到你客戶端的 mcpServers 設定中。 客戶端會在首次連接時完成 OAuth 登入。

{
  "mcpServers": {
    "tollbooth-sample": {
      "type": "http",
      "url": "https://tollbooth-sample.fastmcp.app/mcp"
    }
  }
}

README

tollbooth-sample

Educational Weather Stats MCP Service — the reference implementation for building Tollbooth DPYC monetized API services with Bitcoin Lightning micropayments.

This service wraps the free Open-Meteo weather API and gates paid tool calls through the Tollbooth credit system using the @runtime.paid_tool() decorator. Domain tools contain only business logic; debit, rollback, balance warnings, and constraint evaluation are handled automatically by the OperatorRuntime. Standard DPYC tools (balance, purchase, Secure Courier, Oracle, pricing, constraints) are delegated to the wheel via register_standard_tools().

Build your own operator — the bootstrap-dpyc-operator skill

This repo doubles as a Claude Code plugin. The bootstrap-dpyc-operator skill turns your existing REST API, stdio MCP, or HTTP MCP into a monetized DPYC Operator MCP: it clones this template live, wraps your domain logic, and generates a deploy-ready project. You keep writing business logic — the SDK handles payments, identity, vault, audit, and pricing.

Install it in Claude Code:

/plugin marketplace add lonniev/tollbooth-sample/plugin install bootstrap-dpyc-operator@tollbooth-dpyc

Then ask Claude to "make my API a paid DPYC operator" — the skill activates automatically by its description. It never touches your original code (it emits a sibling <slug>-mcp/ project) and reads this repo's live wheel pin on every run, so it can't go stale.

See skills/bootstrap-dpyc-operator/ for the skill and its reference guides (canonical pattern, source adapters, sessions & vaults, onboarding checklist).

The DPYC Economy

DPYC stands for Don't Pester Your Customer. It's a philosophy and protocol for API monetization that eliminates mid-session payment popups, subscription nag screens, and KYC friction.

How it works

  1. Pre-funded balances — Users buy credits via Bitcoin Lightning before using tools. Each tool call silently debits from their balance. No interruptions, no "please upgrade" modals.

  2. Nostr keypair identity — Users are identified by a Nostr public key (npub), not an email or password. One keypair per role, managed by the user. No account creation forms.

  3. UUID-keyed tool identity — Every tool is a ToolIdentity object with a deterministic UUID v5 derived from a capability name. Pricing hints come from the category field:

    CategoryPricing hintUse case
    free0 satsBalance checks, status
    read1 satSimple lookups
    write5 satsMulti-step operations
    heavy10 satsExpensive queries

    Actual prices are set dynamically by the operator's pricing model in Neon.

  4. Rollback on failure — If the downstream API fails after a debit, credits are automatically rolled back via a compensating tranche. The user never pays for a failed call.

  5. Social Contract — The DPYC ecosystem is a voluntary community bound by transparent, auditable economic rules, with a Certification Chain that cascades trust from the root:

    • Citizens — Users who consume API services
    • Operators — Developers who run MCP services (like this one)
    • Authorities — Certify operators and collect a small tax on purchases
    • First Curator — The root of the chain, mints the initial cert-sat supply

How Tollbooth Monetization Works

ToolIdentity and the frozen tool_id

Each domain tool is registered as a ToolIdentity with a frozen tool_id (an opaque UUID), a capability name, a category (pricing hint), and an intent description. Mint the UUID once at the tool's birth — run capability_uuid("get_current_weather") at a REPL (or uuid.uuid4()), then paste the result as a literal constant and never change it again. Freezing the literal is what lets you rename a capability later without orphaning its pricing rows in Neon. Do not call capability_uuid(...) at runtime; the identity must live in exactly one place:

python
from tollbooth.tool_identity import ToolIdentity, STANDARD_IDENTITIESfrom tollbooth.runtime import OperatorRuntime, register_standard_toolsfrom tollbooth.credential_templates import CredentialTemplate, FieldSpecfrom tollbooth.credential_validators import validate_btcpay_creds
# Frozen UUIDs — minted once at tool birth, never recomputed.GET_CURRENT_WEATHER_UUID    = "b7327eb8-92b4-5252-84e0-ba3f437a16ed"GET_WEATHER_FORECAST_UUID   = "b6d0e596-3aec-5a62-980b-7875aa04d079"GET_HISTORICAL_WEATHER_UUID = "5608f3e9-44c4-5b28-9744-704af6d701f0"
# 1. Define domain tool identities_DOMAIN_TOOLS = [    ToolIdentity(        tool_id=GET_CURRENT_WEATHER_UUID,        capability="get_current_weather",        category="read",        intent="Get current weather conditions",    ),    ToolIdentity(        tool_id=GET_WEATHER_FORECAST_UUID,        capability="get_weather_forecast",        category="write",        intent="Get weather forecast",    ),    ToolIdentity(        tool_id=GET_HISTORICAL_WEATHER_UUID,        capability="get_historical_weather",        category="heavy",        intent="Get historical weather data",    ),]
TOOL_REGISTRY: dict[str, ToolIdentity] = {ti.tool_id: ti for ti in _DOMAIN_TOOLS}

The @runtime.paid_tool() decorator

Every paid tool is a single decorator away from full DPYC monetization. The decorator takes the tool's frozen tool_id constant and handles debit, balance checks, constraint evaluation, rollback on failure, and low-balance warnings automatically. Your tool function contains only domain logic:

python
from typing import Anyfrom fastmcp import FastMCPfrom tollbooth.params import PatronNpub
mcp = FastMCP("tollbooth-sample", ...)
# Create the runtime with merged standard + domain identitiesruntime = OperatorRuntime(    tool_registry={**STANDARD_IDENTITIES, **TOOL_REGISTRY},    operator_credential_template=CredentialTemplate(        service="tollbooth-sample-operator",        version=2,        description="Operator credentials for BTCPay Lightning payments",        fields={            "btcpay_host": FieldSpec(required=True, sensitive=True, ...),            "btcpay_api_key": FieldSpec(required=True, sensitive=True, ...),            "btcpay_store_id": FieldSpec(required=True, sensitive=True, ...),        },    ),    credential_validator=validate_btcpay_creds,    # Connections prove the patron's npub (NIP-98 signed requests or an    # OAuth holder connection) against this host.    holder_auth_url="https://tollbooth-sample.fastmcp.app",    ...)
# Delegate all standard DPYC tools to the wheel.# register_standard_tools returns the slug-prefixed @tool decorator —# use it for the operator's own paid tools below.tool = register_standard_tools(mcp, "weather", runtime, ...)
# Decorate each paid domain tool@tool@runtime.paid_tool(GET_CURRENT_WEATHER_UUID)async def current(    latitude: float,    longitude: float,    npub: PatronNpub = "",) -> dict[str, Any]:    """Get current weather conditions for a location.
    Returns temperature, wind speed, and weather code from Open-Meteo.    """    return await weather.get_current(latitude, longitude)

That is the complete paid tool. No manual debit calls, no try/except rollback blocks, no balance-warning plumbing. The decorator:

  • Looks up the tool's pricing from the ToolIdentity registry by UUID
  • Extracts npub from the function arguments for billing
  • Checks that the connection proves that npub (a signed request, or an OAuth connection that holds it)
  • Debits before calling your function (walking the tool's constraint chain from the pricing model)
  • Rolls back automatically if your function raises an exception
  • Appends a low-balance warning to the response when funds are running low

Key patterns

register_standard_tools(mcp, "weather", runtime, …) — Registers all standard DPYC tools (balance, purchase, payment, pricing, Secure Courier, Oracle, constraints) from the tollbooth-dpyc wheel, mounts oracle delegations under <slug>_oracle_*, and returns the slug-prefixed @tool decorator. Capture the return so you can use the same decorator for your own paid tools — every wire-exposed name on this operator then shares one slug prefix.

validate_btcpay_creds — Credential validator that checks BTCPay credentials at receive time, not at first use. Invalid credentials are rejected immediately during the Secure Courier exchange.

CredentialTemplate — Declares the operator's required secrets (BTCPay host, API key, store ID) so the Secure Courier flow can prompt for the right fields and validate them on delivery.

The npub parameter

Every paid tool must accept an npub keyword argument. It tells the runtime which patron to bill; the connection proves the caller holds it. Use the SDK's PatronNpub type so every operator describes it the same way:

python
from tollbooth.params import PatronNpub
npub: PatronNpub = ""

A paid tool called with an empty or invalid npub is refused (npub is required) before your function runs.

What the runtime handles under the hood

Tool call arrives    |    v@runtime.paid_tool(GET_CURRENT_WEATHER_UUID)    |    +-- UUID lookup in tool_registry -> ToolIdentity + pricing    +-- npub extraction from kwargs; the connection proves it    |    +-- Constraint chain from the pricing model (discounts, surge, supply caps, coupons)    +-- Balance check + debit    |       |    |       insufficient --> Return error (no function call)    |    +-- Call your function    |       |    |       exception --> Automatic rollback, return error    |    +-- Append low-balance warning if needed    |    vReturn result to caller

Constraint Engine

Constraints are dynamic pricing steps that live in the operator's pricing model: each tool's chain in the model lists the steps the ConstraintGate walks on every call, and coupons bound to the tool are added after them. Author them in Pricing Studio or with weather_set_pricing_model; nothing is switched on by environment variable.

Common constraint types (the SDK registry holds more — weather_list_constraint_types enumerates the full set live):

TypeEffect
free_trialFirst N calls are free
happy_hourDiscount during specific hours
temporal_windowAllow calls only during a time window
finite_supplyCap total invocations globally
loyalty_discountDiscount after spending N sats
bulk_bonusDiscount after N invocations
surge_pricingDemand-elastic multiplier during high demand

Use weather_check_price to preview constraint effects without spending credits — it walks exactly the chain the debit will.

Becoming an Operator

New to Tollbooth? See GETTING-STARTED.md for a step-by-step guide covering Nostr keypair setup, Authority enrollment, BTCPay configuration, and deploying your first monetized MCP service.

Quick Start

Local development

bash
git clone https://github.com/lonniev/tollbooth-sample.gitcd tollbooth-samplepip install -e ".[dev]"python -m tollbooth_sample.server

This serves over STDIO. There is no development bypass: paid tools are gated exactly as in production, and the patron's npub is proven by the HTTP connection (a NIP-98 signed request or an OAuth holder bearer), so over STDIO a paid tool is refused. Exercise paid tools against a deployed instance.

Deploy on Prefect Horizon

The hosting platform is Prefect Horizon (FastMCP is the runtime/framework the server is built on).

  1. Push to GitHub
  2. Connect the repo on Prefect Horizon
  3. Set environment variables:
    • TOLLBOOTH_NOSTR_OPERATOR_NSEC — Nostr key for identity bootstrap (the only env var the operator needs; the Neon database URL arrives from your Authority over Nostr, the relay set comes from the shared dpyc-community registry, and all other secrets are delivered via Secure Courier credential templates)

Horizon reads the entrypoint and dependencies from fastmcp.json.

Heads-up for operators with long-running tools. By default, claim-check / async jobs run in-memory (async_jobs.backend: "memory (default)"), which means they do not survive a Horizon recycle (durable_across_recycles: false). That's fine for this reference sample, which has no long-runners — but if you add a tool that defers work to a background job, pin the tollbooth-dpyc [modal] extra, spread LONGRUNNER_CREDENTIAL_FIELDS into your operator credential template, and deliver the durable-executor secrets (modal_token_id / modal_token_secret / modal_app_name) via Secure Courier so jobs settle across redeploys. Check your live state anytime with service_status.async_jobs.

Run tests

bash
pip install -e ".[dev]"pytest -v

Tool Reference

MCP tool nameCostDescription
weather_currentreadCurrent weather for lat/lon
weather_forecastwriteMulti-day forecast (1-16 days)
weather_historicalheavyHistorical weather for a date range
weather_check_balancefreeCheck credit balance
weather_purchase_creditsfreeBuy credits via Lightning
weather_check_paymentfreeCheck invoice status
weather_request_adoptionfreeRequest adoption by an Authority (deferred-courtship onboarding)
weather_check_pricefreePreview cost (shows constraint effects)
weather_service_statusfreeHealth + constraint config summary
weather_oracle_how_to_joinfreeDPYC onboarding instructions
weather_oracle_get_tax_ratefreeCurrent certification tax rate
weather_oracle_lookup_memberfreeLook up a DPYC member
weather_oracle_aboutfreeDPYC ecosystem description
weather_oracle_network_advisoryfreeActive network advisories

The three weather tools are this operator's own; the rest come from register_standard_tools() and include identity (weather_request_npub_proof, weather_receive_npub_proof), Secure Courier, pricing, coupons, and notarization tools. weather_get_operator_onboarding_status reports what is still missing.

DPYC Ecosystem

Core

Operators

Advocates & utilities

License

Apache-2.0

來源:README.md,提交 8656a22

工具

0
該伺服器需要登入,因此 SourceWeft 無法在沒有帳號的情況下讀取其工具,也未收錄。已連接帳號所能看到的內容可能因帳號及其權限而異。

版本歷史

2
  1. v0.5.0最新Oct 21, 2026
  2. v0.4.9Sep 16, 2026

評分

已滿足適用檢查項的 85%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通必需25 分
  • 已宣告認證方式必需10 分
  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分