微算力 · API 导航与自营网关
API 接入 EN
未登录登录
💳

AI Agent实时变现基础设施

nevermined-payments · vv0.1.0
专业技能 安全 S+ 级 作者 aaitor 公开目录收录
563 下载 154 安装 2.1k 收藏 2.9k 浏览

简介

Nevermined官方支付基础设施集成指南,支持x402协议、信用计费和多框架接入,为AI Agent提供实时变现与访问控制能力。

原始描述

Integrates Nevermined payment infrastructure into AI agents, MCP servers, Google A2A agents, and REST APIs. Handles x402 protocol, credit billing, payment plans, and SDK integration for TypeScript (@nevermined-io/payments) and Python (payments-py).

通过你的 Agent 添加

安装目录:nevermined-payments/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。

点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。

或者手动安装

Claude Code~/.claude/skills/nevermined-payments/
Codex CLI~/.codex/skills/nevermined-payments/
DeepSeek Harness~/.agents/skills/nevermined-payments/

包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可; 目录名不用换,也不要把包直接解压到 skills 根目录。 技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。

中文使用说明 来自收录源

核心用法

Nevermined Payments Skill 是一套完整的支付基础设施集成文档,旨在帮助开发者为 AI Agent、MCP 服务器、Google A2A Agent 及 REST API 添加实时变现能力。其核心基于 x402 支付协议——当客户端未携带有效支付令牌时,服务器返回 HTTP 402 状态码并附带支付要求,客户端获取访问令牌后重试请求,服务器验证权限、执行工作负载并结算信用额度。

该 Skill 覆盖六大集成场景:Express.js/FastAPI 中间件保护、Strands Agent 装饰器、MCP 服务器工具注册、Google A2A 协议扩展、通用 HTTP 手动集成以及客户端订阅流程。开发者需先在 nevermined.app 获取 API Key,注册 Agent 和支付计划,然后通过环境变量配置(NVM_API_KEY、NVM_ENVIRONMENT、NVM_PLAN_ID 等),最后根据框架选择对应的中间件或 SDK 方法完成接入。

显著优点

框架覆盖全面:从传统的 Express.js/FastAPI 到新兴的 MCP、Google A2A 协议均有官方支持,降低多技术栈接入门槛。灵活的计费模式:支持固定信用、动态定价(基于请求/响应参数计算)、时间订阅、按量付费及试用等多种计划类型,满足不同业务场景。标准化协议:x402 作为开放标准,使跨平台、跨 Agent 的支付互操作成为可能,尤其支持 Agent-to-Agent 自动结算。完善的开发者体验:提供从环境配置、计划注册、代码集成到故障排查的完整链路,包含详细的决策树和一次性信息收集模板,减少来回沟通成本。

潜在缺点与局限性

第三方依赖锁定:核心功能完全依赖 Nevermined 官方 SDK(@nevermined-io/payments 或 payments-py),若服务中断或政策变更,集成系统受影响。区块链学习成本:涉及 ERC-4337、USDC 结算等概念,对不熟悉 Web3 的开发者存在认知门槛。T3 来源风险:Skill 由个人开发者维护(非 Nevermined 官方组织),长期更新保障存疑,尽管内容为纯文档风险较低。网络与合规限制:支付功能需要连接 Nevermined 网络,对完全离线或受严格金融监管的环境不适用。

适合的目标群体

  • 希望为 AI API 或服务快速添加付费墙的独立开发者和小型团队
  • 构建多 Agent 系统并需要 Agent 间自动结算的架构师(Google A2A 场景)
  • 开发 MCP Server 并希望通过工具调用变现的创作者
  • 已有 Express.js/FastAPI 后端,希望零侵入式添加支付保护的后端工程师

使用风险

性能风险:每次请求需验证 x402 令牌,建议缓存验证结果 5-30 秒,高频场景需评估延迟影响。密钥管理风险:NVM_API_KEY 等敏感信息若泄露,可能导致计划被恶意调用或额度盗刷,必须严格使用环境变量和密钥管理服务。依赖更新风险:SDK 版本迭代可能引入 Breaking Changes,生产环境应锁定版本并建立更新测试流程。结算遗漏风险:若自定义实现时未正确调用 settlePermissions,可能导致服务被调用但信用未扣除,造成收入损失。

技能正文


name: nevermined-payments description: > Integrates Nevermined payment infrastructure into AI agents, MCP servers, Google A2A agents, and REST APIs. Handles x402 protocol, credit billing, payment plans, and SDK integration for TypeScript (@nevermined-io/payments) and Python (payments-py).

Nevermined Payments Integration

Overview

Nevermined provides financial rails for AI agents — real-time monetization, access control, and payments. This skill gives you everything needed to:

  • Protect API endpoints with the x402 payment protocol
  • Charge per-request using credit-based billing
  • Integrate with Express.js, FastAPI, Strands agents, MCP servers, or Google A2A agents
  • Support subscriber-side flows (purchase plans, generate tokens, call protected APIs)
  • Enable agent-to-agent payments via the Google A2A protocol

The x402 protocol uses HTTP 402 responses to advertise payment requirements. Clients acquire an access token and retry the request. The server verifies permissions, executes the workload, then settles (burns credits).

Quick Start Checklist

  1. Get an API key at nevermined.app → Settings → API Keys
  2. Install the SDK (npm install @nevermined-io/payments or pip install payments-py)
  3. Register your agent and plan (via the App UI or programmatically — see references/payment-plans.md)
  4. Add payment protection to your routes/tools (see framework-specific references below)
  5. Test — call without token (expect 402), then with token (expect 200)

Environment Setup

Variable Required Description
NVM_API_KEY Yes Your Nevermined API key (get it at nevermined.app → Settings → API Keys)
NVM_ENVIRONMENT Yes sandbox for testing, live for production
NVM_PLAN_ID Yes The plan ID from registration
NVM_AGENT_ID Sometimes Required for MCP servers and plans with multiple agents
BUILDER_ADDRESS For registration Wallet address to receive payments

.env Template

# Required
NVM_API_KEY=your-api-key-here
NVM_ENVIRONMENT=sandbox
NVM_PLAN_ID=your-plan-id-here

# Required for MCP servers or multi-agent plans
NVM_AGENT_ID=your-agent-id-here

# Required for registration
BUILDER_ADDRESS=0xYourWalletAddress

Prerequisites

  • TypeScript/Express.js: Node.js 18+. Your package.json must include "type": "module" for the @nevermined-io/payments/express subpath import to work.
  • Python/FastAPI: Python 3.9+. Install with pip install payments-py[fastapi] — the [fastapi] extra is required for the middleware.

TypeScript

npm install @nevermined-io/payments
import { Payments } from '@nevermined-io/payments'

const payments = Payments.getInstance({
  nvmApiKey: process.env.NVM_API_KEY!,
  environment: 'sandbox'
})

Python

pip install payments-py
import os
from payments_py import Payments, PaymentOptions

payments = Payments.get_instance(
    PaymentOptions(
        nvm_api_key=os.environ["NVM_API_KEY"],
        environment="sandbox"
    )
)

Core Workflow (All Integrations)

Every Nevermined payment integration follows this 5-step pattern:

  1. Client sends request without a payment token
  2. Server returns 402 with payment-required header (base64-encoded JSON with plan info)
  3. Client acquires x402 token via payments.x402.getX402AccessToken(planId, agentId)
  4. Client retries with payment-signature header containing the token
  5. Server verifies → executes → settles (burns credits), returns response with payment-response header

Framework Decision Tree

Choose the integration that matches your stack:

Framework Language Reference Key Import
Express.js TypeScript/JS references/express-integration.md paymentMiddleware from @nevermined-io/payments/express
FastAPI Python references/fastapi-integration.md PaymentMiddleware from payments_py.x402.fastapi
Strands Agent Python references/strands-integration.md @requires_payment from payments_py.x402.strands
MCP Server TypeScript references/mcp-paywall.md payments.mcp.start() / payments.mcp.registerTool()
Google A2A TS / Python references/a2a-integration.md payments.a2a.start() / payments.a2a.buildPaymentAgentCard()
Any HTTP Any references/x402-protocol.md Manual verify/settle via facilitator API
Client-side TS / Python references/client-integration.md payments.x402.getX402AccessToken()

SDK Quick Reference

TypeScript (@nevermined-io/payments)

// Initialize
const payments = Payments.getInstance({ nvmApiKey, environment })

// Register agent + plan
const { agentId, planId } = await payments.agents.registerAgentAndPlan(
  agentMetadata, agentApi, planMetadata, priceConfig, creditsConfig
)

// Subscriber: order plan and get token
await payments.plans.orderPlan(planId)
const balance = await payments.plans.getPlanBalance(planId)
const { accessToken } = await payments.x402.getX402AccessToken(planId, agentId)

// Server: verify and settle
const verification = await payments.facilitator.verifyPermissions({
  paymentRequired, x402AccessToken: token, maxAmount: BigInt(credits)
})
const settlement = await payments.facilitator.settlePermissions({
  paymentRequired, x402AccessToken: token, maxAmount: BigInt(creditsUsed)
})

// Helpers
import { buildPaymentRequired } from '@nevermined-io/payments'
import { paymentMiddleware, X402_HEADERS } from '@nevermined-io/payments/express'

// MCP server
payments.mcp.registerTool(name, config, handler, { credits: 5n })
const { info, stop } = await payments.mcp.start({ port, agentId, serverName })

// A2A server
const agentCard = payments.a2a.buildPaymentAgentCard(baseCard, { paymentType, credits, planId, agentId })
const server = await payments.a2a.start({ port, basePath: '/a2a/', agentCard, executor })
// A2A client
const client = payments.a2a.getClient({ agentBaseUrl, agentId, planId })
await client.sendMessage("Hello", accessToken)

Python (payments-py)

# Initialize
payments = Payments.get_instance(PaymentOptions(nvm_api_key=key, environment="sandbox"))

# Register agent + plan
result = payments.agents.register_agent_and_plan(
    agent_metadata, agent_api, plan_metadata, price_config, credits_config
)

# Subscriber: order plan and get token
payments.plans.order_plan(plan_id)
balance = payments.plans.get_plan_balance(plan_id)
token_res = payments.x402.get_x402_access_token(plan_id, agent_id)

# Server: verify and settle
verification = payments.facilitator.verify_permissions(
    payment_required=pr, x402_access_token=token, max_amount=str(credits)
)
settlement = payments.facilitator.settle_permissions(
    payment_required=pr, x402_access_token=token, max_amount=str(credits_used)
)

# Helpers
from payments_py.x402.helpers import build_payment_required
from payments_py.x402.fastapi import PaymentMiddleware
from payments_py.x402.strands import requires_payment

# A2A server
from payments_py.a2a.agent_card import build_payment_agent_card
from payments_py.a2a.server import PaymentsA2AServer
agent_card = build_payment_agent_card(base_card, { ... })
server = PaymentsA2AServer.start(agent_card=agent_card, executor=executor, payments_service=payments, port=3005)
# A2A client
client = payments.a2a.get_client(agent_base_url=url, agent_id=agent_id, plan_id=plan_id)

x402 Payment Headers

All x402 v2 integrations use these three HTTP headers:

Header Direction Description
payment-signature Client → Server x402 access token
payment-required Server → Client (402) Base64-encoded JSON with plan requirements
payment-response Server → Client (200) Base64-encoded JSON settlement receipt

The payment-required payload structure:

{
  "x402Version": 2,
  "accepts": [{
    "scheme": "nvm:erc4337",
    "network": "eip155:84532",
    "planId": "<plan-id>",
    "extra": { "agentId": "<agent-id>" }
  }]
}

Payment Plan Types

Nevermined supports several plan types:

  • Credits-based: prepaid balance, deducted per request (most common for APIs)
  • Time-based: access for a fixed duration (e.g., 30 days unlimited)
  • Pay-as-you-go (PAYG): settle in USDC per request, no credit balance
  • Trial: free limited access, one-time claim per user
  • Hybrid: combine credits with time expiry

See references/payment-plans.md for plan registration code.

Common Patterns

Express.js — Fixed credits per route

import { paymentMiddleware } from '@nevermined-io/payments/express'

app.use(paymentMiddleware(payments, {
  'POST /ask': { planId: PLAN_ID, credits: 1 },
  'POST /generate': { planId: PLAN_ID, credits: 5 }
}))

FastAPI — Fixed credits per route

from payments_py.x402.fastapi import PaymentMiddleware

app.add_middleware(
    PaymentMiddleware,
    payments=payments,
    routes={
        "POST /ask": {"plan_id": PLAN_ID, "credits": 1},
        "POST /generate": {"plan_id": PLAN_ID, "credits": 5}
    }
)

Express.js — Dynamic credits based on response

paymentMiddleware(payments, {
  'POST /generate': {
    planId: PLAN_ID,
    credits: (req, res) => {
      const tokens = res.locals.tokenCount || 100
      return Math.ceil(tokens / 100)
    }
  }
})

FastAPI — Dynamic credits based on request

async def calculate_credits(request: Request) -> int:
    body = await request.json()
    max_tokens = body.get("max_tokens", 100)
    return max(1, max_tokens // 100)

app.add_middleware(
    PaymentMiddleware,
    payments=payments,
    routes={"POST /generate": {"plan_id": PLAN_ID, "credits": calculate_credits}}
)

MCP Server — Register tool with paywall

payments.mcp.registerTool(
  "weather.today",
  { title: "Today's Weather", inputSchema: z.object({ city: z.string() }) },
  async (args, extra, context) => ({
    content: [{ type: "text", text: `Weather in ${args.city}: Sunny, 25C` }]
  }),
  { credits: 5n }
)

const { info, stop } = await payments.mcp.start({
  port: 3000,
  agentId: process.env.NVM_AGENT_ID!,
  serverName: "my-server"
})

Strands Agent — Decorator-based payment

from strands import Agent, tool
from payments_py.x402.strands import requires_payment

@tool(context=True)
@requires_payment(payments=payments, plan_id=PLAN_ID, credits=1)
def analyze_data(query: str, tool_context=None) -> dict:
    return {"status": "success", "content": [{"text": f"Analysis: {query}"}]}

agent = Agent(tools=[analyze_data])

Google A2A — Agent server with payment extension

TypeScript
const agentCard = payments.a2a.buildPaymentAgentCard(baseAgentCard, {
  paymentType: "dynamic",
  credits: 1,
  planId: process.env.NVM_PLAN_ID!,
  agentId: process.env.NVM_AGENT_ID!,
})

const server = await payments.a2a.start({
  port: 3005,
  basePath: '/a2a/',
  agentCard,
  executor: new MyExecutor(),
})
Python
from payments_py.a2a.agent_card import build_payment_agent_card
from payments_py.a2a.server import PaymentsA2AServer

agent_card = build_payment_agent_card(base_agent_card, {
    "paymentType": "dynamic",
    "credits": 1,
    "planId": os.environ["NVM_PLAN_ID"],
    "agentId": os.environ["NVM_AGENT_ID"],
})

server = PaymentsA2AServer.start(
    agent_card=agent_card,
    executor=MyExecutor(),
    payments_service=payments,
    port=3005,
    base_path="/a2a/",
)

Google A2A — Client sending a paid task

const client = payments.a2a.getClient({
  agentBaseUrl: 'http://localhost:3005/a2a/',
  agentId: AGENT_ID,
  planId: PLAN_ID,
})

const { accessToken } = await payments.x402.getX402AccessToken(PLAN_ID, AGENT_ID)
const response = await client.sendMessage("Analyze this data", accessToken)

Gathering Developer Information Upfront

When a developer asks you to integrate Nevermined payments, gather ALL required information in a single question before generating code. This avoids multiple back-and-forth interactions.

Ask the developer once for:

  1. Framework: Express.js, FastAPI, MCP server, Strands agent, Google A2A, or generic HTTP?
  2. Routes to protect: Which endpoints need payment protection and how many credits each? (e.g., POST /chat = 1 credit, POST /generate = 5 credits)
  3. Pricing model: Fixed credits per request, or dynamic pricing based on request/response parameters?
  4. Nevermined API Key: Do they already have an NVM_API_KEY? If not, direct them to nevermined.app → Settings → API Keys
  5. Plan ID: Do they already have a NVM_PLAN_ID? If not, do they need a registration script too?
  6. Environment: sandbox (testing) or live (production)?

If they need plan registration, also ask:

  1. Plan name and description: e.g., "Starter Plan — 100 API requests"
  2. Pricing: How much in USDC? (e.g., 10 USDC for 100 credits)
  3. Credits per plan: Total credits included (e.g., 100)
  4. Builder wallet address (BUILDER_ADDRESS): The wallet that receives payments

Example combined prompt to offer the developer:

I need to set up Nevermined payments. Here's my info:

  • Framework: Express.js
  • Routes: POST /chat (1 credit), POST /summarize (3 credits)
  • I need a registration script too
  • Plan: "Starter Plan", 100 credits for 10 USDC
  • Environment: sandbox
  • My API key is in the NVM_API_KEY env var
  • My wallet: 0x1234...

With this information, generate both the registration script and the payment-protected server in a single response.

Agent and Plan Registration

Using the SDK (Recommended)

Register your agent and plan programmatically — see references/payment-plans.md for complete code.

// TypeScript
const { agentId, planId } = await payments.agents.registerAgentAndPlan(
  { name: 'My Agent', description: 'AI service', tags: ['ai'], dateCreated: new Date() },
  { endpoints: [{ POST: 'https://your-api.com/query' }] },
  { name: 'Starter Plan', description: '100 requests for $10', dateCreated: new Date() },
  payments.plans.getERC20PriceConfig(10_000_000n, USDC_ADDRESS, process.env.BUILDER_ADDRESS!),
  payments.plans.getFixedCreditsConfig(100n, 1n)
)
# Python
result = payments.agents.register_agent_and_plan(
    agent_metadata={'name': 'My Agent', 'description': 'AI service', 'tags': ['ai']},
    agent_api={'endpoints': [{'POST': 'https://your-api.com/query'}]},
    plan_metadata={'name': 'Starter Plan', 'description': '100 requests for $10'},
    price_config=get_erc20_price_config(10_000_000, USDC_ADDRESS, os.environ['BUILDER_ADDRESS']),
    credits_config=get_fixed_credits_config(100, 1)
)

Using the Nevermined App (No-Code)

  1. Go to nevermined.app and sign in
  2. Click "My agents" → register a new agent with metadata and endpoints
  3. Create a payment plan: set pricing, credits, and duration
  4. Link the plan to your agent and publish
  5. Copy the agentId and planId for your .env file

Using the CLI

# 1. Install CLI
npm install -g @nevermined-io/cli

# 2. Configure (use sandbox for testing)
nvm config init --api-key "$NVM_API_KEY" --environment sandbox

# 3. Register agent and plan together
nvm agents register-agent-and-plan \
  --agent-metadata '{"name":"My Agent","description":"AI service"}' \
  --agent-api '{"endpoints":[{"POST":"https://your-api.com/query"}]}' \
  --plan-metadata '{"name":"Starter Plan","description":"100 requests"}' \
  --price-config '{"tokenAddress":"0x036CbD53842c5426634e7929541eC2318f3dCF7e","price":10000000,"amountOfCredits":100}' \
  --credits-config '{"minCreditsRequired":1,"minCreditsToCharge":1,"maxCreditsToCharge":10}'

# 4. List your plans
nvm plans get-plans

# 5. As a subscriber: order a plan and get an x402 token
nvm plans order-plan $PLAN_ID
nvm x402token get-x402-access-token $PLAN_ID --agent-id $AGENT_ID

# 6. Test against your running server
curl -X POST http://localhost:3000/chat \
  -H "Content-Type: application/json" \
  -H "payment-signature: $TOKEN" \
  -d '{"message": "Hello"}'

Troubleshooting

Symptom Cause Fix
HTTP 402 returned No payment-signature header or invalid/expired token Generate a fresh token via getX402AccessToken
MCP error -32003 Payment Required — no token, invalid token, or insufficient credits Check subscriber has purchased plan and has credits remaining
MCP error -32002 Server misconfiguration Verify NVM_API_KEY, NVM_PLAN_ID, and NVM_AGENT_ID are set correctly
verification.isValid is false Token expired, wrong plan, or insufficient credits Re-order the plan or generate a new token
Credits not deducting Settlement not called after request Ensure you call settlePermissions after processing (middleware does this automatically)
payment-required header missing Server not returning 402 properly Use buildPaymentRequired() helper or framework middleware

Additional Resources

正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。

标签

payapibackendautomationproduct-managementdevelopment-engineering

同类 Skill