mcpField
M
monetize-service

monetize-service

github.com/coinbase開発1272.9k 回インストール12 週間前に更新
リポジトリ

monetize-service について

x402プロトコルでリクエストごとにUSDCを課金するExpress APIを構築するスキルです。サービス運営者向けに、決済ミドルウェア、エンドポイントの価格設定、Bazaarへの登録を扱います。

主な機能

  1. 01Express決済ミドルウェア
  2. 02エンドポイント別のUSDC価格設定
  3. 03BaseとBase Sepoliaに対応
  4. 04x402 Bazaarへの登録

活用シーン

  1. 01APIリクエストへの課金
  2. 02エージェント向けエンドポイントの公開

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/coinbase/agentic-wallet-skills --skill monetize-service

インストール後、Claude Code で/monetize-serviceを入力して読み込まれたか確認します。

詳細

x402 決済サーバーを構築する

x402 決済プロトコルを使用して、API アクセスに USDC を課金する Express サーバーを作成します。呼び出し元は Base 上でリクエストごとに USDC を支払います。アカウント、API キー、サブスクリプションは不要です。x402 Bazaar を通じて、他のエージェントからサービスが自動的に検出されます。

仕組み

x402 は HTTP ネイティブの決済プロトコルです。クライアントが支払いなしで保護されたエンドポイントにアクセスすると、サーバーは決済要件を含む HTTP 402 を返します。クライアントは USDC 決済に署名し、決済ヘッダーを付けて再試行します。ファシリテーターが決済を検証して確定すると、サーバーはレスポンスを返します。他のエージェントがサービスを自動的に検出して決済できるよう、サービスを x402 Bazaar に登録します。

ウォレットが初期化され、認証済みであることを確認する

npx [email protected] status

ウォレットが認証されていない場合は、authenticate-wallet スキルを参照してください。

ステップ 1:決済先アドレスを取得する

決済を受け取るウォレットアドレスを取得するには、次を実行します。

npx [email protected] address

このアドレスを payTo の値として使用します。

ステップ 2:プロジェクトをセットアップする

mkdir x402-server && cd x402-server
npm init -y
npm install express @x402/express @x402/core @x402/evm @x402/extensions

index.js を作成します。

const express = require("express");
const { paymentMiddleware } = require("@x402/express");
const { x402ResourceServer, HTTPFacilitatorClient } = require("@x402/core/server");
const { ExactEvmScheme } = require("@x402/evm/exact/server");

const app = express();
app.use(express.json());

const PAY_TO = "<address from step 1>";

// Create facilitator client and x402 resource server
const facilitator = new HTTPFacilitatorClient({ url: "https://x402.org/facilitator" });
const server = new x402ResourceServer(facilitator);
server.register("eip155:8453", new ExactEvmScheme());

// x402 payment middleware — protects routes below
app.use(
  paymentMiddleware(
    {
      "GET /api/example": {
        accepts: {
          scheme: "exact",
          price: "$0.01",
          network: "eip155:8453",
          payTo: PAY_TO,
        },
        description: "Description of what this endpoint returns",
        mimeType: "application/json",
      },
    },
    server,
  ),
);

// Protected endpoint
app.get("/api/example", (req, res) => {
  res.json({ data: "This costs $0.01 per request" });
});

app.listen(3000, () => console.log("Server running on port 3000"));

ステップ 3:実行する

node index.js

curl でテストします。決済要件を含む 402 レスポンスが返されるはずです。

curl -i http://localhost:3000/api/example

API リファレンス

paymentMiddleware(routes, server)

x402 決済を強制する Express ミドルウェアを作成します。

パラメーター型説明
routesobjectルートパターンと決済設定を対応付けるルート設定
serverx402ResourceServer事前設定済みの x402 リソースサーバーインスタンス
x402ResourceServer

ファシリテータークライアントを使用して作成します。ミドルウェアに渡す前に、決済スキームと拡張機能を登録します。

const { x402ResourceServer, HTTPFacilitatorClient } = require("@x402/core/server");
const { ExactEvmScheme } = require("@x402/evm/exact/server");

const facilitator = new HTTPFacilitatorClient({ url: "https://x402.org" });
const server = new x402ResourceServer(facilitator);
server.register("eip155:8453", new ExactEvmScheme());
メソッド説明
register(network, scheme)CAIP-2 ネットワーク識別子に対して決済スキームを登録します
ルート設定

routes オブジェクトの各キーは "METHOD /path" です。値には設定オブジェクトを指定します。

{
  "GET /api/data": {
    accepts: {
      scheme: "exact",
      price: "$0.05",
      network: "eip155:8453",
      payTo: "0x...",
    },
    description: "Human-readable description of the endpoint",
    mimeType: "application/json",
    extensions: {
      ...declareDiscoveryExtension({
        output: {
          example: { result: "example response" },
          schema: {
            properties: {
              result: { type: "string" },
            },
          },
        },
      }),
    },
  },
}
accepts 設定フィールド

accepts フィールドには、単一のオブジェクトまたは配列(複数の決済オプション用)を指定できます。

フィールド型説明
schemestring決済スキーム:"exact"
pricestringUSDC 価格(例:"$0.01"、"$1.00")
networkstringCAIP-2 ネットワーク識別子(例:"eip155:8453")
payTostringUSDC 決済を受け取る Ethereum アドレス(0x...)
ルートレベルのフィールド
フィールド型説明
acceptsobject or array決済要件(単一または複数)
descriptionstring?このエンドポイントの機能(クライアントに表示されます)
mimeTypestring?レスポンスの MIME タイプ
extensionsobject?拡張機能の設定(例:Bazaar 検出)
検出拡張機能

declareDiscoveryExtension 関数は、他のエージェントがエンドポイントを検出できるよう、x402 Bazaar に登録します。

const { declareDiscoveryExtension } = require("@x402/extensions/bazaar");

extensions: {
  ...declareDiscoveryExtension({
    output: {
      example: { /* example response body */ },
      schema: {
        properties: {
          /* JSON schema of the response */
        },
      },
    },
  }),
}
フィールド型説明
output.exampleobjectエンドポイントのレスポンス本文の例
output.schemaobjectレスポンス形式を記述する JSON スキーマ
対応ネットワーク
ネットワーク説明
eip155:8453Base メインネット(実際の USDC)
eip155:84532Base Sepolia テストネット(テスト用 USDC)

パターン

価格の異なる複数のエンドポイント
app.use(
  paymentMiddleware(
    {
      "GET /api/cheap": {
        accepts: {
          scheme: "exact",
          price: "$0.001",
          network: "eip155:8453",
          payTo: PAY_TO,
        },
        description: "Inexpensive data lookup",
      },
      "GET /api/expensive": {
        accepts: {
          scheme: "exact",
          price: "$1.00",
          network: "eip155:8453",
          payTo: PAY_TO,
        },
        description: "Premium data access",
      },
      "POST /api/query": {
        accepts: {
          scheme: "exact",
          price: "$0.25",
          network: "eip155:8453",
          payTo: PAY_TO,
        },
        description: "Run a custom query",
      },
    },
    server,
  ),
);

app.get("/api/cheap", (req, res) => { /* ... */ });
app.get("/api/expensive", (req, res) => { /* ... */ });
app.post("/api/query", (req, res) => { /* ... */ });
ワイルドカードルート
app.use(
  paymentMiddleware(
    {
      "GET /api/*": {
        accepts: {
          scheme: "exact",
          price: "$0.05",
          network: "eip155:8453",
          payTo: PAY_TO,
        },
        description: "API access",
      },
    },
    server,
  ),
);

app.get("/api/users", (req, res) => { /* ... */ });
app.get("/api/posts", (req, res) => { /* ... */ });
ヘルスチェック(支払い不要)

支払いミドルウェアの前に無料のエンドポイントを登録します:

app.get("/health", (req, res) => res.json({ status: "ok" }));

// Payment middleware only applies to routes registered after it
app.use(paymentMiddleware({ /* ... */ }, server));
app.get("/api/data", (req, res) => { /* ... */ });
本文とディスカバリー拡張機能を使用する POST
app.use(
  paymentMiddleware(
    {
      "POST /api/analyze": {
        accepts: {
          scheme: "exact",
          price: "$0.10",
          network: "eip155:8453",
          payTo: PAY_TO,
        },
        description: "Analyze text sentiment",
        mimeType: "application/json",
        extensions: {
          ...declareDiscoveryExtension({
            output: {
              example: { sentiment: "positive", score: 0.95 },
              schema: {
                properties: {
                  sentiment: { type: "string" },
                  score: { type: "number" },
                },
              },
            },
          }),
        },
      },
    },
    server,
  ),
);

app.post("/api/analyze", (req, res) => {
  const { text } = req.body;
  // ... your logic
  res.json({ sentiment: "positive", score: 0.95 });
});
エンドポイントごとに複数の支払いオプションを設定

同じエンドポイントで複数のネットワークからの支払いを受け付けます:

"GET /api/data": {
  accepts: [
    {
      scheme: "exact",
      price: "$0.01",
      network: "eip155:8453",
      payTo: EVM_ADDRESS,
    },
    {
      scheme: "exact",
      price: "$0.01",
      network: "eip155:84532",
      payTo: EVM_ADDRESS,
    },
  ],
  description: "Data endpoint accepting Base mainnet or testnet",
}
CDP ファシリテーターの使用(認証あり)

Coinbase ファシリテーターを本番環境で使用する場合(メインネットに対応):

npm install @coinbase/x402
const { facilitator } = require("@coinbase/x402");
const { HTTPFacilitatorClient } = require("@x402/core/server");

const facilitatorClient = new HTTPFacilitatorClient(facilitator);
const server = new x402ResourceServer(facilitatorClient);
server.register("eip155:8453", new ExactEvmScheme());

これには、環境変数 CDP_API_KEY_ID と CDP_API_KEY_SECRET が必要です。https://portal.cdp.coinbase.com から取得してください。

pay-for-service スキルでのテスト

サーバーが起動したら、pay-for-service スキルを使って支払いをテストします:

# Check the endpoint's payment requirements
npx [email protected] x402 details http://localhost:3000/api/example

# Make a paid request
npx [email protected] x402 pay http://localhost:3000/api/example

価格設定のガイドライン

ユースケース推奨価格
シンプルなデータ検索$0.001 - $0.01
API プロキシ/エンリッチメント$0.01 - $0.10
計算負荷の高いクエリ$0.10 - $0.50
AI 推論$0.05 - $1.00

チェックリスト

  • npx [email protected] address でウォレットアドレスを取得する
  • express、@x402/express、@x402/core、@x402/evm、@x402/extensions をインストールする
  • ファシリテータークライアントを使用して x402ResourceServer を作成し、eip155:8453 用に ExactEvmScheme を登録する
  • 価格、説明、ディスカバリー拡張機能を指定してルートを定義する(ルートで宣言すると Bazaar に自動登録されます)
  • 保護対象のルートより前に支払いミドルウェアを登録する
  • ヘルス/ステータスのエンドポイントは支払いミドルウェアより前に配置する
  • curl(402 が返ること)と npx [email protected] x402 pay(200 が返ること)でテストする
  • 他のエージェントがサービスを見つけて利用できるよう、サービスを告知する

コメント