跳转到主要内容
学习指南货币化您的MCP服务器
指南

在10分钟内货币化您的MCP服务器。

10分钟
简短答案

安装@blockchain0x/mcp,在高级工具中,当调用者未支付时调用requirePayment - 它生成一个带有托管结账URL的x402 402挑战,您返回它。一旦payment.received webhook确认结算,您在自己的存储中标记调用者已支付,工具就会运行。免费工具保持免费。对于普通HTTP服务器,接收端x402适配器执行相同的工作。

先决条件

在您开始之前。

  • 一个使用官方 模型上下文协议 SDK 的工作 MCP 服务器,支持 Node 或 Python。如果您还没有,请先使用上游模板搭建一个。
  • 一个 Blockchain0x 账户和一个代理个人资料(请参见 add-payments-to-agent guide 以获取 5 分钟设置)。
  • 一个 API 密钥(使用 sk_test_ 进行本指南)。
  • 一个小型存储以记住谁已付款(数据库行或 Redis 键) - 您的代码拥有此存储,由支付 webhook 更新。
  • 清楚了解您希望收费的工具及每次调用的价格。请参阅 付费 MCP 工具词汇条目 以获取设计模式。
第1步,共4步

安装包。

@blockchain0x/mcp exports requirePayment, a pure function that mints an x402 402 challenge for a tool. It is npm (TypeScript) only. If you run a plain HTTP server instead of an MCP one, install the receive-side x402 adapter and gate routes with it.

安装
# Gate your own MCP tools with the requirePayment 402 builder:
npm install @blockchain0x/mcp

# Or gate a plain HTTP server with the receive-side x402 adapter + SDK:
npm install @blockchain0x/x402 @blockchain0x/node
第2步,共4步

使用requirePayment限制工具。

Inside the tool, check your own paid-state for the caller. If they have not paid, call requirePayment and return the resulting 402 body; if they have, run the work. requirePayment is a pure builder - it does not wrap the handler and does not track payment, so the gating policy stays in your code.

MCP工具(TypeScript)
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { requirePayment } from "@blockchain0x/mcp";
import { z } from "zod";

const server = new McpServer({ name: "premium-data-mcp", version: "1.0.0" });

server.tool(
  "get_quote_realtime",
  "Real-time quote (paid)",
  { ticker: z.string() },
  async ({ ticker }, extra) => {
    if (!hasPaid(extra)) {
      // Pure function: mint an x402 402 challenge and hand the body back.
      const { body } = requirePayment({
        amountUsdc: "0.005",
        payTo: "0xYourWallet",
        hostedUrl: "https://pay.blockchain0x.com/checkout/abc",
      });
      return { content: [{ type: "text", text: JSON.stringify(body) }], isError: true };
    }
    const quote = await fetchLiveQuote(ticker);
    return { content: [{ type: "text", text: JSON.stringify(quote) }] };
  },
);
普通HTTP服务器(接收端x402)
import express from "express";
import { createX402Middleware } from "@blockchain0x/x402/server/express";
import { createClient } from "@blockchain0x/node";

const sdk = createClient({ apiKey: process.env.BLOCKCHAIN0X_API_KEY! });
const app = express();

// Not an MCP server? Gate a plain HTTP route the same way. The middleware
// answers unpaid requests with a 402 and lets paid ones through.
// Configure the price and recipient per the x402 docs.
app.use("/quote", createX402Middleware({ sdk }));

402 主体 requirePayment 返回给未支付的调用者:

// requirePayment returns { status: 402, body }. The body an unpaid caller sees:
{
  "error": "payment_required",
  "amountUsdc": "0.005",
  "payTo": "0xYourWallet",
  "hostedUrl": "https://pay.blockchain0x.com/checkout/abc",
  "network": "mainnet"
}
第3步,共4步

确认支付,然后记住谁支付了。

When a caller pays the checkout, Blockchain0x POSTs a signed payment.received event to your webhook. Verify it with webhooks.verify from @blockchain0x/node, then write the paid state to a store you control - a database row, a Redis key, your call. That store is what the tool checks in Step 2. There is no shipped receipt cache; you own where paid-state lives and how long it lasts.

Webhook 处理程序(TypeScript)
import express from "express";
import { webhooks } from "@blockchain0x/node";

const app = express();
app.use(express.raw({ type: "application/json" }));

app.post("/webhooks/payment", (req, res) => {
  const result = webhooks.verify({
    headers: req.headers,
    rawBody: req.body, // RAW bytes
    secret: process.env.BLOCKCHAIN0X_WEBHOOK_SECRET!,
  });
  if (!result.ok) return res.status(400).json({ code: result.code });

  if (result.eventType === "payment.received") {
    // Remember the payer however you like - a DB row, a Redis key, your call.
    markPaid(result.eventId);
  }
  res.status(200).send("ok");
});

支付授予访问的时间由您决定 - 一次调用、一个会话、一个小时。设置付费状态密钥的过期时间,以匹配您为工具定价的方式。足够长,以便正常会话重用一次支付,足够短,以便限制滥用。

第4步,共4步

部署并验证。

发布服务器。免费工具仍应立即返回其结果;受限工具应在来自新客户端的第一次调用时返回 402 响应体,然后在该调用者被标记为已支付后运行。在上线之前,在 Base Sepolia 上使用 sk_test_ 密钥验证这两个路径。

第一天要关注的两个信号:返回的 402 数量(您的漏斗顶部)和 402 后成功工具运行的数量(您的转化)。如果转化远低于预期,价格可能是错误的。还要关注您的付费状态存储的命中率 - 如果接近零,您的访问窗口太短,付费调用者被要求再次付款。

常见陷阱

五个让首次 MCP 变现者感到困扰的事情。

意外门控免费工具

限制每个工具“以防万一”是很诱人的。不要这样做。付费MCP服务器的全部价值在于免费工具与付费工具共存于同一服务器上,因此客户端可以使用免费的发现和元数据工具而无需支付。仅对实际消耗高级资源的工具生成402;将其余工具保留为普通结果。

requirePayment 是构建器,而不是中间件

requirePayment 是一个纯函数:当工具未付费时调用它,它返回 { status: 402, body },您将主体返回。它不会包装您的处理程序,也不会跟踪谁付款。它接受 amountUsdc、payTo、hostedUrl 和一个可选的网络和描述 - 仅此而已。调用者是否已付款是您在自己的商店中运行的检查。

没有提供收据缓存

Blockchain0x 提供 402 构建器和结算 webhook,而不是收据存储助手。你决定“这个调用者已支付”存储在哪里 - 数据库行、Redis 键、单个进程的内存映射 - 当 payment.received webhook 到达时你翻转它。这将政策(支付授予访问的时间)完全掌握在你手中。

信任客户声称拥有的收据

不要让调用者声称已支付。真实来源是 payment.received webhook,通过 webhooks.verify(或文档中的 HMAC)与您的 webhook 密钥进行验证。仅在经过验证的事件后标记付款人已支付,并在该服务器端状态上对工具进行门控 - 永远不要基于客户端发送的内容。

没有付费工具延迟的指标

在客户端和工具执行之间添加支付步骤会增加调用者在第一次调用时支付和结算所需的时间,然后在你标记他们为已支付后几乎为零。对两个分支进行仪器化,以便在客户投诉时能够区分“工具慢”和“支付慢”。没有指标你将错误诊断瓶颈。

下一步

一旦付费流量开始流动。

在实现货币化后,最有用的后续工作是可靠的 webhook 处理(以便您不会错过支付事件)、支出控制(以便您构建的 MCP 服务器也能支付其他代理)以及优先使用测试网的流程(以便您可以在不烧钱的情况下发布定价更改)。

完整API参考见docs.blockchain0x.com。相关产品表面:MCP集成

最后审查时间:2026-05-15。根据 CC BY 4.0 发布。

按工具调用收费。

返回402,设置您的价格,接受USDC。免费开始。